Skip to main content

apps/gateway/src/tests/jwt.test.ts

Metadata

Indexed Symbols

  • encodeBase64Url (line 6, function) - Implements encode base64 url for module behavior.
  • buildToken (line 10, function) - Implements build token for module behavior.

Markdown Headings (if applicable)

No markdown headings detected.

Source Preview

import { test } from "node:test";
import assert from "node:assert/strict";
import { createHmac } from "node:crypto";
import { verifyHs256Jwt } from "../utils/jwt.js";

function encodeBase64Url(value: string): string {
return Buffer.from(value, "utf8").toString("base64url");
}

function buildToken(payload: Record<string, unknown>, secret: string): string {
const header = encodeBase64Url(JSON.stringify({ alg: "HS256", typ: "JWT" }));
const body = encodeBase64Url(JSON.stringify(payload));
const signature = createHmac("sha256", secret).update(`${header}.${body}`).digest("base64url");
return `${header}.${body}.${signature}`;
}

test("verifyHs256Jwt validates signature and payload", () => {
const secret = "unit-secret";
const token = buildToken(
{
sub: "user-1",
roles: ["msp_admin"],
workspaceIds: ["*"]
},
secret