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

@ -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,
};
}