lokalise-security-basics

0
0
Source

Apply Lokalise security best practices for API tokens and access control. Use when securing API tokens, implementing least privilege access, or auditing Lokalise security configuration. Trigger with phrases like "lokalise security", "lokalise secrets", "secure lokalise", "lokalise API token security".

Install

mkdir -p .claude/skills/lokalise-security-basics && curl -L -o skill.zip "https://mcp.directory/api/skills/download/7836" && unzip -o skill.zip -d .claude/skills/lokalise-security-basics && rm skill.zip

Installs to .claude/skills/lokalise-security-basics

About this skill

Lokalise Security Basics

Overview

Security practices for Lokalise integrations: API token management with scoped permissions, translation content sanitization, CI/CD secret handling, webhook secret verification, and audit logging. Lokalise handles translation strings that may contain user-facing content, interpolation variables, and occasionally PII embedded in keys or values.

Prerequisites

  • Lokalise API token provisioned (admin token for audit, scoped tokens for operations)
  • Understanding of Lokalise token permission model (read-only vs read-write)
  • Secret management infrastructure (GitHub Secrets, AWS Secrets Manager, GCP Secret Manager, or Vault)

Instructions

Step 1: Token Scope Management

Lokalise API tokens are either read-only or read-write. Create separate tokens per use case to enforce least privilege.

import { LokaliseApi } from "@lokalise/node-api";

// Token strategy: separate tokens per context
const TOKENS = {
  // CI download pipeline — read-only token
  ciDownload: process.env.LOKALISE_READ_TOKEN,
  // CI upload pipeline — read-write token
  ciUpload: process.env.LOKALISE_WRITE_TOKEN,
  // Admin operations (contributor management, webhooks) — admin token
  admin: process.env.LOKALISE_ADMIN_TOKEN,
} as const;

function getClient(scope: keyof typeof TOKENS): LokaliseApi {
  const token = TOKENS[scope];
  if (!token) {
    throw new Error(
      `LOKALISE_${scope.toUpperCase()}_TOKEN not set. ` +
      `Generate at https://app.lokalise.com/profile#apitokens`
    );
  }
  return new LokaliseApi({ apiKey: token, enableCompression: true });
}

// Download translations — uses read-only token
const readClient = getClient("ciDownload");
const bundle = await readClient.files().download(projectId, {
  format: "json",
  original_filenames: false,
  bundle_structure: "%LANG_ISO%.json",
});

Step 2: Validate Translation Content

Translation strings may contain interpolation variables, HTML, or user-generated content. Validate before rendering.

interface ValidationIssue {
  key: string;
  severity: "critical" | "warning";
  message: string;
}

function validateTranslation(key: string, value: string): ValidationIssue[] {
  const issues: ValidationIssue[] = [];

  // XSS: Check for script injection in translations
  if (/<script|javascript:|on\w+=/i.test(value)) {
    issues.push({ key, severity: "critical", message: "Potential XSS payload" });
  }

  // Credential leak: Check for secrets in translation values
  if (/(api_key|password|secret|token)\s*[:=]/i.test(value)) {
    issues.push({ key, severity: "critical", message: "Possible credential in value" });
  }

  // Placeholder integrity: Ensure ICU/i18next placeholders are well-formed
  const placeholders = value.match(/\{[^}]+\}|\{\{[^}]+\}\}/g) ?? [];
  for (const p of placeholders) {
    if (/[<>'"]/.test(p)) {
      issues.push({ key, severity: "warning", message: `Suspicious placeholder: ${p}` });
    }
  }

  return issues;
}

// Validate all translations after download
import { readFileSync } from "fs";

function auditTranslationFile(filePath: string): ValidationIssue[] {
  const data: Record<string, string> = JSON.parse(
    readFileSync(filePath, "utf-8")
  );
  return Object.entries(data).flatMap(([key, value]) =>
    validateTranslation(key, value)
  );
}

const issues = auditTranslationFile("./src/locales/de.json");
const critical = issues.filter((i) => i.severity === "critical");
if (critical.length > 0) {
  console.error("CRITICAL security issues found in translations:");
  critical.forEach((i) => console.error(`  ${i.key}: ${i.message}`));
  process.exit(1);
}

Step 3: Webhook Secret Verification

Lokalise sends a random alphanumeric secret in the X-Secret header. Always verify it.

import express from "express";

const WEBHOOK_SECRET = process.env.LOKALISE_WEBHOOK_SECRET!;

function verifyWebhookSecret(
  req: express.Request,
  res: express.Response,
  next: express.NextFunction
): void {
  const secret = req.headers["x-secret"] as string | undefined;

  if (!secret || secret !== WEBHOOK_SECRET) {
    console.error("Webhook secret verification failed", {
      ip: req.ip,
      path: req.path,
      hasSecret: !!secret,
    });
    res.status(401).json({ error: "Invalid webhook secret" });
    return;
  }
  next();
}

Step 4: CI/CD Token Security

# GitHub Actions: use repository secrets, never hardcode tokens
name: Sync Translations
on:
  push:
    branches: [main]
    paths: ['src/locales/en.json']

jobs:
  sync:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Pull translations
        env:
          LOKALISE_API_TOKEN: ${{ secrets.LOKALISE_READ_TOKEN }}
          LOKALISE_PROJECT_ID: ${{ vars.LOKALISE_PROJECT_ID }}
        run: |
          # Token is masked in logs by GitHub Actions
          lokalise2 file download \
            --token "$LOKALISE_API_TOKEN" \
            --project-id "$LOKALISE_PROJECT_ID" \
            --format json \
            --original-filenames=false \
            --bundle-structure "%LANG_ISO%.json" \
            --unzip-to ./src/locales/

Step 5: Scan for Hardcoded Tokens

#!/bin/bash
# scripts/scan-secrets.sh — Run in CI or as pre-commit hook
set -euo pipefail

echo "=== Lokalise Token Security Scan ==="

# Check for hardcoded tokens in source files
HARDCODED=$(grep -rn "X-Api-Token\|apiKey.*['\"][a-f0-9]\{32,\}" \
  --include="*.ts" --include="*.js" --include="*.json" --include="*.yml" \
  src/ .github/ 2>/dev/null \
  | grep -v node_modules \
  | grep -v "process.env\|secrets\.\|vars\.\|\${{" || true)

if [[ -n "$HARDCODED" ]]; then
  echo "FAIL: Potential hardcoded token found:"
  echo "$HARDCODED"
  exit 1
fi

# Verify .env files are gitignored
if ! grep -q "\.env" .gitignore 2>/dev/null; then
  echo "WARN: .env not in .gitignore — add it immediately"
fi

# Check git history for leaked tokens
HISTORY_LEAK=$(git log --all -p --diff-filter=A -- '*.env' '*.env.*' 2>/dev/null \
  | grep -i "LOKALISE_API_TOKEN=" | head -3 || true)

if [[ -n "$HISTORY_LEAK" ]]; then
  echo "CRITICAL: Token found in git history. Rotate immediately."
  echo "  Use 'git filter-repo' to remove, then rotate the token."
  exit 1
fi

echo "PASS: No hardcoded tokens detected"

Step 6: Audit Translation Changes

interface TranslationAuditEntry {
  timestamp: string;
  projectId: string;
  key: string;
  locale: string;
  userId: string;
  action: "create" | "update" | "delete";
  // Never log actual content — may contain PII
  oldLength: number;
  newLength: number;
}

function logTranslationChange(entry: TranslationAuditEntry): void {
  // Ship to your logging backend (Datadog, CloudWatch, etc.)
  console.log(JSON.stringify({
    level: "info",
    event: "translation_change",
    ...entry,
  }));
}

Output

  • Scoped token configuration with separate read/write/admin tokens
  • Translation content validator catching XSS, credential leaks, and malformed placeholders
  • Webhook secret verification middleware for Express
  • CI/CD workflow using repository secrets with masked output
  • Pre-commit/CI scan script for hardcoded tokens
  • Audit logging for translation changes (PII-safe)

Error Handling

IssueCauseSolution
Token leaked in CI logsToken in command outputUse env variables; GitHub Actions auto-masks secrets
XSS via translationsUnsanitized translation rendered as HTMLValidate with validateTranslation() before use
Overprivileged accessUsing admin token for read-only operationsCreate scoped tokens per use case
Unauthorized changesNo audit trailRegister webhook for project.translation.updated events
Token in git historyCommitted .env fileRotate token immediately, use git filter-repo to scrub

Resources

Next Steps

For enterprise-level access control with SSO and contributor groups, see lokalise-enterprise-rbac.

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

7824

automating-mobile-app-testing

jeremylongshore

This skill enables automated testing of mobile applications on iOS and Android platforms using frameworks like Appium, Detox, XCUITest, and Espresso. It generates end-to-end tests, sets up page object models, and handles platform-specific elements. Use this skill when the user requests mobile app testing, test automation for iOS or Android, or needs assistance with setting up device farms and simulators. The skill is triggered by terms like "mobile testing", "appium", "detox", "xcuitest", "espresso", "android test", "ios test".

13615

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

3114

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

4311

performing-security-audits

jeremylongshore

This skill allows Claude to conduct comprehensive security audits of code, infrastructure, and configurations. It leverages various tools within the security-pro-pack plugin, including vulnerability scanning, compliance checking, cryptography review, and infrastructure security analysis. Use this skill when a user requests a "security audit," "vulnerability assessment," "compliance review," or any task involving identifying and mitigating security risks. It helps to ensure code and systems adhere to security best practices and compliance standards.

109

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

1128

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

9521,094

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

846846

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

571700

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

548492

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

673466

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

514280

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.