Skip to main content

apps/gateway/src/utils/jwt.ts

Metadata

Indexed Symbols

  • base64UrlDecode (line 5, function) - Implements base64 url decode for module behavior.
  • verifySignature (line 14, function) - Implements verify signature for module behavior.
  • verifyHs256Jwt (line 24, function) - Implements verify hs256 jwt for module behavior.

Markdown Headings (if applicable)

No markdown headings detected.

Source Preview

import { createHmac, timingSafeEqual } from "node:crypto";

type JwtPayload = Record<string, unknown>;

function base64UrlDecode(value: string): string {
const normalized = value.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(value.length / 4) * 4, "=");
return Buffer.from(normalized, "base64").toString("utf8");
}

function parseJson<T>(value: string): T {
return JSON.parse(value) as T;
}

function verifySignature(input: string, signature: string, secret: string): boolean {
const expected = createHmac("sha256", secret).update(input).digest("base64url");
const expectedBuf = Buffer.from(expected, "utf8");
const actualBuf = Buffer.from(signature, "utf8");
if (expectedBuf.length !== actualBuf.length) {
return false;
}
return timingSafeEqual(expectedBuf, actualBuf);
}

export function verifyHs256Jwt(token: string, secret: string): JwtPayload {
const parts = token.split(".");