Heimdall/src/verifier.ts
Meta Vens 053cb0a17e Register apps at runtime instead of at build time
App slugs were a compile-time union of four names. That was fine while every app
was ours and it blocks what Heimdall is for: an app it has never heard of,
running on someone else's machine, registering against a self-hosted instance
without forking and rebuilding the auth authority. A creator self-hosting
Erycina alongside Heimdall would otherwise maintain a patched auth server
forever.

AppSlug is now a string, which it always was on the wire; the union was a
narrowing the type system could enforce only because the set was closed.
Membership moved from appSlugs.includes to the registry, and where no store is
reachable — the offline token verifier is the case that matters — it is a shape
check, isAppSlug, rather than a false claim to know what exists. A host app
verifying its own tokens should compare aud against its own slug, which it knows
and Heimdall's built-in list does not.

Registration is data end to end. Storage carries the profile and a hash of the
client secret rather than the secret. Built-in profiles resolve first and their
slugs are refused at registration, in both places, so a registration cannot
shadow a shipped app and inherit its audience.

POST /v1/apps answers in the RFC 7591 shape so an ordinary OAuth client library
can read it, returning client_secret exactly once. It is gated on an operator
secret and closed entirely until one is configured: an open registration
endpoint on an OAuth provider lets anyone create a client that starts Discord
and Patreon flows under the instance's identity, which is a phishing surface
wearing the operator's name. A fresh instance is not accidentally open.

Redirect URIs are validated rather than stored as given. They are where an
authorization code is delivered, so a permissive one is a token-theft primitive:
absolute, no fragment, https unless loopback.

Six call sites assumed an app profile always exists. They now answer 404 for an
app nobody registered, and claim issuance refuses outright rather than signing a
token whose audience no verifier can resolve.

108 tests pass, 34 of them new. Zero type errors.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 00:11:41 +02:00

161 lines
4.9 KiB
TypeScript

import { createPublicKey, type KeyObject } from "node:crypto";
import { isAppSlug, providers, type AccessClaimPayload, type AppSlug, type LinkedIdentityInput, type Provider } from "./contracts.js";
import { type PublicSigningJwk, verifyJwt } from "./signing.js";
export interface HeimdallVerifierOptions {
issuer: string;
appSlug: AppSlug;
jwks: {
keys: PublicSigningJwk[];
};
allowedClockSkewSeconds?: number;
}
export type VerifyAccessTokenResult =
| {
valid: true;
header: Record<string, unknown>;
claimSet: AccessClaimPayload;
}
| {
valid: false;
error: string;
};
function isLinkedIdentity(value: unknown): value is LinkedIdentityInput {
if (!value || typeof value !== "object") {
return false;
}
const record = value as Record<string, unknown>;
if (
typeof record.provider !== "string" ||
!providers.includes(record.provider as Provider) ||
typeof record.providerUserId !== "string"
) {
return false;
}
if (record.username !== undefined && typeof record.username !== "string") {
return false;
}
if (record.displayName !== undefined && typeof record.displayName !== "string") {
return false;
}
return true;
}
function parseAccessClaimPayload(payload: Record<string, unknown>): AccessClaimPayload | null {
if (
payload.typ !== "heimdall_access" ||
typeof payload.iss !== "string" ||
typeof payload.aud !== "string" ||
!isAppSlug(payload.aud) ||
typeof payload.sub !== "string" ||
typeof payload.sid !== "string" ||
typeof payload.jti !== "string" ||
typeof payload.iat !== "number" ||
typeof payload.nbf !== "number" ||
typeof payload.exp !== "number" ||
typeof payload.account_id !== "string" ||
typeof payload.access_revision !== "number" ||
!payload.app ||
typeof payload.app !== "object" ||
typeof (payload.app as Record<string, unknown>).slug !== "string" ||
!isAppSlug((payload.app as Record<string, unknown>).slug) ||
typeof (payload.app as Record<string, unknown>).profile_version !== "string" ||
!Array.isArray(payload.facts) ||
!payload.facts.every((fact) => typeof fact === "string") ||
!Array.isArray(payload.capabilities) ||
!payload.capabilities.every((capability) => typeof capability === "string") ||
!Array.isArray(payload.identities) ||
!payload.identities.every(isLinkedIdentity)
) {
return null;
}
if (payload.display_name !== undefined && typeof payload.display_name !== "string") {
return null;
}
return payload as unknown as AccessClaimPayload;
}
function buildKeyIndex(jwks: { keys: PublicSigningJwk[] }): Map<string, KeyObject> {
return new Map(
jwks.keys.map((jwk) => [
jwk.kid,
createPublicKey({
key: jwk,
format: "jwk",
}),
])
);
}
export function createHeimdallAccessTokenVerifier(options: HeimdallVerifierOptions): {
verify(token: string, now?: Date): VerifyAccessTokenResult;
} {
const keyIndex = buildKeyIndex(options.jwks);
const allowedClockSkewSeconds = Math.max(0, Math.trunc(options.allowedClockSkewSeconds ?? 30));
return {
verify(token: string, now = new Date()): VerifyAccessTokenResult {
const [encodedHeader] = token.split(".");
if (!encodedHeader) {
return { valid: false, error: "Malformed JWT." };
}
let header: Record<string, unknown>;
try {
header = JSON.parse(Buffer.from(encodedHeader, "base64url").toString("utf8")) as Record<string, unknown>;
} catch {
return { valid: false, error: "Malformed JWT header." };
}
if (header.alg !== "EdDSA" || typeof header.kid !== "string") {
return { valid: false, error: "Unsupported JWT signing header." };
}
const publicKey = keyIndex.get(header.kid);
if (!publicKey) {
return { valid: false, error: `Unknown signing key id '${header.kid}'.` };
}
const verified = verifyJwt(token, publicKey);
if (!verified.valid) {
return verified;
}
const claimSet = parseAccessClaimPayload(verified.payload);
if (!claimSet) {
return { valid: false, error: "JWT payload is not a valid Heimdall access claim." };
}
if (claimSet.iss !== options.issuer) {
return { valid: false, error: "JWT issuer does not match the configured Heimdall issuer." };
}
if (claimSet.aud !== options.appSlug || claimSet.app.slug !== options.appSlug) {
return { valid: false, error: "JWT audience does not match the expected app slug." };
}
const nowEpochSeconds = Math.floor(now.getTime() / 1000);
if (claimSet.nbf > nowEpochSeconds + allowedClockSkewSeconds) {
return { valid: false, error: "JWT is not valid yet." };
}
if (claimSet.exp <= nowEpochSeconds - allowedClockSkewSeconds) {
return { valid: false, error: "JWT has expired." };
}
return {
valid: true,
header: verified.header,
claimSet,
};
},
};
}