Heimdall/src/claims.ts

181 lines
5.4 KiB
TypeScript
Raw Normal View History

2026-04-26 12:50:07 +01:00
import { randomUUID } from "node:crypto";
import {
type AccessClaimPayload,
type AppSlug,
type LinkedIdentityInput,
type RefreshTokenPayload,
2026-04-26 12:50:07 +01:00
} from "./contracts.js";
R21.3: delete the unreachable registered-app resolution path The runtime app-registration writer (POST /v1/apps) was deleted in an earlier pass because it minted a client_secret nobody verified. This pass kept resolveAppProfile's registered-app fallback and listAppProfiles on the theory that AppSlug is an open string and dynamic registration was a live extension point. Soul falsified that: every HTTP route enumerates the four built-in slugs in its own JSON schema (app.ts's `enum: [...appSlugs]` at every appSlug param/body field), so a registered row could never be resolved from a request. With the writer already gone, this was unreachable code behind a dead writer -- delete it rather than keep authenticating a door nobody can open. Deleted: src/app-registry.ts entirely (resolveAppProfile, listAppProfiles, isBuiltInApp, registeredAppToProfile, returnOriginsFromRedirectUris); StoredRegisteredApp and the findRegisteredApp/listRegisteredApps HeimdallStore methods (store/types.ts); their InMemoryStore and PostgresStore implementations, including seedRegisteredApp and mapRegisteredApp; the registered_apps table (store/schema.ts now drops it on any store built before this schema); tests/app-registry.test.ts. Every call site (app.ts x5, claims.ts, private-command-plane.ts) now calls the existing built-in-only getAppProfile (app-profiles.ts) directly -- sync, no store needed. If dynamic app registration is wanted later it returns as a designed, authenticated feature, not by resurrecting this vestige. Net -305 lines against the prior commit. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-08 14:51:23 +02:00
import { evaluateSharedCapabilities, getAppProfile, type AppProfile } from "./app-profiles.js";
2026-04-26 12:50:07 +01:00
import { type HeimdallConfig } from "./config.js";
import { identityFacts } from "./facts.js";
2026-04-26 12:50:07 +01:00
import { signJwt, type RuntimeKeyMaterial } from "./signing.js";
import { type CreateSessionInput, type HeimdallStore } from "./store/types.js";
function nowEpochSeconds(): number {
return Math.floor(Date.now() / 1000);
}
function clampTtlSeconds(value: number, fallback: number): number {
if (!Number.isFinite(value)) {
return fallback;
}
return Math.max(60, Math.min(86_400, Math.trunc(value)));
}
function normalizeFacts(accountId: string, linkedIdentities: LinkedIdentityInput[], facts: string[]): string[] {
const normalized = new Set(facts);
if (accountId.trim() || linkedIdentities.length) {
normalized.add(identityFacts.authenticated);
2026-04-26 12:50:07 +01:00
}
return [...normalized].sort();
}
export interface IssueAccessClaimInput {
appSlug: AppSlug;
accountId: string;
displayName?: string;
linkedIdentities: LinkedIdentityInput[];
facts: string[];
sessionId?: string;
accessRevision?: number;
ttlSeconds?: number;
}
export interface IssuedAccessClaimResult {
session: {
accountId: string;
sessionId: string;
appSlug: AppSlug;
accessRevision: number;
expiresAt: string;
};
accessToken: string;
refreshToken: string;
refresh: {
expiresAt: string;
};
2026-04-26 12:50:07 +01:00
claimSet: AccessClaimPayload;
verification: {
issuer: string;
jwksUri: string;
alg: string;
kid: string;
};
sharedCapabilities: string[];
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
hybridCapabilities: AppProfile["capabilities"];
2026-04-26 12:50:07 +01:00
}
export async function issueAccessClaim(options: {
config: HeimdallConfig;
keys: RuntimeKeyMaterial;
store: HeimdallStore;
input: IssueAccessClaimInput;
}): Promise<IssuedAccessClaimResult> {
R21.3: delete the unreachable registered-app resolution path The runtime app-registration writer (POST /v1/apps) was deleted in an earlier pass because it minted a client_secret nobody verified. This pass kept resolveAppProfile's registered-app fallback and listAppProfiles on the theory that AppSlug is an open string and dynamic registration was a live extension point. Soul falsified that: every HTTP route enumerates the four built-in slugs in its own JSON schema (app.ts's `enum: [...appSlugs]` at every appSlug param/body field), so a registered row could never be resolved from a request. With the writer already gone, this was unreachable code behind a dead writer -- delete it rather than keep authenticating a door nobody can open. Deleted: src/app-registry.ts entirely (resolveAppProfile, listAppProfiles, isBuiltInApp, registeredAppToProfile, returnOriginsFromRedirectUris); StoredRegisteredApp and the findRegisteredApp/listRegisteredApps HeimdallStore methods (store/types.ts); their InMemoryStore and PostgresStore implementations, including seedRegisteredApp and mapRegisteredApp; the registered_apps table (store/schema.ts now drops it on any store built before this schema); tests/app-registry.test.ts. Every call site (app.ts x5, claims.ts, private-command-plane.ts) now calls the existing built-in-only getAppProfile (app-profiles.ts) directly -- sync, no store needed. If dynamic app registration is wanted later it returns as a designed, authenticated feature, not by resurrecting this vestige. Net -305 lines against the prior commit. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-08 14:51:23 +02:00
const profile = getAppProfile(options.input.appSlug);
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
if (!profile) {
// An unregistered audience must not receive a signed claim: the token
// would name an app no verifier can resolve a profile for.
throw new Error(`Cannot issue an access claim for unknown app '${options.input.appSlug}'.`);
}
2026-04-26 12:50:07 +01:00
const facts = normalizeFacts(options.input.accountId, options.input.linkedIdentities, options.input.facts);
const factSet = new Set(facts);
Make app capability rules data instead of code Every app profile carried an evaluateSharedCapabilities function beside a sharedRule string describing what that function did. Two representations of one rule, free to drift, and the reason a profile could never arrive at runtime: you cannot accept a function from a stranger and run it inside the auth authority. The rules were never more than a disjunction. Every sharedRule across all four built-in profiles is "a || b || c" over a closed vocabulary, and one of them is a bare reference to another capability. So the executable form is a list, not an expression language, and anyOf is now the only representation. The readable form is derived from it rather than stored beside it. Evaluation runs to a fixed point because capabilities may reference each other: repixelizer's queue_submit derives from app_access, and a single pass grants it only when the rules happen to be declared in dependency order. It terminates because the granted set only grows and is bounded by the rule count. validateCapabilityRules is the gate that makes runtime registration acceptable. A term must name a fact Heimdall itself produces or another capability in the same profile. A registered app selects from what Heimdall has already decided is true about an account; it cannot invent a fact to grant itself something, and it cannot reach into another app's capabilities. An unknown term is refused rather than treated as false, because a rule that silently never fires becomes a support ticket instead of an error. The four built-in profiles are now seed data rather than special cases: a registered app produces the same shape and runs through the same evaluator. Behaviour is unchanged. 74 tests pass, 18 of them new, covering derived capabilities in both declaration orders, hybrid capabilities never being granted from shared rules, and every rejection path in the validator. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-06 23:58:58 +02:00
const sharedCapabilities = evaluateSharedCapabilities(profile, {
2026-04-26 12:50:07 +01:00
accountId: options.input.accountId,
facts: factSet,
identities: options.input.linkedIdentities,
});
const issuedAt = nowEpochSeconds();
const ttlSeconds = clampTtlSeconds(
options.input.ttlSeconds ?? options.config.sessionTtlSeconds,
options.config.sessionTtlSeconds
);
const expiresAtEpoch = issuedAt + ttlSeconds;
const refreshTtlSeconds = Math.max(ttlSeconds, Math.trunc(options.config.refreshTtlSeconds));
const refreshExpiresAtEpoch = issuedAt + refreshTtlSeconds;
2026-04-26 12:50:07 +01:00
const sessionId = options.input.sessionId ?? randomUUID();
const accessRevision = options.input.accessRevision ?? 1;
const claimSet: AccessClaimPayload = {
iss: options.config.issuer,
aud: profile.slug,
sub: options.input.accountId,
sid: sessionId,
jti: randomUUID(),
iat: issuedAt,
nbf: issuedAt,
exp: expiresAtEpoch,
typ: "heimdall_access",
account_id: options.input.accountId,
access_revision: accessRevision,
app: {
slug: profile.slug,
profile_version: profile.profileVersion,
},
facts,
capabilities: sharedCapabilities,
identities: options.input.linkedIdentities,
};
if (options.input.displayName) {
claimSet.display_name = options.input.displayName;
}
const accessToken = signJwt(claimSet as unknown as Record<string, unknown>, options.keys);
const refreshClaimSet: RefreshTokenPayload = {
iss: options.config.issuer,
aud: profile.slug,
sub: options.input.accountId,
sid: sessionId,
jti: randomUUID(),
iat: issuedAt,
nbf: issuedAt,
exp: refreshExpiresAtEpoch,
typ: "heimdall_refresh",
account_id: options.input.accountId,
access_revision: accessRevision,
app: {
slug: profile.slug,
profile_version: profile.profileVersion,
},
};
const refreshToken = signJwt(refreshClaimSet as unknown as Record<string, unknown>, options.keys);
2026-04-26 12:50:07 +01:00
const sessionRecord: CreateSessionInput = {
id: sessionId,
accountId: options.input.accountId,
appSlug: profile.slug,
createdAt: new Date(issuedAt * 1000).toISOString(),
lastSeenAt: new Date(issuedAt * 1000).toISOString(),
expiresAt: new Date(refreshExpiresAtEpoch * 1000).toISOString(),
2026-04-26 12:50:07 +01:00
accessRevision,
claimsJson: claimSet as unknown as Record<string, unknown>,
};
await options.store.createSession(sessionRecord);
return {
session: {
accountId: options.input.accountId,
sessionId,
appSlug: profile.slug,
accessRevision,
expiresAt: sessionRecord.expiresAt,
},
accessToken,
refreshToken,
refresh: {
expiresAt: sessionRecord.expiresAt,
},
2026-04-26 12:50:07 +01:00
claimSet,
verification: {
issuer: options.config.issuer,
jwksUri: `${options.config.publicBaseUrl}/.well-known/jwks.json`,
alg: options.keys.alg,
kid: options.keys.kid,
},
sharedCapabilities,
hybridCapabilities: profile.capabilities.filter((capability) => capability.mode === "hybrid"),
};
}