🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(ai-gateway): global enable flag and derived JWT public key / key ID for self-hosting (#19159)
Tobias Wochinger4a8541413b2b
diff --git a/.env.dev.example b/.env.dev.exampleindex c87e9005ba..2761ce8c3a 100644--- a/.env.dev.example+++ b/.env.dev.example@@ -228,6 +228,11 @@ ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000000# AI gateway control-plane key rotation. Generate service keys with# `openssl rand -hex 32` and ES256 PEM keys with# `openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256`.+# Without a public key, Web derives it from the private key (PKCS#8 or SEC1 PEM).+# Without a key ID, Web uses the public key's RFC 7638 JWK thumbprint (the+# previous key ID likewise defaults from the previous public key).+# Set to true to enable the gateway for every organization, ignoring the allowlist.+# LANGFUSE_AI_GATEWAY_ENABLED=false# LANGFUSE_AI_GATEWAY_ORGANIZATION_ID_ALLOWLIST=# LANGFUSE_AI_GATEWAY_SERVICE_KEY=# LANGFUSE_AI_GATEWAY_SERVICE_KEY_PREVIOUS=diff --git a/.env.prod.example b/.env.prod.exampleindex 09b2f7fc43..25716c6de7 100644--- a/.env.prod.example+++ b/.env.prod.example@@ -591,6 +591,15 @@ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true# LANGFUSE_AI_GATEWAY_WEB_URL=https://langfuse.example.com/app# Same shared service key configured in Web. Provider keys are resolved through Web.# LANGFUSE_AI_GATEWAY_SERVICE_KEY=+# Web only: enable the gateway for every organization. When false, only+# organizations in LANGFUSE_AI_GATEWAY_ORGANIZATION_ID_ALLOWLIST can use it.+# LANGFUSE_AI_GATEWAY_ENABLED=false+# Web only: ES256 (P-256) private key, PKCS#8 or SEC1 PEM, that signs gateway+# ingestion tokens. The public key and key ID default to values derived from it.+# Set the key ID on every Web deployment or on none, so all of them agree on it.+# LANGFUSE_AI_GATEWAY_JWT_PRIVATE_KEY=+# LANGFUSE_AI_GATEWAY_JWT_PUBLIC_KEY=+# LANGFUSE_AI_GATEWAY_JWT_KEY_ID=# Largest request body. Each in-flight request reserves a fixed overhead plus its# body from a per-instance memory budget; an exhausted budget returns 503.# LANGFUSE_AI_GATEWAY_MAX_REQUEST_BYTES=16777216diff --git a/web/src/env.mjs b/web/src/env.mjsindex 1dff56790a..2ec3bbda04 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -368,6 +368,9 @@ export const env = createEnv({.optional(),LANGFUSE_AI_GATEWAY_SERVICE_KEY: z.string().min(1).optional(),LANGFUSE_AI_GATEWAY_SERVICE_KEY_PREVIOUS: z.string().min(1).optional(),+ // Enables the gateway for every organization, e.g. on self-hosted+ // deployments. When false, LANGFUSE_AI_GATEWAY_ORGANIZATION_ID_ALLOWLIST applies.+ LANGFUSE_AI_GATEWAY_ENABLED: z.enum(["true", "false"]).default("false"),LANGFUSE_AI_GATEWAY_ORGANIZATION_ID_ALLOWLIST: z.string().optional()@@ -1144,6 +1147,7 @@ export const env = createEnv({process.env.LANGFUSE_AI_GATEWAY_SERVICE_KEY,LANGFUSE_AI_GATEWAY_SERVICE_KEY_PREVIOUS:process.env.LANGFUSE_AI_GATEWAY_SERVICE_KEY_PREVIOUS,+ LANGFUSE_AI_GATEWAY_ENABLED: process.env.LANGFUSE_AI_GATEWAY_ENABLED,LANGFUSE_AI_GATEWAY_ORGANIZATION_ID_ALLOWLIST:process.env.LANGFUSE_AI_GATEWAY_ORGANIZATION_ID_ALLOWLIST,LANGFUSE_AI_GATEWAY_JWT_KEY_ID: process.env.LANGFUSE_AI_GATEWAY_JWT_KEY_ID,diff --git a/web/src/features/ai-gateway/server/auth/gatewayJwtKeys.servertest.ts b/web/src/features/ai-gateway/server/auth/gatewayJwtKeys.servertest.tsnew file mode 100644index 0000000000..de05bc0252--- /dev/null+++ b/web/src/features/ai-gateway/server/auth/gatewayJwtKeys.servertest.ts@@ -0,0 +1,55 @@+import { generateKeyPairSync } from "node:crypto";++import { describe, expect, it } from "vitest";++import { deriveEs256KeyId } from "@/src/server/utils/jwt";++import { resolveGatewayJwtKeys } from "./gatewayJwtKeys";++const keyPair = generateKeyPairSync("ec", { namedCurve: "P-256" });+const publicKeyPem = keyPair.publicKey+ .export({ type: "spki", format: "pem" })+ .toString();+const privateKeyPem = keyPair.privateKey+ .export({ type: "sec1", format: "pem" })+ .toString();++describe("resolveGatewayJwtKeys", () => {+ it("derives the public key and key ID from only a private key", () => {+ expect(+ resolveGatewayJwtKeys({+ privateKey: privateKeyPem,+ publicKey: undefined,+ keyId: undefined,+ }),+ ).toEqual({+ privateKey: privateKeyPem,+ publicKey: publicKeyPem,+ keyId: deriveEs256KeyId(publicKeyPem),+ });+ });++ it("keeps explicitly configured values", () => {+ expect(+ resolveGatewayJwtKeys({+ privateKey: "private",+ publicKey: "public",+ keyId: "current",+ }),+ ).toEqual({ privateKey: "private", publicKey: "public", keyId: "current" });+ });++ it("leaves an unconfigured deployment without keys", () => {+ expect(+ resolveGatewayJwtKeys({+ privateKey: undefined,+ publicKey: undefined,+ keyId: undefined,+ }),+ ).toEqual({+ privateKey: undefined,+ publicKey: undefined,+ keyId: undefined,+ });+ });+});diff --git a/web/src/features/ai-gateway/server/auth/gatewayJwtKeys.ts b/web/src/features/ai-gateway/server/auth/gatewayJwtKeys.tsnew file mode 100644index 0000000000..0ff8c85beb--- /dev/null+++ b/web/src/features/ai-gateway/server/auth/gatewayJwtKeys.ts@@ -0,0 +1,39 @@+import { deriveEs256KeyId, deriveEs256PublicKey } from "@/src/server/utils/jwt";++type GatewayJwtKeyConfig = {+ privateKey: string | undefined;+ publicKey: string | undefined;+ keyId: string | undefined;+};++let cached:+ | { input: GatewayJwtKeyConfig; resolved: GatewayJwtKeyConfig }+ | undefined;++/**+ * Fills in the current ES256 key pair from what is configured: a missing+ * public key is derived from the private key, and a missing key ID defaults+ * to the public key's JWK thumbprint.+ */+export function resolveGatewayJwtKeys(+ input: GatewayJwtKeyConfig,+): GatewayJwtKeyConfig {+ if (+ cached &&+ cached.input.privateKey === input.privateKey &&+ cached.input.publicKey === input.publicKey &&+ cached.input.keyId === input.keyId+ ) {+ return cached.resolved;+ }++ const publicKey =+ input.publicKey ??+ (input.privateKey ? deriveEs256PublicKey(input.privateKey) : undefined);+ const keyId =+ input.keyId ?? (publicKey ? deriveEs256KeyId(publicKey) : undefined);+ const resolved = { privateKey: input.privateKey, publicKey, keyId };++ cached = { input: { ...input }, resolved };+ return resolved;+}diff --git a/web/src/features/ai-gateway/server/auth/ingestionTokenVerifier.servertest.ts b/web/src/features/ai-gateway/server/auth/ingestionTokenVerifier.servertest.tsindex 7624aa023f..cf86605175 100644--- a/web/src/features/ai-gateway/server/auth/ingestionTokenVerifier.servertest.ts+++ b/web/src/features/ai-gateway/server/auth/ingestionTokenVerifier.servertest.ts@@ -1,9 +1,9 @@-import { createHash } from "node:crypto";+import { createHash, generateKeyPairSync } from "node:crypto";import { describe, expect, it, vi } from "vitest";import { signHmacSha256 } from "@/src/server/utils/hmac";-import { createEs256JwtSigner } from "@/src/server/utils/jwt";+import { createEs256JwtSigner, deriveEs256KeyId } from "@/src/server/utils/jwt";import { UnauthorizedError } from "@langfuse/shared";import type { PrismaClient } from "@langfuse/shared/src/db";@@ -102,28 +102,137 @@ function database(input: { project?: object | null } = {}) {} as unknown as PrismaClient;}-describe("verifyGatewayIngestionAuthorization without signing keys", () => {- it("rejects a public key without its stable key ID", async () => {+describe("verifyGatewayIngestionAuthorization with derived key config", () => {+ it.each([+ { name: "only the private key", privateKey, publicKey: undefined },+ { name: "only the public key", privateKey: undefined, publicKey },+ ])(+ "accepts tokens signed under the default key ID with $name",+ async (configured) => {+ vi.resetModules();+ vi.doMock("@/src/env.mjs", () => ({+ env: {+ LANGFUSE_AI_GATEWAY_JWT_PRIVATE_KEY: configured.privateKey,+ LANGFUSE_AI_GATEWAY_JWT_PUBLIC_KEY: configured.publicKey,+ LANGFUSE_AI_GATEWAY_JWT_KEY_ID: undefined,+ LANGFUSE_AI_GATEWAY_JWT_ISSUER: "test-issuer",+ LANGFUSE_AI_GATEWAY_JWT_AUDIENCE: "test-audience",+ LANGFUSE_AI_GATEWAY_ORGANIZATION_ID_ALLOWLIST: ["org-1"],+ LANGFUSE_AI_GATEWAY_SERVICE_KEY: "current-service-key",+ },+ }));+ const { verifyGatewayIngestionAuthorization: verifyWithDerivedKeys } =+ await import("./ingestionTokenVerifier");+ const { resolveGatewayJwtKeys } = await import("./gatewayJwtKeys");++ // The signing side resolves from the private key, as resolveService does.+ const { keyId } = resolveGatewayJwtKeys({+ privateKey,+ publicKey: undefined,+ keyId: undefined,+ });+ const ingestionToken = createEs256JwtSigner({+ privateKey,+ keyId: keyId!,+ issuer: "test-issuer",+ audience: "test-audience",+ }).sign({+ expiresInSeconds: 60,+ claims: {+ version: 1,+ organization_id: "org-1",+ project_id: "project-1",+ ingestion_mode: "full",+ scope: "gateway-ingest",+ },+ });++ await expect(+ verifyWithDerivedKeys(+ `Bearer ${ingestionToken}`,+ gatewayAuthorization(ingestionToken),+ database(),+ ),+ ).resolves.toMatchObject({ scope: { projectId: "project-1" } });++ vi.doUnmock("@/src/env.mjs");+ vi.resetModules();+ },+ );++ it("accepts tokens from the previous key under its default key ID", async () => {+ const current = generateKeyPairSync("ec", { namedCurve: "P-256" });vi.resetModules();vi.doMock("@/src/env.mjs", () => ({env: {- LANGFUSE_AI_GATEWAY_JWT_PUBLIC_KEY: publicKey,- LANGFUSE_AI_GATEWAY_JWT_KEY_ID: undefined,- LANGFUSE_AI_GATEWAY_JWT_PREVIOUS_KEY_ID: undefined,- LANGFUSE_AI_GATEWAY_JWT_PREVIOUS_PUBLIC_KEY: undefined,+ LANGFUSE_AI_GATEWAY_JWT_PRIVATE_KEY: current.privateKey+ .export({ type: "pkcs8", format: "pem" })+ .toString(),+ LANGFUSE_AI_GATEWAY_JWT_PREVIOUS_PUBLIC_KEY: publicKey,LANGFUSE_AI_GATEWAY_JWT_ISSUER: "test-issuer",LANGFUSE_AI_GATEWAY_JWT_AUDIENCE: "test-audience",+ LANGFUSE_AI_GATEWAY_ORGANIZATION_ID_ALLOWLIST: ["org-1"],+ LANGFUSE_AI_GATEWAY_SERVICE_KEY: "current-service-key",},}));+ const { verifyGatewayIngestionAuthorization: verifyWithRotatedKeys } =+ await import("./ingestionTokenVerifier");- await expect(import("./ingestionTokenVerifier")).rejects.toThrow(- "LANGFUSE_AI_GATEWAY_JWT_KEY_ID and LANGFUSE_AI_GATEWAY_JWT_PUBLIC_KEY must be set together",- );+ const ingestionToken = createEs256JwtSigner({+ privateKey,+ keyId: deriveEs256KeyId(publicKey),+ issuer: "test-issuer",+ audience: "test-audience",+ }).sign({+ expiresInSeconds: 60,+ claims: {+ version: 1,+ organization_id: "org-1",+ project_id: "project-1",+ ingestion_mode: "full",+ scope: "gateway-ingest",+ },+ });++ await expect(+ verifyWithRotatedKeys(+ `Bearer ${ingestionToken}`,+ gatewayAuthorization(ingestionToken),+ database(),+ ),+ ).resolves.toMatchObject({ scope: { projectId: "project-1" } });vi.doUnmock("@/src/env.mjs");vi.resetModules();});+ it("stays inert instead of failing the import on an invalid private key", async () => {+ vi.resetModules();+ vi.doMock("@/src/env.mjs", () => ({+ env: {+ LANGFUSE_AI_GATEWAY_JWT_PRIVATE_KEY: "not a pem",+ LANGFUSE_AI_GATEWAY_JWT_ISSUER: "test-issuer",+ LANGFUSE_AI_GATEWAY_JWT_AUDIENCE: "test-audience",+ LANGFUSE_AI_GATEWAY_ORGANIZATION_ID_ALLOWLIST: ["org-1"],+ },+ }));+ const { verifyGatewayIngestionAuthorization: verifyWithInvalidKey } =+ await import("./ingestionTokenVerifier");++ await expect(+ verifyWithInvalidKey(+ `Bearer ${token()}`,+ undefined,+ {} as unknown as PrismaClient,+ ),+ ).resolves.toBeNull();++ vi.doUnmock("@/src/env.mjs");+ vi.resetModules();+ });+});++describe("verifyGatewayIngestionAuthorization without signing keys", () => {it("stays inert so the regular API-key verifier still sees the header", async () => {// Every deployment that never enabled the gateway is in this state. If the// verifier rejected here, any three-part bearer token would 401 before thediff --git a/web/src/features/ai-gateway/server/auth/ingestionTokenVerifier.ts b/web/src/features/ai-gateway/server/auth/ingestionTokenVerifier.tsindex 89df403959..41fd52ec05 100644--- a/web/src/features/ai-gateway/server/auth/ingestionTokenVerifier.ts+++ b/web/src/features/ai-gateway/server/auth/ingestionTokenVerifier.ts@@ -2,14 +2,19 @@ import { env } from "@/src/env.mjs";import { getOrganizationPlanServerSide } from "@/src/features/entitlements/server";import { CloudConfigSchema, UnauthorizedError } from "@langfuse/shared";import { prisma, type PrismaClient } from "@langfuse/shared/src/db";-import type { ApiAccessScopeWithOptionalApiKeyId } from "@langfuse/shared/src/server";+import {+ type ApiAccessScopeWithOptionalApiKeyId,+ logger,+} from "@langfuse/shared/src/server";import { z } from "zod/v4";import {createEs256JwtVerifier,+ deriveEs256KeyId,type JwtRegisteredClaims,} from "@/src/server/utils/jwt";import { requireGatewayEnabledForOrganization } from "../availability";+import { resolveGatewayJwtKeys } from "./gatewayJwtKeys";import { verifyGatewayRequestSignature } from "./gatewayRequestSignatureVerifier";/** Outlives the gateway's default ten-minute execution ceiling plus upload batching. */@@ -54,17 +59,40 @@ function configuredPublicKey(input: {return [{ id: input.keyId, publicKey: input.publicKey }];}+// Every authenticated public API route imports this module, so invalid key+// configuration must disable gateway token verification instead of failing+// the import.const gatewayIngestionTokenVerifier = (() => {+ try {+ return createGatewayIngestionTokenVerifier();+ } catch (error) {+ logger.error(+ "Invalid AI gateway JWT key configuration; gateway ingestion tokens are not accepted",+ error,+ );+ return undefined;+ }+})();++function createGatewayIngestionTokenVerifier() {+ const current = resolveGatewayJwtKeys({+ privateKey: env.LANGFUSE_AI_GATEWAY_JWT_PRIVATE_KEY,+ publicKey: env.LANGFUSE_AI_GATEWAY_JWT_PUBLIC_KEY,+ keyId: env.LANGFUSE_AI_GATEWAY_JWT_KEY_ID,+ });+ const previousPublicKey = env.LANGFUSE_AI_GATEWAY_JWT_PREVIOUS_PUBLIC_KEY;const publicKeys = [...configuredPublicKey({- keyId: env.LANGFUSE_AI_GATEWAY_JWT_KEY_ID,- publicKey: env.LANGFUSE_AI_GATEWAY_JWT_PUBLIC_KEY,+ keyId: current.keyId,+ publicKey: current.publicKey,keyIdVariable: "LANGFUSE_AI_GATEWAY_JWT_KEY_ID",publicKeyVariable: "LANGFUSE_AI_GATEWAY_JWT_PUBLIC_KEY",}),...configuredPublicKey({- keyId: env.LANGFUSE_AI_GATEWAY_JWT_PREVIOUS_KEY_ID,- publicKey: env.LANGFUSE_AI_GATEWAY_JWT_PREVIOUS_PUBLIC_KEY,+ keyId:+ env.LANGFUSE_AI_GATEWAY_JWT_PREVIOUS_KEY_ID ??+ (previousPublicKey ? deriveEs256KeyId(previousPublicKey) : undefined),+ publicKey: previousPublicKey,keyIdVariable: "LANGFUSE_AI_GATEWAY_JWT_PREVIOUS_KEY_ID",publicKeyVariable: "LANGFUSE_AI_GATEWAY_JWT_PREVIOUS_PUBLIC_KEY",}),@@ -78,7 +106,7 @@ const gatewayIngestionTokenVerifier = (() => {claimsSchema: GatewayIngestionClaimsSchema,}): undefined;-})();+}export async function verifyGatewayIngestionAuthorization(authorization: string | undefined,diff --git a/web/src/features/ai-gateway/server/availability.ts b/web/src/features/ai-gateway/server/availability.tsindex 7b00fcae3d..aeb3665e24 100644--- a/web/src/features/ai-gateway/server/availability.ts+++ b/web/src/features/ai-gateway/server/availability.ts@@ -5,12 +5,14 @@ import { env } from "@/src/env.mjs";type GatewayAvailabilityEnvironment = {nodeEnv: string | undefined;previewPrUrl?: string;+ enabledForAllOrganizations?: boolean;};const getGatewayAvailabilityEnvironment =(): GatewayAvailabilityEnvironment => ({nodeEnv: env.NODE_ENV,previewPrUrl: env.NEXT_PUBLIC_PREVIEW_PR_URL,+ enabledForAllOrganizations: env.LANGFUSE_AI_GATEWAY_ENABLED === "true",});export const isGatewayEnabledForOrganization = (@@ -19,6 +21,7 @@ export const isGatewayEnabledForOrganization = ([],environment = getGatewayAvailabilityEnvironment(),): boolean =>+ environment.enabledForAllOrganizations === true ||environment.nodeEnv === "development" ||environment.previewPrUrl !== undefined ||allowedOrganizationIds.includes(organizationId);diff --git a/web/src/features/ai-gateway/server/resolve/resolveService.ts b/web/src/features/ai-gateway/server/resolve/resolveService.tsindex 15e86e75e9..d5ed9e78a9 100644--- a/web/src/features/ai-gateway/server/resolve/resolveService.ts+++ b/web/src/features/ai-gateway/server/resolve/resolveService.ts@@ -9,6 +9,7 @@ import {} from "@/src/server/utils/jwt";import type { GatewayApiKeyAuthContext } from "@/src/features/ai-gateway/server/auth/gatewayApiKeyAuthenticator";+import { resolveGatewayJwtKeys } from "@/src/features/ai-gateway/server/auth/gatewayJwtKeys";import { GATEWAY_INGESTION_TOKEN_TTL_SECONDS } from "@/src/features/ai-gateway/server/auth/ingestionTokenVerifier";import { GatewayControlPlaneError as GatewayResolveError } from "@/src/features/ai-gateway/server/gatewayControlPlaneError";import {@@ -31,16 +32,12 @@ let cachedGatewayIngestionTokenSigner:| undefined;function getGatewayIngestionTokenSigner() {- const privateKey = env.LANGFUSE_AI_GATEWAY_JWT_PRIVATE_KEY;- if (!privateKey) return undefined;-- const publicKey = env.LANGFUSE_AI_GATEWAY_JWT_PUBLIC_KEY;- const keyId = env.LANGFUSE_AI_GATEWAY_JWT_KEY_ID;- if (!publicKey || !keyId) {- throw new Error(- "LANGFUSE_AI_GATEWAY_JWT_PRIVATE_KEY, LANGFUSE_AI_GATEWAY_JWT_PUBLIC_KEY, and LANGFUSE_AI_GATEWAY_JWT_KEY_ID must be set together",- );- }+ const { privateKey, keyId } = resolveGatewayJwtKeys({+ privateKey: env.LANGFUSE_AI_GATEWAY_JWT_PRIVATE_KEY,+ publicKey: env.LANGFUSE_AI_GATEWAY_JWT_PUBLIC_KEY,+ keyId: env.LANGFUSE_AI_GATEWAY_JWT_KEY_ID,+ });+ if (!privateKey || !keyId) return undefined;const config = {privateKey,diff --git a/web/src/server/utils/jwt.servertest.ts b/web/src/server/utils/jwt.servertest.tsindex 45c18ae54f..72b4bb8c28 100644--- a/web/src/server/utils/jwt.servertest.ts+++ b/web/src/server/utils/jwt.servertest.ts@@ -6,6 +6,8 @@ import { z } from "zod/v4";import {createEs256JwtSigner,createEs256JwtVerifier,+ deriveEs256KeyId,+ deriveEs256PublicKey,type JwtRegisteredClaims,} from "@/src/server/utils/jwt";@@ -209,4 +211,49 @@ describe("ES256 JWT utilities", () => {verifyToken(token, [{ id: "current", publicKey: key.publicKey }]),).toThrow();});++ describe("key derivation", () => {+ const { privateKey, publicKey } = generateKeyPairSync("ec", {+ namedCurve: "P-256",+ });+ const publicKeyPem = publicKey+ .export({ format: "pem", type: "spki" })+ .toString();+ // What Helm's `genPrivateKey "ecdsa"` emits.+ const sec1Pem = privateKey+ .export({ format: "pem", type: "sec1" })+ .toString();++ it.each([+ {+ format: "PKCS#8",+ privateKey: privateKey+ .export({ format: "pem", type: "pkcs8" })+ .toString(),+ },+ { format: "SEC1", privateKey: sec1Pem },+ { format: "escaped SEC1", privateKey: sec1Pem.replaceAll("\n", "\\n") },+ ])(+ "derives a public key that verifies tokens from a $format private key",+ ({ privateKey }) => {+ const derived = deriveEs256PublicKey(privateKey);+ const token = signToken({ privateKey, keyId: "current" });++ expect(derived).toBe(publicKeyPem);+ expect(+ verifyToken(token, [{ id: "current", publicKey: derived }]).subjectId,+ ).toBe("subject-1");+ },+ );++ it("derives the same key ID from escaped and unescaped public keys", () => {+ const keyId = deriveEs256KeyId(publicKeyPem);++ expect(keyId).toMatch(/^[A-Za-z0-9_-]{43}$/);+ expect(deriveEs256KeyId(publicKeyPem.replaceAll("\n", "\\n"))).toBe(+ keyId,+ );+ expect(deriveEs256KeyId(generatePemKeyPair().publicKey)).not.toBe(keyId);+ });+ });});diff --git a/web/src/server/utils/jwt.ts b/web/src/server/utils/jwt.tsindex 2ca2fc0aa0..4a7d33a860 100644--- a/web/src/server/utils/jwt.ts+++ b/web/src/server/utils/jwt.ts@@ -1,4 +1,5 @@import {+ createHash,createPrivateKey,createPublicKey,type KeyObject,@@ -126,6 +127,28 @@ export function createEs256JwtVerifier<};}+/** deriveEs256PublicKey accepts PKCS#8 (`PRIVATE KEY`) and SEC1 (`EC PRIVATE KEY`) PEMs. */+export function deriveEs256PublicKey(privateKey: string): string {+ return createPublicKey(parsePrivateKey(privateKey))+ .export({ type: "spki", format: "pem" })+ .toString();+}++/**+ * deriveEs256KeyId returns the RFC 7638 JWK thumbprint of a public key, so+ * every holder of the same key agrees on the key ID without configuring one.+ */+export function deriveEs256KeyId(publicKey: string): string {+ const jwk = parsePublicKey(publicKey).export({ format: "jwk" });+ const canonical = JSON.stringify({+ crv: jwk.crv,+ kty: jwk.kty,+ x: jwk.x,+ y: jwk.y,+ });+ return createHash("sha256").update(canonical).digest("base64url");+}+function signEs256Jwt<TClaims extends Record<string, unknown>>(input: {privateKey: KeyObject;keyId: string;