OAuth PKCE and State Generator (core/pkce.ts)

llm-gateway · packages/backend/src/routing/oauth/core/pkce.ts · typescript · MIT
auth, security, lang:typescript, tag:pkce, tag:crypto

Generates cryptographically secure PKCE code verifiers, challenges, and random state strings for OAuth flows. Use this in backend auth services.

// Source: https://github.com/mnfst/llm-gateway | License: MIT | Copyright 2026 MNFST, Inc
// Provided via justclaw.it.com; keep this notice with the code.
import { createHash, randomBytes } from 'crypto';

export interface PkcePair {
  /** Random verifier the client keeps secret until token exchange. */
  verifier: string;
  /** SHA-256(verifier), base64url-encoded — sent on /authorize as code_challenge. */
  challenge: string;
}

export function generatePkce(): PkcePair {
  const verifier = randomBytes(32).toString('base64url');
  const challenge = createHash('sha256').update(verifier).digest('base64url');
  return { verifier, challenge };
}

export function generateState(byteLength = 32): string {
  return randomBytes(byteLength).toString('hex');
}

See the full source, get the GitHub permalink, and search for more like it.

Get a free API key