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>
This commit is contained in:
Meta Vens 2026-09-07 00:11:41 +02:00
commit 053cb0a17e
15 changed files with 930 additions and 23 deletions

View file

@ -171,7 +171,12 @@ export const builtInAppProfiles: Record<AppSlug, AppProfile> = {
export const appProfiles = builtInAppProfiles;
export function getAppProfile(appSlug: AppSlug): AppProfile {
/**
* Built-in profiles only, and it can miss: an app registered at runtime is
* resolved through the registry, which needs a store. Callers with a store
* should prefer resolveAppProfile.
*/
export function getAppProfile(appSlug: AppSlug): AppProfile | undefined {
return appProfiles[appSlug];
}

203
src/app-registry.ts Normal file
View file

@ -0,0 +1,203 @@
// Runtime app registration.
//
// App slugs used to be a compile-time union. That was tolerable while every app
// was ours, and it blocks the thing Heimdall is for: an app it has never heard
// of, running on someone else's machine, needs to register against a
// self-hosted instance without forking and rebuilding the auth authority.
//
// A registration is entirely data. It is accepted only if every capability rule
// names a fact Heimdall itself produces or another capability in the same
// profile, which is what stops a registration from granting itself something
// Heimdall never decided was true.
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
import { builtInAppProfiles, type AppProfile } from "./app-profiles.js";
import { validateCapabilityRules, type CapabilityDefinition } from "./capability-rules.js";
import { providers, type Provider } from "./contracts.js";
import { type HeimdallStore, type StoredRegisteredApp } from "./store/types.js";
/** Slugs are used as JWT audiences and storage keys; keep them boring. */
const SLUG_PATTERN = /^[a-z][a-z0-9_-]{1,62}$/;
export interface AppRegistrationRequest {
slug: string;
displayName: string;
profileVersion?: string;
identityProviders: string[];
entitlementSources?: string[];
managedConnectionProviders?: string[];
capabilities: CapabilityDefinition[];
redirectUris: string[];
}
export interface RegistrationProblem {
field: string;
reason: string;
}
export interface AppRegistrationResult {
app: StoredRegisteredApp;
/** Returned once, at registration. Only its hash is stored. */
clientSecret: string;
}
export function isBuiltInApp(slug: string): boolean {
return Object.hasOwn(builtInAppProfiles, slug);
}
function isKnownProvider(value: string): value is Provider {
return (providers as readonly string[]).includes(value);
}
/**
* A redirect URI is where an authorization code is delivered, so a permissive
* one is a token-theft primitive rather than a convenience. Absolute, no
* fragment, and TLS unless it is loopback.
*/
function redirectUriProblem(value: string): string | null {
let url: URL;
try {
url = new URL(value);
} catch {
return "Redirect URI must be an absolute URL.";
}
if (url.hash) return "Redirect URI must not carry a fragment.";
const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "::1";
if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
return "Redirect URI must use https, except on loopback.";
}
return null;
}
export function validateAppRegistration(request: AppRegistrationRequest): RegistrationProblem[] {
const problems: RegistrationProblem[] = [];
if (!SLUG_PATTERN.test(request.slug ?? "")) {
problems.push({
field: "slug",
reason: "Slug must be 2-63 characters, lowercase, starting with a letter, using only a-z 0-9 _ and -.",
});
} else if (isBuiltInApp(request.slug)) {
// Otherwise a registration could shadow a shipped app and inherit its
// audience, which is impersonation rather than registration.
problems.push({ field: "slug", reason: `Slug '${request.slug}' is reserved by a built-in app profile.` });
}
if (!request.displayName?.trim()) {
problems.push({ field: "displayName", reason: "A display name is required." });
}
for (const [field, values] of [
["identityProviders", request.identityProviders],
["entitlementSources", request.entitlementSources ?? []],
["managedConnectionProviders", request.managedConnectionProviders ?? []],
] as const) {
for (const value of values ?? []) {
if (!isKnownProvider(value)) {
problems.push({ field, reason: `Unknown provider '${value}'.` });
}
}
}
if (!request.identityProviders?.length) {
problems.push({ field: "identityProviders", reason: "At least one identity provider is required." });
}
if (!request.redirectUris?.length) {
problems.push({ field: "redirectUris", reason: "At least one redirect URI is required." });
}
for (const uri of request.redirectUris ?? []) {
const problem = redirectUriProblem(uri);
if (problem) problems.push({ field: "redirectUris", reason: `${problem} (${uri})` });
}
if (!request.capabilities?.length) {
problems.push({ field: "capabilities", reason: "At least one capability is required." });
}
for (const problem of validateCapabilityRules(request.capabilities ?? [])) {
problems.push({ field: `capabilities.${problem.capability}`, reason: problem.reason });
}
return problems;
}
export function hashClientSecret(secret: string): string {
// A generated 256-bit secret does not need a slow KDF; it needs to not be
// stored in the clear. Passwords would be a different question.
return createHash("sha256").update(secret, "utf8").digest("hex");
}
export function verifyClientSecret(secret: string, storedHash: string | null): boolean {
if (!storedHash) return false;
const candidate = Buffer.from(hashClientSecret(secret), "hex");
const expected = Buffer.from(storedHash, "hex");
if (candidate.length !== expected.length) return false;
return timingSafeEqual(candidate, expected);
}
export async function registerApp(
store: HeimdallStore,
request: AppRegistrationRequest,
registeredAt: string = new Date().toISOString(),
): Promise<AppRegistrationResult> {
const problems = validateAppRegistration(request);
if (problems.length > 0) {
throw new AppRegistrationError(problems);
}
const clientSecret = randomBytes(32).toString("base64url");
const app = await store.registerApp({
slug: request.slug,
displayName: request.displayName.trim(),
profileVersion: request.profileVersion?.trim() || registeredAt.slice(0, 10),
registeredAt,
identityProviders: request.identityProviders as Provider[],
entitlementSources: (request.entitlementSources ?? []) as Provider[],
managedConnectionProviders: (request.managedConnectionProviders ?? []) as Provider[],
capabilities: request.capabilities,
redirectUris: request.redirectUris,
clientSecretHash: hashClientSecret(clientSecret),
});
return { app, clientSecret };
}
export class AppRegistrationError extends Error {
constructor(readonly problems: RegistrationProblem[]) {
super(`App registration rejected: ${problems.map((problem) => problem.reason).join(" ")}`);
this.name = "AppRegistrationError";
}
}
export function registeredAppToProfile(app: StoredRegisteredApp): AppProfile {
return {
slug: app.slug,
displayName: app.displayName,
profileVersion: app.profileVersion,
identityProviders: app.identityProviders,
entitlementSources: app.entitlementSources,
managedConnectionProviders: app.managedConnectionProviders,
capabilities: app.capabilities,
};
}
/**
* Built-ins first, so a shipped app cannot be shadowed even if a row for it
* somehow exists. Registration refuses those slugs, and this is the second
* place that holds.
*/
export async function resolveAppProfile(store: HeimdallStore, slug: string): Promise<AppProfile | null> {
const builtIn = builtInAppProfiles[slug as keyof typeof builtInAppProfiles];
if (builtIn) return builtIn;
const registered = await store.findRegisteredApp(slug);
return registered ? registeredAppToProfile(registered) : null;
}
export async function listAppProfiles(store: HeimdallStore): Promise<AppProfile[]> {
const registered = await store.listRegisteredApps();
return [
...Object.values(builtInAppProfiles),
...registered.filter((app) => !isBuiltInApp(app.slug)).map(registeredAppToProfile),
];
}

View file

@ -8,6 +8,7 @@ import {
oauthHandoffKinds,
oauthModes,
providers,
isAppSlug,
type AppSlug,
type OAuthHandoff,
type OAuthEntitlementPolicy,
@ -21,7 +22,15 @@ import {
type Provider,
} from "./contracts.js";
import { mapIssueClaimRequest, issueAccessClaim, type IssueAccessClaimInput } from "./claims.js";
import { getAppProfile, serializeAppProfile, supportsProvider } from "./app-profiles.js";
import { builtInAppProfiles, getAppProfile, serializeAppProfile, supportsProvider } from "./app-profiles.js";
import {
AppRegistrationError,
listAppProfiles,
registerApp,
registeredAppToProfile,
resolveAppProfile,
type AppRegistrationRequest,
} from "./app-registry.js";
import { renderBrowserHandoffPage } from "./browser-handoff.js";
import { type HeimdallConfig, loadConfig } from "./config.js";
import { createTokenCustody, type TokenCustody } from "./custody.js";
@ -76,7 +85,7 @@ function buildDiscovery(config: HeimdallConfig) {
displayName: providerCatalog[provider].displayName,
roles: providerCatalog[provider].roles,
})),
apps: appSlugs.map((appSlug) => serializeAppProfile(getAppProfile(appSlug))),
apps: Object.values(builtInAppProfiles).map(serializeAppProfile),
};
}
@ -156,7 +165,7 @@ function parseOAuthStatePayload(payload: Record<string, unknown>): OAuthStatePay
typeof payload.provider !== "string" ||
!providers.includes(payload.provider as Provider) ||
typeof payload.app_slug !== "string" ||
!appSlugs.includes(payload.app_slug as AppSlug) ||
!isAppSlug(payload.app_slug) ||
typeof payload.mode !== "string" ||
!oauthModes.includes(payload.mode as OAuthMode) ||
typeof payload.return_to !== "string" ||
@ -193,7 +202,7 @@ function parseRefreshTokenPayload(payload: Record<string, unknown>): RefreshToke
payload.typ !== "heimdall_refresh" ||
typeof payload.iss !== "string" ||
typeof payload.aud !== "string" ||
!appSlugs.includes(payload.aud as AppSlug) ||
!isAppSlug(payload.aud) ||
typeof payload.sub !== "string" ||
typeof payload.sid !== "string" ||
typeof payload.jti !== "string" ||
@ -330,6 +339,11 @@ function getSharedSecret(request: { headers: Record<string, string | string[] |
return Array.isArray(header) ? header[0] : header;
}
function getRegistrationSecret(request: { headers: Record<string, unknown> }): string | undefined {
const header = request.headers["x-heimdall-registration-secret"];
return typeof header === "string" ? header : undefined;
}
function secretMatches(expected: string | undefined, provided: string | undefined): boolean {
if (!expected || !provided) {
return false;
@ -434,7 +448,10 @@ async function evaluateStoredEntitlements(options: {
entitlementPolicies: OAuthEntitlementPolicy[];
now: string;
}): Promise<string[]> {
const profile = getAppProfile(options.appSlug);
const profile = await resolveAppProfile(options.store, options.appSlug);
if (!profile) {
throw new Error(`Unknown app '${options.appSlug}'.`);
}
const linkedIdentities = await options.store.listStoredLinkedIdentitiesForAccount(options.accountId);
const facts: string[] = [];
@ -552,9 +569,56 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
app.get("/.well-known/heimdall-configuration", async () => buildDiscovery(config));
app.get("/v1/apps", async () => ({
apps: appSlugs.map((appSlug) => serializeAppProfile(getAppProfile(appSlug))),
apps: (await listAppProfiles(store)).map(serializeAppProfile),
}));
// POST /v1/apps registration.
//
// Gated on an operator secret rather than open. Heimdall is an OAuth
// provider: an unauthenticated registration endpoint lets anyone create a
// client that starts Discord and Patreon flows under this instance identity,
// which is a phishing surface wearing the operator name. Registration is
// closed until an operator sets one, so a fresh instance is not accidentally
// open.
app.post<{ Body: AppRegistrationRequest }>("/v1/apps", async (request, reply) => {
if (!config.appRegistrationSecret) {
reply.code(404);
return {
error: "registration_closed",
detail: "Runtime app registration is not enabled on this instance.",
};
}
if (!secretMatches(config.appRegistrationSecret, getRegistrationSecret(request))) {
reply.code(401);
return { error: "unauthorized", detail: "A valid registration secret is required." };
}
try {
const { app: registered, clientSecret } = await registerApp(store, request.body);
reply.code(201);
// RFC 7591 response shape, so an ordinary OAuth client library can read
// it. client_secret is returned exactly once; only its hash is stored.
return {
client_id: registered.slug,
client_secret: clientSecret,
client_name: registered.displayName,
redirect_uris: registered.redirectUris,
client_id_issued_at: Math.floor(Date.parse(registered.createdAt) / 1000),
profile: serializeAppProfile(registeredAppToProfile(registered)),
};
} catch (error) {
if (error instanceof AppRegistrationError) {
reply.code(400);
return {
error: "invalid_client_metadata",
detail: "App registration was rejected.",
problems: error.problems,
};
}
throw error;
}
});
app.get<{ Params: { appSlug: AppSlug } }>(
"/v1/apps/:appSlug",
{
@ -564,12 +628,19 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
required: ["appSlug"],
additionalProperties: false,
properties: {
appSlug: { type: "string", enum: [...appSlugs] },
appSlug: { type: "string" },
},
},
},
},
async (request) => serializeAppProfile(getAppProfile(request.params.appSlug))
async (request, reply) => {
const profile = await resolveAppProfile(store, request.params.appSlug);
if (!profile) {
reply.code(404);
return { error: "unknown_app", detail: `No app '${request.params.appSlug}' is registered.` };
}
return serializeAppProfile(profile);
}
);
app.post<{ Params: { provider: Provider }; Body: OAuthStartRequest }>(
@ -651,7 +722,11 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
},
async (request, reply) => {
const { provider } = request.params;
const profile = getAppProfile(request.body.appSlug);
const profile = await resolveAppProfile(store, request.body.appSlug);
if (!profile) {
reply.code(404);
return { error: "unknown_app", detail: `No app '${request.body.appSlug}' is registered.` };
}
if (!supportsProvider(profile, provider)) {
reply.code(400);
@ -1519,7 +1594,11 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
},
},
async (request, reply) => {
const profile = getAppProfile(request.params.appSlug);
const profile = await resolveAppProfile(store, request.params.appSlug);
if (!profile) {
reply.code(404);
return { error: "unknown_app", detail: `No app '${request.params.appSlug}' is registered.` };
}
const providedSecret = getSharedSecret(request);
if (!secretMatches(config.appSharedSecrets[profile.slug], providedSecret)) {
@ -1668,7 +1747,11 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
},
},
async (request, reply) => {
const profile = getAppProfile(request.params.appSlug);
const profile = await resolveAppProfile(store, request.params.appSlug);
if (!profile) {
reply.code(404);
return { error: "unknown_app", detail: `No app '${request.params.appSlug}' is registered.` };
}
const providedSecret = getSharedSecret(request);
if (!secretMatches(config.appSharedSecrets[profile.slug], providedSecret)) {

View file

@ -6,7 +6,8 @@ import {
type LinkedIdentityInput,
type RefreshTokenPayload,
} from "./contracts.js";
import { evaluateSharedCapabilities, getAppProfile } from "./app-profiles.js";
import { evaluateSharedCapabilities, type AppProfile } from "./app-profiles.js";
import { resolveAppProfile } from "./app-registry.js";
import { type HeimdallConfig } from "./config.js";
import { identityFacts } from "./facts.js";
import { signJwt, type RuntimeKeyMaterial } from "./signing.js";
@ -66,7 +67,7 @@ export interface IssuedAccessClaimResult {
kid: string;
};
sharedCapabilities: string[];
hybridCapabilities: ReturnType<typeof getAppProfile>["capabilities"];
hybridCapabilities: AppProfile["capabilities"];
}
export async function issueAccessClaim(options: {
@ -75,7 +76,12 @@ export async function issueAccessClaim(options: {
store: HeimdallStore;
input: IssueAccessClaimInput;
}): Promise<IssuedAccessClaimResult> {
const profile = getAppProfile(options.input.appSlug);
const profile = await resolveAppProfile(options.store, options.input.appSlug);
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}'.`);
}
const facts = normalizeFacts(options.input.accountId, options.input.linkedIdentities, options.input.facts);
const factSet = new Set(facts);
const sharedCapabilities = evaluateSharedCapabilities(profile, {

View file

@ -44,6 +44,8 @@ export interface HeimdallConfig {
appRuntimeIds?: Partial<Record<AppSlug, string[]>>;
appBackendCallbacks: Partial<Record<AppSlug, string[]>>;
bifrostPatronSupportEndpoint?: string;
/** Operator secret gating runtime app registration. Unset means registration is closed. */
appRegistrationSecret?: string;
bifrostPatronSupportSecret?: string;
storage: StorageConfig;
providers: Record<Provider, ProviderClientConfig>;
@ -300,6 +302,9 @@ export function loadConfig(
}
if (env.GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET) {
if (env.GC_ACCESS_APP_REGISTRATION_SECRET) {
config.appRegistrationSecret = env.GC_ACCESS_APP_REGISTRATION_SECRET;
}
config.bifrostPatronSupportSecret = env.GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET;
}

View file

@ -2,9 +2,27 @@ export const providers = ["discord", "patreon", "github", "twitch", "youtube", "
export type Provider = (typeof providers)[number];
/** Apps shipped with Heimdall. Seed data, not the set of permissible apps. */
export const appSlugs = ["repixelizer", "streampixels", "bifrost", "ghostlight"] as const;
export type AppSlug = (typeof appSlugs)[number];
export type BuiltInAppSlug = (typeof appSlugs)[number];
/**
* An app identifier. Always a string on the wire; it was narrowed to a union
* only because every app was known at build time. Validity is decided by the
* app registry, not the type system.
*/
export type AppSlug = string;
/**
* Shape check only. Whether an app exists is a registry question, and callers
* without a store — the offline token verifier, for one — can only check that
* an identifier is well formed. A host app verifying its own tokens should
* compare aud against its own slug rather than trusting a shape.
*/
export function isAppSlug(value: unknown): value is AppSlug {
return typeof value === "string" && /^[a-z][a-z0-9_-]{1,62}$/.test(value);
}
export const oauthModes = ["sign_in", "link", "connect"] as const;

View file

@ -9,7 +9,7 @@ import {
import { type FastifyInstance } from "fastify";
import { getHeimdallRuntimeContext, verifyRefreshToken } from "./app.js";
import { executeHeimdallAccessPlugin, HEIMDALL_ACCESS_PLUGIN_ID, type EvePluginAbiRequest } from "./access-plugin.js";
import { appSlugs, oauthModes, providers, type AppSlug, type OAuthEntitlementPolicy, type OAuthMode, type Provider } from "./contracts.js";
import { isAppSlug, oauthModes, providers, type AppSlug, type OAuthEntitlementPolicy, type OAuthMode, type Provider } from "./contracts.js";
import { type HeimdallConfig } from "./config.js";
import { openPrivateEnvelope, sealPrivateEnvelope, type HeimdallPrivateEnvelope } from "./private-command-security.js";
@ -61,7 +61,7 @@ export async function startHeimdallPrivateCommandPlane(
throw new Error("Heimdall private commands require the typed encrypted MessagePack envelope.");
}
const envelope = decode(Buffer.from(request.payload, "base64")) as HeimdallPrivateEnvelope;
if (!appSlugs.includes(envelope.appSlug as AppSlug)) throw new Error("Unknown Heimdall app binding.");
if (!isAppSlug(envelope.appSlug)) throw new Error("Unknown Heimdall app binding.");
const appSlug = envelope.appSlug as AppSlug;
const secret = config.appSharedSecrets[appSlug];
if (!secret) throw new Error("Heimdall app binding has no private command secret.");

View file

@ -15,6 +15,8 @@ import {
type StoredAuthCompletion,
type StoredCapabilityGrant,
type StoredLinkedIdentity,
type RegisterAppInput,
type StoredRegisteredApp,
type StoredSession,
type StoredPrivateCommandReceipt,
type UpsertLinkedIdentityInput,
@ -37,6 +39,7 @@ function isGrantActive(grant: StoredCapabilityGrant, appSlug: AppSlug, at: strin
}
export class InMemoryStore implements HeimdallStore {
private readonly registeredApps = new Map<string, StoredRegisteredApp>();
private readonly accounts = new Map<string, StoredAccount>();
private readonly linkedIdentities = new Map<string, StoredLinkedIdentity>();
private readonly grants = new Map<string, StoredCapabilityGrant>();
@ -47,6 +50,36 @@ export class InMemoryStore implements HeimdallStore {
private readonly entitlementSnapshots = new Map<string, CreateEntitlementSnapshotInput>();
private readonly auditEvents = new Map<string, CreateAuditEventInput>();
async registerApp(input: RegisterAppInput): Promise<StoredRegisteredApp> {
const existing = this.registeredApps.get(input.slug);
const record: StoredRegisteredApp = {
slug: input.slug,
displayName: input.displayName,
profileVersion: input.profileVersion,
createdAt: existing?.createdAt ?? input.registeredAt,
updatedAt: input.registeredAt,
identityProviders: [...input.identityProviders],
entitlementSources: [...input.entitlementSources],
managedConnectionProviders: [...input.managedConnectionProviders],
capabilities: structuredClone(input.capabilities),
redirectUris: [...input.redirectUris],
clientSecretHash: input.clientSecretHash,
};
this.registeredApps.set(record.slug, record);
return structuredClone(record);
}
async findRegisteredApp(slug: string): Promise<StoredRegisteredApp | null> {
const record = this.registeredApps.get(slug);
return record ? structuredClone(record) : null;
}
async listRegisteredApps(): Promise<StoredRegisteredApp[]> {
return [...this.registeredApps.values()]
.sort((left, right) => left.slug.localeCompare(right.slug))
.map((record) => structuredClone(record));
}
async ensureSchema(): Promise<void> {
return;
}

View file

@ -1,5 +1,6 @@
import { randomUUID } from "node:crypto";
import { Pool, type PoolClient, type QueryResultRow } from "pg";
import { type CapabilityDefinition } from "../capability-rules.js";
import { type AppSlug, type HeimdallAuthAttemptStatus, type LinkedIdentityInput, type Provider } from "../contracts.js";
import { CREATE_SCHEMA_SQL } from "./schema.js";
import {
@ -17,6 +18,8 @@ import {
type StoredAuthCompletion,
type StoredCapabilityGrant,
type StoredLinkedIdentity,
type RegisterAppInput,
type StoredRegisteredApp,
type StoredSession,
type StoredPrivateCommandReceipt,
type UpsertLinkedIdentityInput,
@ -61,6 +64,20 @@ interface GrantRow extends QueryResultRow {
updated_at: string;
}
interface RegisteredAppRow extends QueryResultRow {
slug: string;
display_name: string;
profile_version: string;
created_at: string;
updated_at: string;
identity_providers: Provider[];
entitlement_sources: Provider[];
managed_connection_providers: Provider[];
capabilities_json: CapabilityDefinition[];
redirect_uris: string[];
client_secret_hash: string | null;
}
interface SessionRow extends QueryResultRow {
id: string;
account_id: string;
@ -282,6 +299,63 @@ function mapAuthAttemptRow(row: AuthAttemptRow): StoredAuthAttempt {
export class PostgresStore implements HeimdallStore {
constructor(private readonly pool: Pick<Pool, "query" | "end">) {}
async registerApp(input: RegisterAppInput): Promise<StoredRegisteredApp> {
// Re-registering an app keeps its original created_at: the record is the
// same app being updated, not a new one, and RFC 7592 treats management as
// an update to an existing registration.
const result = await this.pool.query<RegisteredAppRow>(
`
INSERT INTO registered_apps (
slug, display_name, profile_version, created_at, updated_at,
identity_providers, entitlement_sources, managed_connection_providers,
capabilities_json, redirect_uris, client_secret_hash
)
VALUES ($1, $2, $3, $4, $4, $5, $6, $7, $8, $9, $10)
ON CONFLICT (slug)
DO UPDATE SET
display_name = EXCLUDED.display_name,
profile_version = EXCLUDED.profile_version,
updated_at = EXCLUDED.updated_at,
identity_providers = EXCLUDED.identity_providers,
entitlement_sources = EXCLUDED.entitlement_sources,
managed_connection_providers = EXCLUDED.managed_connection_providers,
capabilities_json = EXCLUDED.capabilities_json,
redirect_uris = EXCLUDED.redirect_uris,
client_secret_hash = COALESCE(EXCLUDED.client_secret_hash, registered_apps.client_secret_hash)
RETURNING *
`,
[
input.slug,
input.displayName,
input.profileVersion,
input.registeredAt,
JSON.stringify(input.identityProviders),
JSON.stringify(input.entitlementSources),
JSON.stringify(input.managedConnectionProviders),
JSON.stringify(input.capabilities),
JSON.stringify(input.redirectUris),
input.clientSecretHash,
],
);
return mapRegisteredApp(result.rows[0]!);
}
async findRegisteredApp(slug: string): Promise<StoredRegisteredApp | null> {
const result = await this.pool.query<RegisteredAppRow>(
`SELECT * FROM registered_apps WHERE slug = $1`,
[slug],
);
const row = result.rows[0];
return row ? mapRegisteredApp(row) : null;
}
async listRegisteredApps(): Promise<StoredRegisteredApp[]> {
const result = await this.pool.query<RegisteredAppRow>(
`SELECT * FROM registered_apps ORDER BY slug ASC`,
);
return result.rows.map(mapRegisteredApp);
}
async ensureSchema(): Promise<void> {
await this.pool.query(CREATE_SCHEMA_SQL);
}
@ -773,3 +847,19 @@ export function createPostgresStore(databaseUrl: string): HeimdallStore {
});
return new PostgresStore(pool);
}
function mapRegisteredApp(row: RegisteredAppRow): StoredRegisteredApp {
return {
slug: row.slug,
displayName: row.display_name,
profileVersion: row.profile_version,
createdAt: new Date(row.created_at).toISOString(),
updatedAt: new Date(row.updated_at).toISOString(),
identityProviders: row.identity_providers,
entitlementSources: row.entitlement_sources,
managedConnectionProviders: row.managed_connection_providers,
capabilities: row.capabilities_json,
redirectUris: row.redirect_uris,
clientSecretHash: row.client_secret_hash,
};
}

View file

@ -1,4 +1,18 @@
export const CREATE_SCHEMA_SQL = `
CREATE TABLE IF NOT EXISTS registered_apps (
slug TEXT PRIMARY KEY,
display_name TEXT NOT NULL,
profile_version TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL,
identity_providers JSONB NOT NULL,
entitlement_sources JSONB NOT NULL,
managed_connection_providers JSONB NOT NULL,
capabilities_json JSONB NOT NULL,
redirect_uris JSONB NOT NULL,
client_secret_hash TEXT
);
CREATE TABLE IF NOT EXISTS accounts (
id TEXT PRIMARY KEY,
created_at TIMESTAMPTZ NOT NULL,

View file

@ -1,3 +1,4 @@
import { type CapabilityDefinition } from "../capability-rules.js";
import {
type AppSlug,
type HeimdallAuthAttemptStatus,
@ -6,6 +7,40 @@ import {
type Provider,
} from "../contracts.js";
/**
* An app registered at runtime.
*
* The built-in profiles are seed data of the same shape; nothing here is
* special-cased for them. clientSecretHash is stored rather than the secret,
* so a database read cannot impersonate a registered app.
*/
export interface StoredRegisteredApp {
slug: string;
displayName: string;
profileVersion: string;
createdAt: string;
updatedAt: string;
identityProviders: Provider[];
entitlementSources: Provider[];
managedConnectionProviders: Provider[];
capabilities: CapabilityDefinition[];
redirectUris: string[];
clientSecretHash: string | null;
}
export interface RegisterAppInput {
slug: string;
displayName: string;
profileVersion: string;
registeredAt: string;
identityProviders: Provider[];
entitlementSources: Provider[];
managedConnectionProviders: Provider[];
capabilities: CapabilityDefinition[];
redirectUris: string[];
clientSecretHash: string | null;
}
export interface StoredAccount {
id: string;
createdAt: string;
@ -192,6 +227,9 @@ export interface StoredPrivateCommandReceipt {
export type CreatePrivateCommandReceiptInput = StoredPrivateCommandReceipt;
export interface HeimdallStore {
registerApp(input: RegisterAppInput): Promise<StoredRegisteredApp>;
findRegisteredApp(slug: string): Promise<StoredRegisteredApp | null>;
listRegisteredApps(): Promise<StoredRegisteredApp[]>;
ensureSchema(): Promise<void>;
close(): Promise<void>;
createAccount(input: CreateAccountInput): Promise<StoredAccount>;

View file

@ -1,5 +1,5 @@
import { createPublicKey, type KeyObject } from "node:crypto";
import { appSlugs, providers, type AccessClaimPayload, type AppSlug, type LinkedIdentityInput, type Provider } from "./contracts.js";
import { isAppSlug, providers, type AccessClaimPayload, type AppSlug, type LinkedIdentityInput, type Provider } from "./contracts.js";
import { type PublicSigningJwk, verifyJwt } from "./signing.js";
export interface HeimdallVerifierOptions {
@ -52,7 +52,7 @@ function parseAccessClaimPayload(payload: Record<string, unknown>): AccessClaimP
payload.typ !== "heimdall_access" ||
typeof payload.iss !== "string" ||
typeof payload.aud !== "string" ||
!appSlugs.includes(payload.aud as AppSlug) ||
!isAppSlug(payload.aud) ||
typeof payload.sub !== "string" ||
typeof payload.sid !== "string" ||
typeof payload.jti !== "string" ||
@ -64,7 +64,7 @@ function parseAccessClaimPayload(payload: Record<string, unknown>): AccessClaimP
!payload.app ||
typeof payload.app !== "object" ||
typeof (payload.app as Record<string, unknown>).slug !== "string" ||
!appSlugs.includes((payload.app as Record<string, unknown>).slug as AppSlug) ||
!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") ||

View file

@ -243,8 +243,7 @@ export function buildHeimdallProviderAdvertisement(options: { updatedAt: string
},
};
}),
appProfiles: appSlugs.map((appSlug) => {
const profile = appProfiles[appSlug];
appProfiles: Object.values(appProfiles).map((profile) => {
return {
slug: profile.slug,
displayName: profile.displayName,

View file

@ -0,0 +1,195 @@
import { afterEach, describe, expect, it } from "vitest";
import { type FastifyInstance } from "fastify";
import { buildApp } from "../src/app.js";
import { type HeimdallConfig } from "../src/config.js";
import { identityFacts } from "../src/facts.js";
const REGISTRATION_SECRET = "operator-registration-secret";
function createTestConfig(overrides: Partial<HeimdallConfig> = {}): HeimdallConfig {
return {
serviceName: "heimdall",
host: "127.0.0.1",
port: 4100,
workspaceRoot: ".",
dataRoot: "./.heimdall-data",
cultCachePath: "./.heimdall-data/cultcache/heimdall.service.cc",
publicBaseUrl: "https://heimdall.test",
issuer: "https://heimdall.test",
daemonId: "test-heimdall",
idunnRudpHealth: undefined,
idunnHealthContract: "heimdall.cultnet-rudp-provider-health",
providerHealthIdentityPath: "./.heimdall-data/provider-health-identity.cc",
sessionTtlSeconds: 3600,
refreshTtlSeconds: 60 * 60 * 24 * 30,
stateTtlSeconds: 600,
completionTtlSeconds: 300,
bootstrapSigningPrivateKeyOnMissing: false,
tokenEncryptionKeyBase64: Buffer.alloc(32, 7).toString("base64"),
appSharedSecrets: {},
appBackendCallbacks: {},
storage: { backend: "memory", applySchemaOnStartup: true },
providers: {
discord: { clientId: "discord-client", clientSecret: "discord-secret" },
patreon: { clientId: "patreon-client", clientSecret: "patreon-secret" },
github: { clientId: "github-client", clientSecret: "github-secret" },
twitch: { clientId: "twitch-client", clientSecret: "twitch-secret" },
youtube: { clientId: "youtube-client", clientSecret: "youtube-secret" },
spotify: { clientId: "spotify-client", clientSecret: "spotify-secret" },
},
...overrides,
} as HeimdallConfig;
}
const registration = {
slug: "erycina",
displayName: "Erycina",
identityProviders: ["discord"],
redirectUris: ["https://erycina.test/auth/callback"],
capabilities: [
{ key: "viewer_access", mode: "shared", summary: "Signed-in viewer.", anyOf: [identityFacts.authenticated] },
],
};
const apps: FastifyInstance[] = [];
afterEach(async () => {
while (apps.length > 0) await apps.pop()!.close();
});
async function buildOpenInstance(): Promise<FastifyInstance> {
const app = await buildApp({ config: createTestConfig({ appRegistrationSecret: REGISTRATION_SECRET }) });
apps.push(app);
return app;
}
describe("POST /v1/apps", () => {
it("is closed on an instance with no registration secret configured", async () => {
// A fresh instance must not be accidentally open. Heimdall is an OAuth
// provider; an open registration endpoint lets anyone create a client that
// starts provider flows under this instance's identity.
const app = await buildApp({ config: createTestConfig() });
apps.push(app);
const response = await app.inject({ method: "POST", url: "/v1/apps", payload: registration });
expect(response.statusCode).toBe(404);
expect(response.json().error).toBe("registration_closed");
});
it("refuses a request with no registration secret", async () => {
const app = await buildOpenInstance();
const response = await app.inject({ method: "POST", url: "/v1/apps", payload: registration });
expect(response.statusCode).toBe(401);
});
it("refuses a request with the wrong registration secret", async () => {
const app = await buildOpenInstance();
const response = await app.inject({
method: "POST",
url: "/v1/apps",
headers: { "x-heimdall-registration-secret": "not-it" },
payload: registration,
});
expect(response.statusCode).toBe(401);
});
it("registers an app and returns an RFC 7591 shaped response", async () => {
const app = await buildOpenInstance();
const response = await app.inject({
method: "POST",
url: "/v1/apps",
headers: { "x-heimdall-registration-secret": REGISTRATION_SECRET },
payload: registration,
});
expect(response.statusCode).toBe(201);
const body = response.json();
expect(body.client_id).toBe("erycina");
expect(body.client_secret).toBeTruthy();
expect(body.client_name).toBe("Erycina");
expect(body.redirect_uris).toEqual(["https://erycina.test/auth/callback"]);
expect(typeof body.client_id_issued_at).toBe("number");
});
it("rejects an invalid registration with the problems that caused it", async () => {
const app = await buildOpenInstance();
const response = await app.inject({
method: "POST",
url: "/v1/apps",
headers: { "x-heimdall-registration-secret": REGISTRATION_SECRET },
payload: { ...registration, slug: "bifrost" },
});
expect(response.statusCode).toBe(400);
expect(response.json().error).toBe("invalid_client_metadata");
expect(JSON.stringify(response.json().problems)).toMatch(/reserved by a built-in/);
});
it("rejects a capability rule naming a fact Heimdall does not produce", async () => {
const app = await buildOpenInstance();
const response = await app.inject({
method: "POST",
url: "/v1/apps",
headers: { "x-heimdall-registration-secret": REGISTRATION_SECRET },
payload: {
...registration,
capabilities: [{ key: "admin", mode: "shared", summary: "x", anyOf: ["invented.superuser"] }],
},
});
expect(response.statusCode).toBe(400);
expect(JSON.stringify(response.json().problems)).toMatch(/Unknown term/);
});
});
describe("app discovery after registration", () => {
it("lists a registered app alongside the built-ins", async () => {
const app = await buildOpenInstance();
await app.inject({
method: "POST",
url: "/v1/apps",
headers: { "x-heimdall-registration-secret": REGISTRATION_SECRET },
payload: registration,
});
const listed = (await app.inject({ method: "GET", url: "/v1/apps" })).json();
const slugs = listed.apps.map((profile: { slug: string }) => profile.slug);
expect(slugs).toContain("erycina");
expect(slugs).toContain("bifrost");
});
it("serves a registered app's profile by slug", async () => {
const app = await buildOpenInstance();
await app.inject({
method: "POST",
url: "/v1/apps",
headers: { "x-heimdall-registration-secret": REGISTRATION_SECRET },
payload: registration,
});
const response = await app.inject({ method: "GET", url: "/v1/apps/erycina" });
expect(response.statusCode).toBe(200);
expect(response.json().displayName).toBe("Erycina");
});
it("404s an app nobody registered, rather than serving an empty profile", async () => {
const app = await buildOpenInstance();
const response = await app.inject({ method: "GET", url: "/v1/apps/nobody" });
expect(response.statusCode).toBe(404);
expect(response.json().error).toBe("unknown_app");
});
it("still serves the built-in profiles", async () => {
const app = await buildOpenInstance();
const response = await app.inject({ method: "GET", url: "/v1/apps/repixelizer" });
expect(response.statusCode).toBe(200);
expect(response.json().slug).toBe("repixelizer");
});
});

218
tests/app-registry.test.ts Normal file
View file

@ -0,0 +1,218 @@
import { beforeEach, describe, expect, it } from "vitest";
import {
AppRegistrationError,
hashClientSecret,
isBuiltInApp,
listAppProfiles,
registerApp,
resolveAppProfile,
validateAppRegistration,
verifyClientSecret,
type AppRegistrationRequest,
} from "../src/app-registry.js";
import { evaluateCapabilityRules } from "../src/capability-rules.js";
import { entitlementFacts, grantFacts, identityFacts } from "../src/facts.js";
import { InMemoryStore } from "../src/store/in-memory.js";
const request = (overrides: Partial<AppRegistrationRequest> = {}): AppRegistrationRequest => ({
slug: "erycina",
displayName: "Erycina",
identityProviders: ["discord"],
redirectUris: ["https://erycina.example/auth/callback"],
capabilities: [
{ key: "viewer_access", mode: "shared", summary: "Signed-in viewer.", anyOf: [identityFacts.authenticated] },
],
...overrides,
});
let store: InMemoryStore;
beforeEach(() => {
store = new InMemoryStore();
});
describe("validateAppRegistration", () => {
it("accepts a well-formed registration", () => {
expect(validateAppRegistration(request())).toEqual([]);
});
it("refuses a slug that shadows a built-in app", () => {
// Otherwise a registration inherits a shipped app's audience, which is
// impersonation rather than registration.
const problems = validateAppRegistration(request({ slug: "bifrost" }));
expect(problems[0]!.reason).toMatch(/reserved by a built-in/);
});
it("refuses slugs that would be awkward as a JWT audience or storage key", () => {
for (const slug of ["A", "1app", "has space", "has/slash", ""]) {
expect(validateAppRegistration(request({ slug })).some((p) => p.field === "slug")).toBe(true);
}
});
it("refuses an unknown provider", () => {
const problems = validateAppRegistration(request({ identityProviders: ["myspace"] }));
expect(problems.some((p) => p.reason.includes("myspace"))).toBe(true);
});
it("requires at least one identity provider", () => {
expect(validateAppRegistration(request({ identityProviders: [] })).some((p) => p.field === "identityProviders")).toBe(true);
});
it("refuses a capability rule naming a fact Heimdall does not produce", () => {
// The registration gate. An app selects from Heimdall's vocabulary; it
// cannot invent a fact to grant itself something.
const problems = validateAppRegistration(
request({
capabilities: [{ key: "admin", mode: "shared", summary: "x", anyOf: ["invented.superuser"] }],
}),
);
expect(problems.some((p) => p.reason.includes("Unknown term"))).toBe(true);
});
describe("redirect URIs", () => {
it("requires at least one", () => {
expect(validateAppRegistration(request({ redirectUris: [] })).some((p) => p.field === "redirectUris")).toBe(true);
});
it("refuses a relative URI", () => {
expect(validateAppRegistration(request({ redirectUris: ["/callback"] }))[0]!.reason).toMatch(/absolute/);
});
it("refuses plain http off loopback, because that is where a code would leak", () => {
expect(
validateAppRegistration(request({ redirectUris: ["http://erycina.example/cb"] }))[0]!.reason,
).toMatch(/https/);
});
it("allows http on loopback, for local development", () => {
expect(validateAppRegistration(request({ redirectUris: ["http://127.0.0.1:8080/cb"] }))).toEqual([]);
expect(validateAppRegistration(request({ redirectUris: ["http://localhost:8080/cb"] }))).toEqual([]);
});
it("refuses a fragment", () => {
expect(validateAppRegistration(request({ redirectUris: ["https://a.example/cb#x"] }))[0]!.reason).toMatch(/fragment/);
});
});
it("reports every problem rather than stopping at the first", () => {
const problems = validateAppRegistration(request({ slug: "!!", displayName: "", identityProviders: [] }));
expect(problems.length).toBeGreaterThan(2);
});
});
describe("registerApp", () => {
it("stores the app and returns a secret exactly once", async () => {
const { app, clientSecret } = await registerApp(store, request());
expect(app.slug).toBe("erycina");
expect(clientSecret).toBeTruthy();
// The secret is returned, never stored.
expect(app).not.toHaveProperty("clientSecret");
expect(app.clientSecretHash).toBe(hashClientSecret(clientSecret));
});
it("refuses an invalid registration rather than storing a broken profile", async () => {
await expect(registerApp(store, request({ slug: "bifrost" }))).rejects.toBeInstanceOf(AppRegistrationError);
expect(await store.findRegisteredApp("bifrost")).toBeNull();
});
it("keeps the original creation time when an app re-registers", async () => {
const first = await registerApp(store, request(), "2026-01-01T00:00:00.000Z");
const second = await registerApp(store, request({ displayName: "Erycina v2" }), "2026-06-01T00:00:00.000Z");
expect(second.app.createdAt).toBe(first.app.createdAt);
expect(second.app.updatedAt).toBe("2026-06-01T00:00:00.000Z");
expect(second.app.displayName).toBe("Erycina v2");
});
});
describe("verifyClientSecret", () => {
it("accepts the issued secret and rejects anything else", async () => {
const { app, clientSecret } = await registerApp(store, request());
expect(verifyClientSecret(clientSecret, app.clientSecretHash)).toBe(true);
expect(verifyClientSecret("not-the-secret", app.clientSecretHash)).toBe(false);
expect(verifyClientSecret(clientSecret, null)).toBe(false);
});
});
describe("resolveAppProfile", () => {
it("resolves a registered app", async () => {
await registerApp(store, request());
const profile = await resolveAppProfile(store, "erycina");
expect(profile?.displayName).toBe("Erycina");
});
it("resolves a built-in app without touching storage", async () => {
expect((await resolveAppProfile(store, "bifrost"))?.displayName).toBe("Bifrost");
});
it("returns null for an app nobody registered", async () => {
expect(await resolveAppProfile(store, "nope")).toBeNull();
});
it("a built-in cannot be shadowed even if a row exists for it", async () => {
// Registration refuses built-in slugs; this is the second place that holds,
// so a row written by some other path cannot hijack a shipped audience.
await store.registerApp({
slug: "bifrost",
displayName: "Impostor",
profileVersion: "x",
registeredAt: "2026-01-01T00:00:00.000Z",
identityProviders: ["discord"],
entitlementSources: [],
managedConnectionProviders: [],
capabilities: [],
redirectUris: [],
clientSecretHash: null,
});
expect((await resolveAppProfile(store, "bifrost"))?.displayName).toBe("Bifrost");
});
});
describe("a registered profile evaluates like a built-in", () => {
it("grants capabilities through the same evaluator", async () => {
await registerApp(
store,
request({
capabilities: [
{ key: "member_access", mode: "shared", summary: "member", anyOf: [entitlementFacts.appAccess, grantFacts.globalMember] },
{ key: "post_create", mode: "shared", summary: "post", anyOf: ["member_access"] },
],
}),
);
const profile = await resolveAppProfile(store, "erycina");
expect(evaluateCapabilityRules(profile!.capabilities, new Set([grantFacts.globalMember]))).toEqual([
"member_access",
"post_create",
]);
expect(evaluateCapabilityRules(profile!.capabilities, new Set([identityFacts.authenticated]))).toEqual([]);
});
});
describe("listAppProfiles", () => {
it("lists built-ins alongside registered apps", async () => {
await registerApp(store, request());
const slugs = (await listAppProfiles(store)).map((profile) => profile.slug);
expect(slugs).toContain("bifrost");
expect(slugs).toContain("erycina");
});
it("lists each app once", async () => {
await registerApp(store, request());
const slugs = (await listAppProfiles(store)).map((profile) => profile.slug);
expect(new Set(slugs).size).toBe(slugs.length);
});
});
describe("isBuiltInApp", () => {
it("knows the shipped profiles", () => {
expect(isBuiltInApp("repixelizer")).toBe(true);
expect(isBuiltInApp("erycina")).toBe(false);
});
});