Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 2 min read

Guardrailing Browser-Based JSON & Schema Converters Against Adversarial Payloads

If you run developer utilities (JSON-to-TypeScript, SQL-to-Zod, JWT decoders, or JSON diff tools) completely client-side in the browser, you solve the privacy problem immediately: production secrets never hit a remote se

If you run developer utilities (JSON-to-TypeScript, SQL-to-Zod, JWT decoders, or JSON diff tools) completely client-side in the browser, you solve the privacy problem immediately: production secrets never hit a remote server.

However, moving computation into the visitor's browser creates a different challenge: how do you stop malformed or adversarial payloads from freezing the user's tab?

When building DevTransform (a 46+ converter suite running purely in the browser), we added a fast linear pre-flight guardrail before running JSON.parse() or recursive interface generation. Here is the exact pattern and why it matters.

The Problem With Naive JSON.parse() on Untrusted Input

A string like [[[[...10,000 nested brackets...]]]] is tiny in byte size, yet deeply nested structures can overwhelm recursive AST builders or type-inference passes.

Instead of catching crashes after calling JSON.parse(), we run an O(n) character-level depth scanner first that tracks string literals and escape characters cleanly without allocating intermediate objects:

export function validateJsonNestingDepth(jsonStr: string, maxDepth: number = 50): void {
  let depth = 0;
  let inString = false;
  let escape = false;

  for (let i = 0; i < jsonStr.length; i++) {
    const ch = jsonStr[i];

    if (escape) {
      escape = false;
      continue;
    }

    if (ch === '\\' && inString) {
      escape = true;
      continue;
    }

    if (ch === '"') {
      inString = !inString;
      continue;
    }

    if (!inString) {
      if (ch === '{' || ch === '[') {
        depth++;
        if (depth > maxDepth) {
          throw new Error(
            `JSON nesting depth exceeds safety threshold (${maxDepth} levels). Flatten deeply nested structures before processing.`
          );
        }
      } else if (ch === '}' || ch === ']') {
        if (depth > 0) depth--;
      }
    }
  }
}

Why Track inString and escape Manually?

A naive regex or bracket counter breaks on valid JSON strings containing literal braces such as "pattern": "{{{value}}}" or escaped quotes \". Tracking inString + escape in a single pass keeps the check both fast and immune to false positives.

Intercepting Before Execution Across All Converters

Every JSON-based tool in our unified dispatcher (json-to-ts, json-to-zod, json-to-prisma, json-diff, json-to-go, json-to-sql) passes through this check before parsing:

export function executeConversion(engineType: string, input: string, options: any = {}): string {
  if (engineType.startsWith('json-') || engineType === 'json-diff') {
    validateJsonNestingDepth(input, 50);
    if (options.jsonB && typeof options.jsonB === 'string') {
      validateJsonNestingDepth(options.jsonB, 50);
    }
  }

  switch (engineType) {
    case 'json-to-ts':
      return jsonToTypeScript(input);
    case 'sql-to-schema':
      return sqlToSchema(input, options.sqlTarget || 'typescript');
    case 'curl-to-code':
      return curlToCode(input, options.curlTarget || 'fetch');
    case 'jwt-decoder':
      return jwtDecoder(input);
    // ...40+ additional client-side converters
  }
}

Handling Edge Cases in Client-Side Code Generation

Once input clears pre-flight validation, generating clean TypeScript interfaces also requires handling real-world API quirks:

  • Unsafe property keys (e.g. first-name, @type, 2fa_enabled): test keys against /^[a-zA-Z_$][a-zA-Z0-9_$]*$/ and quote non-identifiers automatically.
  • CSV parsing (csv-to-json): write an RFC 4180 quote-aware character scanner instead of splitting on , (str.split(',') corrupts any field with commas or escaped "" inside quotes).
  • Zero telemetry: decode JWTs, transform .env configs into Kubernetes Secrets, and convert SQL DDLs into Prisma/Drizzle schemas with zero network calls for payloads.

Try the Zero-Server Toolkit Live

  • DevTransform β€” 46+ instant developer utilities (JSON -> TypeScript / Zod / Prisma / Go / SQL, JWT Decoder, cURL converter, Cron parser, Diff).
  • PDFTransform β€” Our companion 100% browser-side PDF suite (merge, compress, OCR, and edit text in PDF without uploading files).

What pre-flight guardrails or parser edge cases have saved your frontend tools in production? Let's discuss below!

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.