App profiles: returnTo allowlist and per-app policy requirement as data

AppProfile gains allowedReturnOrigins (repixelizer/streampixels/bifrost
-> <slug>.gamecult.org, ghostlight -> yggdrasil.gamecult.org per
docs/app-profiles and the existing test fixtures) and an optional
requiredEntitlementPolicyKind, replacing the private command plane's
`appSlug === "ghostlight"` branches with data a future app can declare
for itself. A registered (non-built-in) app's allowedReturnOrigins is
derived from its stored redirectUris' origins — the same shape the
deleted registration validator used to check, now put to use instead of
only being validated at intake.

app-registry.ts also sheds the registration-only surface:
validateAppRegistration, AppRegistrationRequest, RegistrationProblem,
and AppRegistrationError deleted (the previous commit removed their
only writer, HeimdallStore.registerApp). resolveAppProfile/
listAppProfiles/isBuiltInApp are unchanged in shape.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-08 14:22:37 +02:00
commit 29571204da
2 changed files with 57 additions and 111 deletions

View file

@ -3,7 +3,7 @@ import {
type CapabilityDefinition,
type CapabilityMode,
} from "./capability-rules.js";
import { type AppSlug, type LinkedIdentityInput, type Provider } from "./contracts.js";
import { type AppSlug, type LinkedIdentityInput, type OAuthEntitlementPolicy, type Provider } from "./contracts.js";
import { entitlementFacts, grantFacts, identityFacts } from "./facts.js";
export type { CapabilityDefinition, CapabilityMode };
@ -31,6 +31,20 @@ export interface AppProfile {
entitlementSources: Provider[];
managedConnectionProviders: Provider[];
capabilities: CapabilityDefinition[];
/**
* Origins `returnTo` may land on for this app. A caller-chosen returnTo is
* where the browser handoff page postMessages the completion payload
* (src/browser-handoff.ts), so an unlisted origin is an exfiltration
* primitive, not a convenience. Compared by URL origin, not prefix.
*/
allowedReturnOrigins: readonly string[];
/**
* Some apps require the caller to supply an entitlement policy of a
* specific kind on every begin/refresh (ghostlight's caller-owned Discord
* role gate). Data instead of a per-slug branch in the private command
* plane; absent for apps with no such requirement.
*/
requiredEntitlementPolicyKind?: OAuthEntitlementPolicy["kind"];
}
/** The membership signal shared by every app that gates on GameCult membership. */
@ -47,6 +61,7 @@ const repixelizerProfile: AppProfile = {
identityProviders: ["discord", "patreon"],
entitlementSources: ["discord", "patreon"],
managedConnectionProviders: [],
allowedReturnOrigins: ["https://repixelizer.gamecult.org"],
capabilities: [
{
key: "app_access",
@ -88,6 +103,7 @@ const streampixelsProfile: AppProfile = {
identityProviders: ["twitch", "youtube"],
entitlementSources: [],
managedConnectionProviders: ["twitch", "youtube"],
allowedReturnOrigins: ["https://streampixels.gamecult.org"],
capabilities: [
{
key: "viewer_access",
@ -125,6 +141,7 @@ const bifrostProfile: AppProfile = {
identityProviders: ["discord", "patreon"],
entitlementSources: ["discord", "patreon"],
managedConnectionProviders: [],
allowedReturnOrigins: ["https://bifrost.gamecult.org"],
capabilities: [
{
key: "member_access",
@ -142,6 +159,8 @@ const ghostlightProfile: AppProfile = {
identityProviders: ["discord"],
entitlementSources: ["discord"],
managedConnectionProviders: [],
allowedReturnOrigins: ["https://yggdrasil.gamecult.org"],
requiredEntitlementPolicyKind: "discord_role_access",
capabilities: [
{
key: "app_access",
@ -204,3 +223,17 @@ export function supportsProvider(profile: AppProfile, provider: Provider): boole
profile.entitlementSources.includes(provider)
);
}
/**
* Whether `returnTo` may be handed back to the browser for this app. Origin
* comparison only (scheme + host + port) — the allowlist names an app's
* origin once rather than every path it might redirect to. An unparseable
* URL is refused rather than throwing.
*/
export function isAllowedReturnOrigin(profile: AppProfile, returnTo: string): boolean {
try {
return profile.allowedReturnOrigins.includes(new URL(returnTo).origin);
} catch {
return false;
}
}

View file

@ -1,124 +1,37 @@
// Runtime app registration.
// App profile resolution: built-in profiles plus whatever is provisioned
// directly in the `registered_apps` table.
//
// 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.
// This used to also own runtime registration (POST /v1/apps): a caller
// self-registered a profile and got back a client_secret nobody ever
// verified. That HTTP surface, its validation, and the minted secret are
// gone (the caller-identity cut). `registered_apps` remains a profile store
// beneath the built-in profiles; a row is now provisioned by direct SQL
// against Postgres (or InMemoryStore.seedRegisteredApp for tests), not by an
// app calling Heimdall.
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 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.
* A registered app's `redirectUris` is the same "where may this app send a
* browser back to" data a runtime registration used to validate; it becomes
* the profile's return-origin allowlist. An unparseable entry is dropped
* rather than widening the allowlist with garbage.
*/
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}'.` });
}
function returnOriginsFromRedirectUris(redirectUris: string[]): string[] {
const origins = new Set<string>();
for (const uri of redirectUris) {
try {
origins.add(new URL(uri).origin);
} catch {
// Dropped: an unparseable redirect URI cannot name a trustworthy origin.
}
}
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 class AppRegistrationError extends Error {
constructor(readonly problems: RegistrationProblem[]) {
super(`App registration rejected: ${problems.map((problem) => problem.reason).join(" ")}`);
this.name = "AppRegistrationError";
}
return [...origins];
}
export function registeredAppToProfile(app: StoredRegisteredApp): AppProfile {
@ -130,13 +43,13 @@ export function registeredAppToProfile(app: StoredRegisteredApp): AppProfile {
entitlementSources: app.entitlementSources,
managedConnectionProviders: app.managedConnectionProviders,
capabilities: app.capabilities,
allowedReturnOrigins: returnOriginsFromRedirectUris(app.redirectUris),
};
}
/**
* 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.
* somehow exists.
*/
export async function resolveAppProfile(store: HeimdallStore, slug: string): Promise<AppProfile | null> {
const builtIn = builtInAppProfiles[slug as keyof typeof builtInAppProfiles];