Accept caller-owned entitlement policy

This commit is contained in:
Meta Vens 2026-04-29 13:22:01 +01:00
commit 5043a5fc9a
13 changed files with 203 additions and 62 deletions

View file

@ -24,6 +24,3 @@ GC_ACCESS_PROVIDER_TWITCH_CLIENT_ID=
GC_ACCESS_PROVIDER_TWITCH_CLIENT_SECRET=
GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_ID=
GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_SECRET=
GC_ACCESS_APP_REPIXELIZER_DISCORD_GUILD_ID=
GC_ACCESS_APP_REPIXELIZER_DISCORD_ALLOWED_ROLE_IDS=

View file

@ -466,7 +466,6 @@ Suggested generic env surface:
- `GC_ACCESS_PROVIDER_DISCORD_CLIENT_ID=...`
- `GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET=...`
- `GC_ACCESS_PROVIDER_DISCORD_BOT_TOKEN=...`
- `GC_ACCESS_PROVIDER_DISCORD_GUILD_ID=...`
- `GC_ACCESS_PROVIDER_PATREON_CLIENT_ID=...`
- `GC_ACCESS_PROVIDER_PATREON_CLIENT_SECRET=...`
- `GC_ACCESS_PROVIDER_PATREON_CAMPAIGN_ID=...`

View file

@ -84,11 +84,13 @@ Goals:
and persistent Postgres storage
- configure the Discord OAuth app redirect URI to
`https://heimdall.gamecult.org/v1/oauth/discord/callback`
- configure Heimdall's Discord client credentials, Repixelizer guild id, and
the Repixelizer Discord access role ids in
`GC_ACCESS_APP_REPIXELIZER_DISCORD_ALLOWED_ROLE_IDS`
- configure Heimdall's Discord client credentials for the Repixelizer-owned
Discord OAuth app
- configure Repixelizer for `GC_ACCESS_MODE=heimdall` and
`GC_ACCESS_ALLOWED_PROVIDERS=discord`
- configure Repixelizer's Discord access policy with its GameCult guild id and
allowed role ids; Repixelizer sends that policy to Heimdall during the
backend-callback OAuth start
- run the live browser OAuth flow and confirm Repixelizer receives the backend
callback, verifies the claim locally, adopts a local session, gates hosted
access, and stamps queued jobs with `account_id` / `session_id`
@ -105,7 +107,8 @@ Deployment/configuration status:
Current Discord policy:
- Heimdall grants Repixelizer `entitlement.app_access` only when the Discord
member has one of the configured allowed role ids
member has one of the role ids Repixelizer sent in its caller-owned
entitlement policy
- launch policy is intentionally role-gated: the GameCult Discord can remain
public, but Repixelizer access is limited to members with either `KLTST`
or the Patreon-synced `Inner Sanctum` role

View file

@ -476,6 +476,7 @@ Deploy and verify the hardened slice in the first real app binding:
- confirm direct backend callback delivery to Repixelizer
- confirm Repixelizer verifies the Heimdall access token locally and gates
hosted routes from the adopted session
- configure Repixelizer access as role-gated Discord access: the GameCult guild
may be public, but the allowed role list should contain the `KLTST` and
Patreon-synced `Inner Sanctum` role ids
- configure Repixelizer access as role-gated Discord access in Repixelizer's
own runtime env: the GameCult guild may be public, but the caller-owned
policy sent to Heimdall should contain the `KLTST` and Patreon-synced
`Inner Sanctum` role ids

View file

@ -98,6 +98,8 @@ verification:
- open `https://repixelizer.gamecult.org/app/`
- start Discord sign-in with an account that has the `KLTST` or
Patreon-synced `Inner Sanctum` role
- confirm Repixelizer sends its app-owned Discord guild/role policy in the
backend-callback OAuth start
- confirm Heimdall receives the Discord callback and evaluates guild role
entitlement
- confirm Repixelizer receives the backend callback, verifies the Heimdall
@ -107,7 +109,10 @@ verification:
Launch policy is role-gated on purpose: the GameCult Discord can remain public,
but Repixelizer access is limited to members with either `KLTST` or the
Patreon-synced `Inner Sanctum` role.
Patreon-synced `Inner Sanctum` role. Repixelizer owns that role policy through
its own runtime env and sends it to Heimdall during backend-callback OAuth
start; Heimdall owns provider OAuth mechanics and claim issuance, not the
per-app role list.
## Immediate Re-entry Instruction

View file

@ -10,6 +10,7 @@ import {
providers,
type AppSlug,
type OAuthHandoff,
type OAuthEntitlementPolicy,
type OAuthMode,
type OAuthConnectionBinding,
type RedeemAuthCompletionRequest,
@ -65,6 +66,7 @@ function buildOAuthStateToken(options: {
returnTo: string;
connection: OAuthConnectionBinding | undefined;
handoff: OAuthHandoff;
entitlementPolicy: OAuthEntitlementPolicy | undefined;
keys: ReturnType<typeof createRuntimeKeyMaterial>;
}): { token: string; expiresAt: string } {
const issuedAt = nowEpochSeconds();
@ -84,6 +86,7 @@ function buildOAuthStateToken(options: {
return_to: options.returnTo,
connection: options.connection ?? null,
handoff: options.handoff,
entitlement_policy: options.entitlementPolicy ?? null,
};
const token = signJwt(payload as unknown as Record<string, unknown>, options.keys);
@ -104,6 +107,18 @@ function parseOAuthStatePayload(payload: Record<string, unknown>): OAuthStatePay
((handoff as Record<string, unknown>).kind === "backend_callback" &&
typeof (handoff as Record<string, unknown>).attemptId === "string" &&
typeof (handoff as Record<string, unknown>).callbackUrl === "string")));
const entitlementPolicy = payload.entitlement_policy;
const entitlementPolicyIsValid =
entitlementPolicy === null ||
entitlementPolicy === undefined ||
(typeof entitlementPolicy === "object" &&
entitlementPolicy !== null &&
(entitlementPolicy as Record<string, unknown>).kind === "discord_role_access" &&
typeof (entitlementPolicy as Record<string, unknown>).guildId === "string" &&
Array.isArray((entitlementPolicy as Record<string, unknown>).allowedRoleIds) &&
((entitlementPolicy as Record<string, unknown>).allowedRoleIds as unknown[]).every(
(roleId) => typeof roleId === "string"
));
if (
payload.typ !== "heimdall_oauth_state" ||
typeof payload.provider !== "string" ||
@ -120,7 +135,8 @@ function parseOAuthStatePayload(payload: Record<string, unknown>): OAuthStatePay
typeof payload.iat !== "number" ||
typeof payload.nbf !== "number" ||
typeof payload.exp !== "number" ||
!handoffIsValid
!handoffIsValid ||
!entitlementPolicyIsValid
) {
return null;
}
@ -129,6 +145,9 @@ function parseOAuthStatePayload(payload: Record<string, unknown>): OAuthStatePay
if (!normalizedPayload.handoff) {
normalizedPayload.handoff = { kind: "browser_completion" };
}
if (!normalizedPayload.entitlement_policy) {
normalizedPayload.entitlement_policy = null;
}
return normalizedPayload;
}
@ -171,6 +190,42 @@ function normalizeOAuthHandoff(value: OAuthStartRequest["handoff"]): OAuthHandof
throw new Error("Invalid OAuth handoff definition.");
}
function normalizeEntitlementPolicy(value: OAuthStartRequest["entitlementPolicy"]): OAuthEntitlementPolicy | undefined {
if (!value) {
return undefined;
}
if (
value.kind === "discord_role_access" &&
typeof value.guildId === "string" &&
value.guildId.trim() &&
Array.isArray(value.allowedRoleIds)
) {
const allowedRoleIds = value.allowedRoleIds.map((roleId) => roleId.trim()).filter(Boolean);
if (allowedRoleIds.length) {
return {
kind: "discord_role_access",
guildId: value.guildId.trim(),
allowedRoleIds,
};
}
}
throw new Error("Invalid entitlement policy definition.");
}
function acceptsBackendPolicy(appSlug: AppSlug, handoff: OAuthHandoff): boolean {
if (handoff.kind !== "backend_callback") {
return false;
}
if (appSlug === "repixelizer") {
return handoff.callbackUrl === "https://repixelizer.gamecult.org/api/auth/heimdall/callback";
}
return false;
}
async function maybeDeliverBackendHandoff(handoff: OAuthHandoff, payload: BackendHandoffPayload): Promise<void> {
if (handoff.kind !== "backend_callback") {
return;
@ -281,6 +336,21 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
callbackUrl: { type: "string", format: "uri" },
},
},
entitlementPolicy: {
type: "object",
required: ["kind", "guildId", "allowedRoleIds"],
additionalProperties: false,
properties: {
kind: { type: "string", enum: ["discord_role_access"] },
guildId: { type: "string", minLength: 1 },
allowedRoleIds: {
type: "array",
minItems: 1,
items: { type: "string", minLength: 1 },
uniqueItems: true,
},
},
},
},
},
},
@ -308,6 +378,23 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
detail: error instanceof Error ? error.message : "Invalid OAuth handoff definition.",
};
}
let entitlementPolicy: OAuthEntitlementPolicy | undefined;
try {
entitlementPolicy = normalizeEntitlementPolicy(request.body.entitlementPolicy);
} catch (error) {
reply.code(400);
return {
error: "invalid_entitlement_policy",
detail: error instanceof Error ? error.message : "Invalid entitlement policy definition.",
};
}
if (entitlementPolicy && !acceptsBackendPolicy(profile.slug, handoff)) {
reply.code(400);
return {
error: "untrusted_entitlement_policy",
detail: "Caller-supplied entitlement policy is only accepted for trusted backend callback handoffs.",
};
}
const providerConfig = config.providers[provider];
if (!providerConfig.clientId) {
@ -328,6 +415,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
returnTo: request.body.returnTo,
connection: request.body.connection,
handoff,
entitlementPolicy,
keys,
});
@ -550,6 +638,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
appSlug: statePayload.app_slug,
accountId: account.id,
connection: statePayload.connection,
entitlementPolicy: statePayload.entitlement_policy,
},
identity,
tokenSet,

View file

@ -11,11 +11,6 @@ export interface StorageConfig {
applySchemaOnStartup: boolean;
}
export interface RepixelizerBindingConfig {
discordGuildId?: string;
discordAllowedRoleIds: string[];
}
export interface HeimdallConfig {
serviceName: string;
host: string;
@ -31,9 +26,6 @@ export interface HeimdallConfig {
signingKeyId?: string;
tokenEncryptionKeyBase64?: string;
storage: StorageConfig;
apps: {
repixelizer: RepixelizerBindingConfig;
};
providers: Record<Provider, ProviderClientConfig>;
}
@ -67,17 +59,6 @@ function readBoolean(envValue: string | undefined, fallback: boolean): boolean {
return fallback;
}
function readCsv(envValue: string | undefined): string[] {
if (!envValue) {
return [];
}
return envValue
.split(",")
.map((value) => value.trim())
.filter(Boolean);
}
function readProviderConfig(env: NodeJS.ProcessEnv, provider: Provider): ProviderClientConfig {
const prefix = `GC_ACCESS_PROVIDER_${provider.toUpperCase()}`;
const config: ProviderClientConfig = {};
@ -120,11 +101,6 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): HeimdallConfig
backend: storageBackend,
applySchemaOnStartup: readBoolean(env.GC_ACCESS_APPLY_SCHEMA_ON_STARTUP, true),
},
apps: {
repixelizer: {
discordAllowedRoleIds: readCsv(env.GC_ACCESS_APP_REPIXELIZER_DISCORD_ALLOWED_ROLE_IDS),
},
},
providers: providersConfig,
};
@ -149,9 +125,5 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): HeimdallConfig
config.storage.databaseUrl = env.GC_ACCESS_DATABASE_URL;
}
if (env.GC_ACCESS_APP_REPIXELIZER_DISCORD_GUILD_ID) {
config.apps.repixelizer.discordGuildId = env.GC_ACCESS_APP_REPIXELIZER_DISCORD_GUILD_ID;
}
return config;
}

View file

@ -36,6 +36,14 @@ export interface OAuthBackendCallbackHandoff {
export type OAuthHandoff = OAuthBrowserCompletionHandoff | OAuthBackendCallbackHandoff;
export interface DiscordRoleEntitlementPolicy {
kind: "discord_role_access";
guildId: string;
allowedRoleIds: string[];
}
export type OAuthEntitlementPolicy = DiscordRoleEntitlementPolicy;
export interface OAuthStartRequest {
appSlug: AppSlug;
mode: OAuthMode;
@ -43,6 +51,7 @@ export interface OAuthStartRequest {
connection?: OAuthConnectionBinding;
handoff?: OAuthHandoff;
requestedScopes?: string[];
entitlementPolicy?: OAuthEntitlementPolicy;
}
export interface OAuthStatePayload {
@ -60,6 +69,7 @@ export interface OAuthStatePayload {
return_to: string;
connection: OAuthConnectionBinding | null;
handoff: OAuthHandoff | null;
entitlement_policy: OAuthEntitlementPolicy | null;
}
export interface LinkedIdentityInput {

View file

@ -1,5 +1,10 @@
import { Buffer } from "node:buffer";
import { type AppSlug, type OAuthConnectionBinding, type Provider } from "./contracts.js";
import {
type AppSlug,
type OAuthConnectionBinding,
type OAuthEntitlementPolicy,
type Provider,
} from "./contracts.js";
import { type HeimdallConfig } from "./config.js";
import { entitlementFacts } from "./facts.js";
import { type CreateEntitlementSnapshotInput } from "./store/types.js";
@ -32,6 +37,7 @@ export interface OAuthCallbackContext {
appSlug: AppSlug;
accountId: string;
connection: OAuthConnectionBinding | null;
entitlementPolicy: OAuthEntitlementPolicy | null;
}
export interface OAuthProviderRuntime {
@ -166,12 +172,12 @@ async function evaluateDiscordEntitlements(options: {
return { facts: [], snapshots: [] };
}
const guildId = options.config.apps.repixelizer.discordGuildId;
const allowedRoleIds = options.config.apps.repixelizer.discordAllowedRoleIds;
if (!guildId) {
const policy = options.callback.entitlementPolicy;
if (!policy || policy.kind !== "discord_role_access") {
return { facts: [], snapshots: [] };
}
const guildId = policy.guildId;
const allowedRoleIds = policy.allowedRoleIds;
const response = await fetch(
`https://discord.com/api/v10/users/@me/guilds/${guildId}/member`,
@ -233,7 +239,7 @@ async function evaluateDiscordEntitlements(options: {
? "Matched a configured Repixelizer access role."
: allowedRoleIds.length
? "User is in the guild but lacks the configured Repixelizer access role."
: "No Repixelizer Discord role ids are configured.",
: "Repixelizer did not supply any Discord role ids in its entitlement policy.",
rawSummaryJson: {
guildId,
roles,

View file

@ -13,3 +13,4 @@
{"ts": "2026-04-29T10:53:44+00:00", "type": "design", "status": "accepted", "note": "Repixelizer Discord launch policy is intentionally role-gated: the GameCult guild can remain public, but Heimdall should grant Repixelizer app access only to members with the Cultist role configured in GC_ACCESS_APP_REPIXELIZER_DISCORD_ALLOWED_ROLE_IDS."}
{"ts": "2026-04-29T11:39:36+00:00", "type": "deployment", "status": "accepted", "note": "Heimdall is deployed on Yggdrasil behind nginx at https://heimdall.gamecult.org with Postgres storage, file-backed Ed25519 signing key bootstrap, configured token custody, and public JWKS/discovery/health checks passing. Repixelizer is deployed at https://repixelizer.gamecult.org in Heimdall mode with Discord as the only provider, required access enabled, and queue protection enabled; public auth-start returns a Discord authorization URL using the Heimdall callback and Repixelizer backend handoff."}
{"ts": "2026-04-29T12:06:26+00:00", "type": "config", "status": "accepted", "note": "Repixelizer Discord access now accepts either KLTST (861962027550244914) or the Patreon-synced Inner Sanctum role (1497585425491955894) via GC_ACCESS_APP_REPIXELIZER_DISCORD_ALLOWED_ROLE_IDS."}
{"ts": "2026-04-29T12:19:57+00:00", "type": "design", "status": "accepted", "note": "Repixelizer Discord role policy moved out of Heimdall app-specific env. Repixelizer owns the GameCult guild and role list through REPIXELIZER_ACCESS_DISCORD_* and sends a caller-owned discord_role_access policy in the trusted backend-callback OAuth start; Heimdall keeps provider OAuth credentials/callback mechanics and evaluates the supplied policy."}

View file

@ -73,7 +73,7 @@ accepted_design:
- The first stateful slice adds durable auth/control-plane storage plus a real Discord callback path for Repixelizer.
- Repixelizer has consumed the Heimdall backend-callback flow in its hosted web layer; Heimdall no longer needs to wait on Repixelizer refactoring before live Discord launch work.
- Heimdall is deployed on Yggdrasil at `https://heimdall.gamecult.org` with nginx/TLS, Postgres storage, file-backed signing-key bootstrap, configured token custody, and passing public health/discovery/JWKS checks.
- Repixelizer is deployed on Yggdrasil at `https://repixelizer.gamecult.org` with `GC_ACCESS_MODE=heimdall`, `GC_ACCESS_ALLOWED_PROVIDERS=discord`, required access, and queue protection enabled.
- Repixelizer is deployed on Yggdrasil at `https://repixelizer.gamecult.org` with `GC_ACCESS_MODE=heimdall`, `GC_ACCESS_ALLOWED_PROVIDERS=discord`, required access, queue protection enabled, and app-owned Discord guild/role policy sent to Heimdall during backend-callback OAuth start.
landed_baseline:
- Shared architecture extracted into its own repo and renamed to Heimdall.
@ -95,5 +95,5 @@ rejected_paths:
reason: reusing auth mechanics does not justify centralizing app-domain audience or product data
current_status:
summary: Heimdall has a live first Yggdrasil deployment for the Discord-only Repixelizer path: TypeScript/Fastify runtime behind nginx/TLS at `https://heimdall.gamecult.org`, Ed25519 JWT signing with bootstrapped file-backed key support, JWKS/discovery exposure, signed OAuth start-state handling, Postgres-backed auth/control-plane persistence, a real Discord callback path, AES-256-GCM token sealing for managed provider credentials at rest, direct backend callback delivery for Repixelizer, and the older one-time completion-code exchange retained as fallback. Repixelizer is deployed at `https://repixelizer.gamecult.org` in Heimdall mode with Discord as the only public provider, required access enabled, and queue protection enabled. Public health/discovery/JWKS/config checks pass, and public auth-start returns a Discord authorization URL using the Heimdall callback plus Repixelizer backend handoff. Patreon, GitHub, Twitch, and YouTube are catalogued providers but their callback runtimes are still not implemented. The key boundary still holds: Heimdall owns auth/control-plane authority and credential custody; app-domain bindings and runtime behavior remain app-owned.
next_action: Run the real browser OAuth flow end to end from `https://repixelizer.gamecult.org/app/` with a Discord account that has the `KLTST` role or the Patreon-synced `Inner Sanctum` role, confirm Heimdall receives the Discord callback, confirms guild role entitlement, delivers the backend callback to Repixelizer, Repixelizer adopts a local httpOnly session, and hosted/queue routes are gated correctly. The public OAuth start URL should request only `identify guilds.members.read`.
summary: Heimdall has a live first Yggdrasil deployment for the Discord-only Repixelizer path: TypeScript/Fastify runtime behind nginx/TLS at `https://heimdall.gamecult.org`, Ed25519 JWT signing with bootstrapped file-backed key support, JWKS/discovery exposure, signed OAuth start-state handling, Postgres-backed auth/control-plane persistence, a real Discord callback path, AES-256-GCM token sealing for managed provider credentials at rest, direct backend callback delivery for Repixelizer, and the older one-time completion-code exchange retained as fallback. Repixelizer is deployed at `https://repixelizer.gamecult.org` in Heimdall mode with Discord as the only public provider, required access enabled, queue protection enabled, and app-owned Discord guild/role policy sent to Heimdall in trusted backend-callback OAuth starts. Public health/discovery/JWKS/config checks pass, and public auth-start returns a Discord authorization URL using the Heimdall callback plus Repixelizer backend handoff. Patreon, GitHub, Twitch, and YouTube are catalogued providers but their callback runtimes are still not implemented. The key boundary still holds: Heimdall owns auth/control-plane authority and credential custody; app-domain bindings and runtime behavior remain app-owned.
next_action: Run the real browser OAuth flow end to end from `https://repixelizer.gamecult.org/app/` with a Discord account that has the `KLTST` role or the Patreon-synced `Inner Sanctum` role, confirm Repixelizer sends its caller-owned Discord role policy, Heimdall receives the Discord callback, confirms guild role entitlement, delivers the backend callback to Repixelizer, Repixelizer adopts a local httpOnly session, and hosted/queue routes are gated correctly. The public OAuth start URL should request only `identify guilds.members.read`.

View file

@ -24,12 +24,6 @@ function createTestConfig(): HeimdallConfig {
backend: "memory",
applySchemaOnStartup: true,
},
apps: {
repixelizer: {
discordGuildId: "gamecult-guild",
discordAllowedRoleIds: ["role-repixelizer"],
},
},
providers: {
discord: { clientId: "discord-client", clientSecret: "discord-secret" },
patreon: { clientId: "patreon-client", clientSecret: "patreon-secret" },
@ -198,6 +192,76 @@ describe("Heimdall service", () => {
typ: "heimdall_oauth_state",
provider: "discord",
app_slug: "repixelizer",
entitlement_policy: null,
})
);
}
});
it("rejects caller-owned entitlement policy for browser completion handoffs", async () => {
const app = await buildApp({ config: createTestConfig() });
apps.push(app);
const response = await app.inject({
method: "POST",
url: "/v1/oauth/discord/start",
payload: {
appSlug: "repixelizer",
mode: "sign_in",
returnTo: "https://repixelizer.gamecult.org/app/",
entitlementPolicy: {
kind: "discord_role_access",
guildId: "gamecult-guild",
allowedRoleIds: ["role-repixelizer"],
},
},
});
expect(response.statusCode).toBe(400);
expect(response.json()).toEqual(expect.objectContaining({ error: "untrusted_entitlement_policy" }));
});
it("accepts caller-owned entitlement policy for trusted backend handoffs", async () => {
const app = await buildApp({ config: createTestConfig() });
apps.push(app);
const response = await app.inject({
method: "POST",
url: "/v1/oauth/discord/start",
payload: {
appSlug: "repixelizer",
mode: "sign_in",
returnTo: "https://repixelizer.gamecult.org/app/",
handoff: {
kind: "backend_callback",
attemptId: "attempt-123",
callbackUrl: "https://repixelizer.gamecult.org/api/auth/heimdall/callback",
},
entitlementPolicy: {
kind: "discord_role_access",
guildId: "gamecult-guild",
allowedRoleIds: ["role-repixelizer"],
},
},
});
expect(response.statusCode).toBe(201);
const payload = response.json();
expect(payload.authorizationUrl).toContain("discord.com/oauth2/authorize");
const verified = verifyJwt(payload.stateToken as string, getPublicKey(app));
expect(verified.valid).toBe(true);
if (verified.valid) {
expect(verified.payload).toEqual(
expect.objectContaining({
typ: "heimdall_oauth_state",
provider: "discord",
app_slug: "repixelizer",
entitlement_policy: {
kind: "discord_role_access",
guildId: "gamecult-guild",
allowedRoleIds: ["role-repixelizer"],
},
})
);
}

View file

@ -21,12 +21,6 @@ function createTestConfig(overrides: Partial<HeimdallConfig> = {}): HeimdallConf
backend: "memory",
applySchemaOnStartup: true,
},
apps: {
repixelizer: {
discordGuildId: "gamecult-guild",
discordAllowedRoleIds: ["role-repixelizer"],
},
},
providers: {
discord: {},
patreon: {},