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,