Add Eve access plugin and private auth plane

This commit is contained in:
Meta Vens 2026-08-22 00:44:57 +02:00
commit 19e5109cf4
47 changed files with 1781 additions and 35 deletions

127
src/access-plugin.ts Normal file
View file

@ -0,0 +1,127 @@
export const HEIMDALL_ACCESS_PLUGIN_ID = "gamecult.heimdall.access";
export interface EvePluginAbiRequest {
schema: "gamecult.eve.plugin_abi.request.v1";
pluginId: string;
operation: string;
requestId: string;
input: Record<string, unknown>;
}
export interface EvePluginAbiResponse {
schema: "gamecult.eve.plugin_abi.response.v1";
pluginId: string;
operation: string;
requestId: string;
status: "ok" | "invalid" | "unsupported";
output: Record<string, unknown>;
diagnostics?: Array<Record<string, unknown>>;
}
const accessStates = new Set(["anonymous", "pending", "denied", "authenticated", "expired", "unavailable"]);
export function buildHeimdallAccessPluginAdvertisement() {
return {
schema: "gamecult.eve.plugin_advertisement.v1",
pluginId: HEIMDALL_ACCESS_PLUGIN_ID,
ownerService: "asgard.heimdall",
version: "0.1.0",
manifestAddress: "cultmesh://gamecult/heimdall/plugins/access/manifest",
runtime: {
invocationModel: "executable-sidecar",
contract: "gamecult.eve.plugin_abi.v1",
transports: ["cultnet.operation.v0", "in-process-reference"],
authority: ["renderer-independent", "no-access-grant", "no-provider-state-mutation"],
sidecar: {
processKind: "heimdall-daemon-plugin-organ",
protocol: "cultnet.operation.v0",
requestSchema: "gamecult.eve.plugin_abi.request.v1",
responseSchema: "gamecult.eve.plugin_abi.response.v1",
operations: ["describe", "validate", "project"],
commandEnvelope: "gamecult.eve.command_invocation.v1",
receiptSchema: "gamecult.eve.command_result.v1",
stateAuthority: "Heimdall projects access state; the plugin cannot grant access.",
endpoint: "rudp://127.0.0.1:4101",
},
},
schemas: [
"heimdall.access_gate_state.v1",
"heimdall.auth_attempt.v1",
"heimdall.auth_begin_receipt.v1",
"heimdall.auth_completion_receipt.v1",
"heimdall.auth_navigation_receipt.v1",
"heimdall.auth_completion_status.v1",
],
componentKinds: ["heimdall.access_gate", "heimdall.identity", "heimdall.access_status"],
commands: ["heimdall.auth.begin", "heimdall.auth.complete", "app.auth.logout"],
fixtures: ["anonymous", "pending", "denied", "authenticated", "expired", "unavailable"],
navigationOrigins: ["https://discord.com", "https://heimdall.gamecult.org"],
};
}
export function executeHeimdallAccessPlugin(request: EvePluginAbiRequest): EvePluginAbiResponse {
if (request.schema !== "gamecult.eve.plugin_abi.request.v1" || request.pluginId !== HEIMDALL_ACCESS_PLUGIN_ID) {
return response(request, "invalid", {}, "Request does not target the Heimdall access plugin.");
}
if (request.operation === "describe") {
return response(request, "ok", {
pluginId: HEIMDALL_ACCESS_PLUGIN_ID,
version: "0.1.0",
operations: ["describe", "validate", "project"],
componentKinds: ["heimdall.access_gate", "heimdall.identity", "heimdall.access_status"],
commands: ["heimdall.auth.begin", "heimdall.auth.complete", "app.auth.logout"],
capabilities: ["auth.gate", "auth.begin", "auth.complete", "auth.logout"],
authority: ["no-access-grant", "no-provider-state-mutation"],
});
}
const state = record(request.input.state);
const diagnostic = validateState(state);
if (request.operation === "validate") {
return diagnostic ? response(request, "invalid", { valid: false }, diagnostic) : response(request, "ok", { valid: true });
}
if (request.operation === "project") {
if (diagnostic) return response(request, "invalid", {}, diagnostic);
return response(request, "ok", {
component: {
kind: "heimdall.access_gate",
props: {
state: state.state,
title: state.title,
detail: state.detail,
displayName: state.displayName ?? "",
},
},
});
}
return response(request, "unsupported", {}, `Unsupported operation '${request.operation}'.`);
}
function validateState(state: Record<string, unknown>): string | undefined {
if (state.schema !== "heimdall.access_gate_state.v1") return "Access projection requires heimdall.access_gate_state.v1.";
if (typeof state.state !== "string" || !accessStates.has(state.state)) return "Access state is invalid.";
if (typeof state.title !== "string" || !state.title) return "Access title is required.";
if (typeof state.detail !== "string") return "Access detail is required.";
if (typeof state.canBegin !== "boolean" || typeof state.canComplete !== "boolean") return "Access command availability is required.";
return undefined;
}
function response(
request: EvePluginAbiRequest,
status: EvePluginAbiResponse["status"],
output: Record<string, unknown>,
diagnostic?: string,
): EvePluginAbiResponse {
return {
schema: "gamecult.eve.plugin_abi.response.v1",
pluginId: HEIMDALL_ACCESS_PLUGIN_ID,
operation: request.operation,
requestId: request.requestId,
status,
output,
...(diagnostic ? { diagnostics: [{ code: status, message: diagnostic }] } : {}),
};
}
function record(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
}

View file

@ -200,16 +200,16 @@ const bifrostProfile: AppProfile = {
const ghostlightProfile: AppProfile = {
slug: "ghostlight",
displayName: "Ghostlight Dungeon",
profileVersion: "2026-08-19",
profileVersion: "2026-08-22",
identityProviders: ["discord"],
entitlementSources: [],
entitlementSources: ["discord"],
managedConnectionProviders: [],
capabilities: [
{
key: "app_access",
mode: "shared",
summary: "May enter the public Ghostlight Dungeon demo.",
sharedRule: identityFacts.authenticated,
summary: "May enter Ghostlight Dungeon after Heimdall verifies the app-supplied GameCult Discord role policy.",
sharedRule: "entitlement.app_access || grant.global_member || grant.app_access",
},
{
key: "campaign_play",
@ -219,7 +219,11 @@ const ghostlightProfile: AppProfile = {
},
],
evaluateSharedCapabilities(context) {
return context.facts.has(identityFacts.authenticated) ? ["app_access"] : [];
return hasAnyFact(context.facts, [
entitlementFacts.appAccess,
grantFacts.globalMember,
grantFacts.appAccess,
]) ? ["app_access"] : [];
},
};

View file

@ -44,13 +44,25 @@ import {
const MANAGED_CREDENTIAL_REFRESH_SKEW_MS = 5 * 60 * 1000;
interface BuildAppOptions {
export interface BuildAppOptions {
config?: HeimdallConfig;
store?: HeimdallStore;
oauthRuntimes?: Partial<OAuthRuntimeRegistry>;
tokenCustody?: TokenCustody;
}
export interface HeimdallRuntimeContext {
config: HeimdallConfig;
keys: ReturnType<typeof createRuntimeKeyMaterial>;
store: HeimdallStore;
oauthRuntimes: OAuthRuntimeRegistry;
tokenCustody: TokenCustody;
}
export function getHeimdallRuntimeContext(app: FastifyInstance): HeimdallRuntimeContext {
return (app as FastifyInstance & { heimdallContext: HeimdallRuntimeContext }).heimdallContext;
}
function buildDiscovery(config: HeimdallConfig) {
return {
issuer: config.issuer,
@ -117,7 +129,9 @@ function parseOAuthStatePayload(payload: Record<string, unknown>): OAuthStatePay
handoff === undefined ||
(typeof handoff === "object" &&
handoff !== null &&
((handoff as Record<string, unknown>).kind === "browser_completion" ||
(((handoff as Record<string, unknown>).kind === "browser_completion" &&
((handoff as Record<string, unknown>).attemptId === undefined ||
typeof (handoff as Record<string, unknown>).attemptId === "string")) ||
((handoff as Record<string, unknown>).kind === "backend_callback" &&
typeof (handoff as Record<string, unknown>).attemptId === "string" &&
typeof (handoff as Record<string, unknown>).callbackUrl === "string")));
@ -237,7 +251,8 @@ function normalizeOAuthHandoff(value: OAuthStartRequest["handoff"]): OAuthHandof
}
if (value.kind === "browser_completion") {
return value;
const attemptId = value.attemptId?.trim();
return attemptId ? { kind: "browser_completion", attemptId } : { kind: "browser_completion" };
}
if (
@ -678,7 +693,8 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
detail: "Backend callback handoffs are only accepted for configured app callback URLs.",
};
}
if (entitlementPolicy && handoff.kind !== "backend_callback") {
const trustedAppCaller = secretMatches(config.appSharedSecrets[profile.slug], getSharedSecret(request));
if (entitlementPolicy && handoff.kind !== "backend_callback" && !trustedAppCaller) {
reply.code(400);
return {
error: "untrusted_entitlement_policy",
@ -774,8 +790,17 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
return { error: "state_provider_mismatch" };
}
const handoff = statePayload.handoff ?? { kind: "browser_completion" };
const denyBrowserAttempt = async (denialCode: string): Promise<void> => {
if (handoff.kind !== "browser_completion" || !handoff.attemptId) return;
await store.updateAuthAttempt(statePayload.app_slug, handoff.attemptId, {
status: "denied",
at: new Date().toISOString(),
denialCode,
});
};
if (request.query.error) {
await denyBrowserAttempt("provider_error");
if (handoff.kind === "backend_callback") {
await maybeDeliverBackendHandoff(handoff, {
source: "heimdall",
@ -821,6 +846,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
}
if (!request.query.code) {
await denyBrowserAttempt("missing_code");
if (handoff.kind === "backend_callback") {
await maybeDeliverBackendHandoff(handoff, {
source: "heimdall",
@ -1061,6 +1087,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
const completionExpiresAt = new Date(Date.now() + config.completionTtlSeconds * 1000).toISOString();
const completion = await store.createAuthCompletion({
...(handoff.kind === "browser_completion" && handoff.attemptId ? { code: handoff.attemptId } : {}),
appSlug: statePayload.app_slug,
provider: request.params.provider,
mode: statePayload.mode,
@ -1071,6 +1098,12 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
expiresAt: completionExpiresAt,
payloadJson: completionPayload as unknown as Record<string, unknown>,
});
if (handoff.kind === "browser_completion" && handoff.attemptId) {
await store.updateAuthAttempt(statePayload.app_slug, handoff.attemptId, {
status: "completed",
at: nowIso,
});
}
await store.createAuditEvent({
accountId: account.id,
@ -1097,6 +1130,9 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
mode: statePayload.mode,
returnTo: statePayload.return_to,
completionCode: completion.code,
...(handoff.kind === "browser_completion" && handoff.attemptId
? { attemptId: handoff.attemptId }
: {}),
})
);
}
@ -1113,6 +1149,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
} catch (error) {
const message = error instanceof Error ? error.message : "OAuth callback failed.";
const nowIso = new Date().toISOString();
await denyBrowserAttempt("oauth_callback_failed");
await store.createAuditEvent({
appSlug: statePayload.app_slug,
eventType: "oauth_callback_failed",
@ -1215,6 +1252,10 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
},
createdAt: nowIso,
});
await store.updateAuthAttempt(request.params.appSlug, request.body.completionCode, {
status: "consumed",
at: nowIso,
});
reply.code(201);
return completion.payloadJson;

View file

@ -17,6 +17,8 @@ export interface HeimdallConfig {
serviceName: string;
host: string;
port: number;
privateCommandHost?: string;
privateCommandPort?: number;
workspaceRoot: string;
dataRoot: string;
cultCachePath: string;
@ -36,6 +38,7 @@ export interface HeimdallConfig {
signingKeyId?: string;
tokenEncryptionKeyBase64?: string;
appSharedSecrets: Partial<Record<AppSlug, string>>;
appRuntimeIds?: Partial<Record<AppSlug, string[]>>;
appBackendCallbacks: Partial<Record<AppSlug, string[]>>;
bifrostPatronSupportEndpoint?: string;
bifrostPatronSupportSecret?: string;
@ -128,11 +131,21 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): HeimdallConfig
})
.filter(([, value]) => Array.isArray(value) && value.length > 0)
) as Partial<Record<AppSlug, string[]>>;
const appRuntimeIds = Object.fromEntries(
appSlugs
.map((appSlug) => {
const envKey = `GC_ACCESS_APP_${appSlug.toUpperCase()}_RUNTIME_IDS`;
return [appSlug, readList(env[envKey])];
})
.filter(([, value]) => Array.isArray(value) && value.length > 0)
) as Partial<Record<AppSlug, string[]>>;
const config: HeimdallConfig = {
serviceName: "heimdall",
host,
port,
privateCommandHost: env.GC_ACCESS_PRIVATE_COMMAND_HOST ?? "127.0.0.1",
privateCommandPort: readInt(env.GC_ACCESS_PRIVATE_COMMAND_PORT, 4101),
workspaceRoot,
dataRoot,
cultCachePath: env.GC_ACCESS_CULTCACHE_PATH ?? path.join(dataRoot, "cultcache", "heimdall.service.cc"),
@ -149,6 +162,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): HeimdallConfig
completionTtlSeconds: readInt(env.GC_ACCESS_COMPLETION_TTL_SECONDS, 300),
bootstrapSigningPrivateKeyOnMissing: readBoolean(env.GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP, false),
appSharedSecrets,
appRuntimeIds,
appBackendCallbacks,
storage: {
backend: storageBackend,

View file

@ -26,6 +26,7 @@ export interface OAuthConnectionBinding {
export interface OAuthBrowserCompletionHandoff {
kind: "browser_completion";
attemptId?: string;
}
export interface OAuthBackendCallbackHandoff {
@ -98,6 +99,23 @@ export interface RedeemAuthCompletionRequest {
completionCode: string;
}
export type HeimdallAuthAttemptStatus = "pending" | "completed" | "denied" | "consumed" | "expired";
export interface HeimdallAuthAttempt {
schema: "heimdall.auth_attempt.v1";
handle: string;
appSlug: AppSlug;
provider: Provider;
mode: OAuthMode;
returnTo: string;
status: HeimdallAuthAttemptStatus;
createdAt: string;
expiresAt: string;
completedAt?: string;
consumedAt?: string;
denialCode?: string;
}
export interface RefreshSessionRequest {
refreshToken: string;
entitlementPolicy?: OAuthEntitlementPolicy;

View file

@ -1,16 +1,22 @@
import { buildApp } from "./app.js";
import { loadConfig } from "./config.js";
import { publishIdunnRudpHealth } from "./idunn-rudp-health.js";
import { startHeimdallPrivateCommandPlane } from "./private-command-plane.js";
import type { CultNetOperationServer } from "cultnet-ts";
import { createHeimdallRuntimePulse, buildHeimdallHealthDetail, publishHeimdallVerseState } from "./verse-state.js";
const config = loadConfig();
const app = await buildApp({ config });
const versePulseIntervalMs = 60_000;
const healthPulseIntervalMs = 10_000;
let privateCommands: CultNetOperationServer | undefined;
try {
privateCommands = await startHeimdallPrivateCommandPlane(app, config);
app.addHook("onClose", async () => privateCommands?.close());
await app.listen({ host: config.host, port: config.port });
app.log.info(`Heimdall listening on ${config.host}:${config.port}`);
app.log.info(`Heimdall private CultNet commands listening at ${privateCommands.endpoint}`);
await publishVerseState().catch((error) => {
console.error("Heimdall verse publication failed on startup:", error);
});
@ -25,6 +31,7 @@ try {
void runHealthPulseLoop();
verseTimer.unref?.();
} catch (error) {
await privateCommands?.close().catch(() => undefined);
app.log.error(error);
process.exitCode = 1;
}

View file

@ -0,0 +1,292 @@
import { createHash, randomUUID } from "node:crypto";
import { decode, encode } from "@msgpack/msgpack";
import {
startCultNetOperationServer,
type CultNetOperationRequestMessage,
type CultNetOperationResponseMessage,
type CultNetOperationServer,
} from "cultnet-ts";
import { type FastifyInstance } from "fastify";
import { getHeimdallRuntimeContext } 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 { type HeimdallConfig } from "./config.js";
import { openPrivateEnvelope, sealPrivateEnvelope, type HeimdallPrivateEnvelope } from "./private-command-security.js";
export const HEIMDALL_PRIVATE_COMMAND_SERVICE = "heimdall.private.commands";
export const HEIMDALL_PRIVATE_ENVELOPE_SCHEMA = "heimdall.private_command_envelope.v1";
interface CachedResult {
fingerprint: string;
status: string;
envelope: HeimdallPrivateEnvelope;
}
export async function startHeimdallPrivateCommandPlane(
app: FastifyInstance,
config: HeimdallConfig,
): Promise<CultNetOperationServer> {
const seenNonces = new Map<string, number>();
const inFlight = new Map<string, Promise<CachedResult>>();
return await startCultNetOperationServer({
runtimeId: config.daemonId,
host: config.privateCommandHost ?? "127.0.0.1",
port: config.privateCommandPort ?? 4101,
handler: async (request) => {
const now = Date.now();
for (const [nonce, expiry] of seenNonces) if (expiry <= now) seenNonces.delete(nonce);
try {
if (request.serviceId === HEIMDALL_ACCESS_PLUGIN_ID) {
if (request.payloadSchema !== "gamecult.eve.plugin_abi.request.v1" || request.payloadEncoding !== "messagepack-base64") {
throw new Error("Heimdall access plugin requires the Eve plugin ABI request schema.");
}
const pluginRequest = decode(Buffer.from(request.payload, "base64")) as EvePluginAbiRequest;
if (pluginRequest.operation !== request.operation) throw new Error("Plugin ABI operation disagrees with CultNet routing.");
const pluginResponse = executeHeimdallAccessPlugin(pluginRequest);
return {
schemaVersion: "cultnet.operation_response.v0",
messageId: request.messageId,
serviceId: request.serviceId,
operation: request.operation,
status: pluginResponse.status,
payloadSchema: "gamecult.eve.plugin_abi.response.v1",
payloadEncoding: "messagepack-base64",
payload: Buffer.from(encode(pluginResponse)).toString("base64"),
diagnostics: [],
sourceRuntimeId: config.daemonId,
};
}
if (request.serviceId !== HEIMDALL_PRIVATE_COMMAND_SERVICE) throw new Error("Unknown Heimdall private command service.");
if (request.payloadSchema !== HEIMDALL_PRIVATE_ENVELOPE_SCHEMA || request.payloadEncoding !== "messagepack-base64") {
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.");
const appSlug = envelope.appSlug as AppSlug;
const secret = config.appSharedSecrets[appSlug];
if (!secret) throw new Error("Heimdall app binding has no private command secret.");
if (envelope.operation !== request.operation) throw new Error("Private envelope operation disagrees with CultNet routing.");
const expectedContentSchema = request.operation === "heimdall.auth.begin"
? "heimdall.auth_begin_command.v1"
: request.operation === "heimdall.auth.complete"
? "heimdall.auth_complete_command.v1"
: undefined;
if (!expectedContentSchema || envelope.contentSchema !== expectedContentSchema) {
throw new Error("Private command content schema does not match its operation.");
}
const allowedRuntimeIds = config.appRuntimeIds?.[appSlug] ?? [`yggdrasil-${appSlug}`];
if (!request.sourceRuntimeId || !allowedRuntimeIds.includes(request.sourceRuntimeId)) {
throw new Error("Private command caller is not the configured app runtime.");
}
const payload = openPrivateEnvelope(envelope, secret, now);
const fingerprint = createHash("sha256").update(request.payload).digest("hex");
const resultKey = `${appSlug}:${envelope.idempotencyKey}`;
const store = getHeimdallRuntimeContext(app).store;
const persisted = await store.findPrivateCommandReceipt(appSlug, envelope.idempotencyKey);
if (persisted) {
if (persisted.requestFingerprint !== fingerprint) throw new Error("Idempotency key was reused with different command content.");
const cachedEnvelope = decode(Buffer.from(persisted.envelopeBase64, "base64")) as HeimdallPrivateEnvelope;
return response(request, persisted.status, cachedEnvelope, config.daemonId);
}
const pending = inFlight.get(resultKey);
if (pending) {
const cached = await pending;
if (cached.fingerprint !== fingerprint) throw new Error("Idempotency key was reused with different command content.");
return response(request, cached.status, cached.envelope, config.daemonId);
}
if (seenNonces.has(`${appSlug}:${envelope.nonce}`)) throw new Error("Private command nonce was already used.");
seenNonces.set(`${appSlug}:${envelope.nonce}`, Date.parse(envelope.expiresAt));
const execution = (async (): Promise<CachedResult> => {
const output = await executePrivateCommand(app, config, appSlug, request.operation, payload);
const sealed = sealPrivateEnvelope({
appSlug,
operation: request.operation,
contentSchema: output.payloadSchema,
idempotencyKey: envelope.idempotencyKey,
secret,
payload: output.payload,
});
const stored = await store.createPrivateCommandReceipt({
appSlug,
idempotencyKey: envelope.idempotencyKey,
requestFingerprint: fingerprint,
status: output.status,
contentSchema: output.payloadSchema,
envelopeBase64: Buffer.from(encode(sealed)).toString("base64"),
createdAt: sealed.issuedAt,
expiresAt: sealed.expiresAt,
});
return {
fingerprint: stored.requestFingerprint,
status: stored.status,
envelope: decode(Buffer.from(stored.envelopeBase64, "base64")) as HeimdallPrivateEnvelope,
};
})();
inFlight.set(resultKey, execution);
let cachedResult: CachedResult;
try {
cachedResult = await execution;
} finally {
if (inFlight.get(resultKey) === execution) inFlight.delete(resultKey);
}
return response(request, cachedResult.status, cachedResult.envelope, config.daemonId);
} catch (error) {
return {
schemaVersion: "cultnet.operation_response.v0",
messageId: request.messageId,
serviceId: request.serviceId,
operation: request.operation,
status: "denied",
payloadSchema: "gamecult.cultnet.operation_failure.v1",
payloadEncoding: "messagepack-base64",
payload: Buffer.from(encode({ code: "private-command-denied", message: "Heimdall denied the private command." })).toString("base64"),
diagnostics: [error instanceof Error ? error.message : "Private command failed."],
sourceRuntimeId: config.daemonId,
};
}
},
});
}
async function executePrivateCommand(
app: FastifyInstance,
config: HeimdallConfig,
appSlug: AppSlug,
operation: string,
payload: Record<string, unknown>,
): Promise<{ status: string; payloadSchema: string; payload: Record<string, unknown> }> {
if (operation === "heimdall.auth.begin") return await beginAuth(app, config, appSlug, payload);
if (operation === "heimdall.auth.complete") return await completeAuth(app, appSlug, payload);
throw new Error(`Unsupported Heimdall private operation '${operation}'.`);
}
async function beginAuth(
app: FastifyInstance,
config: HeimdallConfig,
appSlug: AppSlug,
payload: Record<string, unknown>,
): Promise<{ status: string; payloadSchema: string; payload: Record<string, unknown> }> {
const provider = String(payload.provider ?? "discord") as Provider;
const mode = String(payload.mode ?? "sign_in") as OAuthMode;
const returnTo = String(payload.returnTo ?? "");
if (!providers.includes(provider) || !oauthModes.includes(mode) || !returnTo) throw new Error("Auth begin payload is incomplete.");
const entitlementPolicy = parseEntitlementPolicy(payload.entitlementPolicy);
if (appSlug === "ghostlight" && (!entitlementPolicy || entitlementPolicy.kind !== "discord_role_access")) {
throw new Error("Ghostlight authentication requires its caller-owned Discord role policy.");
}
const now = new Date();
const attempt = await getHeimdallRuntimeContext(app).store.createAuthAttempt({
handle: randomUUID(),
appSlug,
provider,
mode,
returnTo,
createdAt: now.toISOString(),
expiresAt: new Date(now.getTime() + config.stateTtlSeconds * 1000).toISOString(),
});
const start = await app.inject({
method: "POST",
url: `/v1/oauth/${provider}/start`,
headers: { "x-heimdall-app-secret": config.appSharedSecrets[appSlug] ?? "" },
payload: {
appSlug,
mode,
returnTo,
handoff: { kind: "browser_completion", attemptId: attempt.handle },
...(entitlementPolicy ? { entitlementPolicy } : {}),
},
});
const startPayload = start.json<Record<string, unknown>>();
if (start.statusCode !== 201) {
await getHeimdallRuntimeContext(app).store.updateAuthAttempt(appSlug, attempt.handle, {
status: "denied",
at: new Date().toISOString(),
denialCode: String(startPayload.error ?? "oauth_start_denied"),
});
throw new Error(String(startPayload.detail ?? startPayload.error ?? "OAuth start was denied."));
}
const authorizationUrl = String(startPayload.authorizationUrl ?? "");
const authorizationOrigin = new URL(authorizationUrl).origin;
return {
status: "accepted",
payloadSchema: "heimdall.auth_begin_receipt.v1",
payload: {
schema: "heimdall.auth_begin_receipt.v1",
status: "pending",
handle: attempt.handle,
expiresAt: attempt.expiresAt,
navigation: {
url: authorizationUrl,
allowedOrigins: [authorizationOrigin, new URL(config.publicBaseUrl).origin],
},
},
};
}
async function completeAuth(
app: FastifyInstance,
appSlug: AppSlug,
payload: Record<string, unknown>,
): Promise<{ status: string; payloadSchema: string; payload: Record<string, unknown> }> {
const handle = String(payload.handle ?? "");
if (!handle) throw new Error("Auth completion requires an opaque attempt handle.");
const store = getHeimdallRuntimeContext(app).store;
const attempt = await store.findAuthAttempt(appSlug, handle);
if (!attempt) throw new Error("Auth attempt is unknown for this app.");
const now = new Date().toISOString();
if (attempt.expiresAt <= now && attempt.status !== "completed") {
await store.updateAuthAttempt(appSlug, handle, { status: "expired", at: now });
return authCompletion("denied", { error: "expired_attempt" });
}
if (attempt.status === "pending") return authCompletion("pending", { handle });
if (attempt.status !== "completed") return authCompletion("denied", { error: attempt.denialCode ?? `attempt_${attempt.status}` });
const redemption = await app.inject({
method: "POST",
url: `/v1/apps/${appSlug}/auth-completions/redeem`,
payload: { completionCode: handle },
});
if (redemption.statusCode !== 201) return authCompletion("denied", { error: "invalid_or_expired_completion" });
return authCompletion("authenticated", redemption.json<Record<string, unknown>>());
}
function authCompletion(status: string, values: Record<string, unknown>) {
return {
status: status === "authenticated" ? "accepted" : status,
payloadSchema: "heimdall.auth_completion_receipt.v1",
payload: { ...values, schema: "heimdall.auth_completion_receipt.v1", status },
};
}
function parseEntitlementPolicy(value: unknown): OAuthEntitlementPolicy | undefined {
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
const record = value as Record<string, unknown>;
if (record.kind === "discord_role_access" && typeof record.guildId === "string" && Array.isArray(record.allowedRoleIds)) {
const allowedRoleIds = record.allowedRoleIds.filter((item): item is string => typeof item === "string" && Boolean(item));
return allowedRoleIds.length ? { kind: "discord_role_access", guildId: record.guildId, allowedRoleIds } : undefined;
}
if (record.kind === "patreon_membership_access" && typeof record.requiredTierTitle === "string") {
return { kind: "patreon_membership_access", requiredTierTitle: record.requiredTierTitle };
}
return undefined;
}
function response(
request: CultNetOperationRequestMessage,
status: string,
envelope: HeimdallPrivateEnvelope,
runtimeId: string,
): CultNetOperationResponseMessage {
return {
schemaVersion: "cultnet.operation_response.v0",
messageId: request.messageId,
serviceId: request.serviceId,
operation: request.operation,
status,
payloadSchema: HEIMDALL_PRIVATE_ENVELOPE_SCHEMA,
payloadEncoding: "messagepack-base64",
payload: Buffer.from(encode(envelope)).toString("base64"),
diagnostics: [],
sourceRuntimeId: runtimeId,
};
}

View file

@ -0,0 +1,129 @@
import {
createCipheriv,
createDecipheriv,
createHash,
createHmac,
randomBytes,
timingSafeEqual,
} from "node:crypto";
import { decode, encode } from "@msgpack/msgpack";
export interface HeimdallPrivateEnvelope {
schema: "heimdall.private_command_envelope.v1";
appSlug: string;
operation: string;
contentSchema: string;
issuedAt: string;
expiresAt: string;
nonce: string;
idempotencyKey: string;
iv: string;
ciphertext: string;
authTag: string;
signature: string;
}
function keyFor(secret: string): Buffer {
return createHash("sha256").update("heimdall.private-command.v1\0").update(secret).digest();
}
function authenticatedFields(envelope: Omit<HeimdallPrivateEnvelope, "signature">): string {
return [
envelope.schema,
envelope.appSlug,
envelope.operation,
envelope.contentSchema,
envelope.issuedAt,
envelope.expiresAt,
envelope.nonce,
envelope.idempotencyKey,
envelope.iv,
envelope.ciphertext,
envelope.authTag,
].join("\n");
}
function aad(envelope: Pick<HeimdallPrivateEnvelope, "schema" | "appSlug" | "operation" | "contentSchema" | "issuedAt" | "expiresAt" | "nonce" | "idempotencyKey">): Buffer {
return Buffer.from([
envelope.schema,
envelope.appSlug,
envelope.operation,
envelope.contentSchema,
envelope.issuedAt,
envelope.expiresAt,
envelope.nonce,
envelope.idempotencyKey,
].join("\n"), "utf8");
}
export function sealPrivateEnvelope(options: {
appSlug: string;
operation: string;
contentSchema: string;
idempotencyKey: string;
secret: string;
payload: Record<string, unknown>;
issuedAt?: string;
expiresAt?: string;
nonce?: string;
}): HeimdallPrivateEnvelope {
const issuedAt = options.issuedAt ?? new Date().toISOString();
const expiresAt = options.expiresAt ?? new Date(Date.parse(issuedAt) + 30_000).toISOString();
const nonce = options.nonce ?? randomBytes(16).toString("base64url");
const iv = randomBytes(12);
const partial = {
schema: "heimdall.private_command_envelope.v1" as const,
appSlug: options.appSlug,
operation: options.operation,
contentSchema: options.contentSchema,
issuedAt,
expiresAt,
nonce,
idempotencyKey: options.idempotencyKey,
iv: iv.toString("base64url"),
ciphertext: "",
authTag: "",
};
const cipher = createCipheriv("aes-256-gcm", keyFor(options.secret), iv);
cipher.setAAD(aad(partial));
const ciphertext = Buffer.concat([
cipher.update(encode(options.payload)),
cipher.final(),
]);
partial.ciphertext = ciphertext.toString("base64url");
partial.authTag = cipher.getAuthTag().toString("base64url");
const signature = createHmac("sha256", options.secret).update(authenticatedFields(partial)).digest("base64url");
return { ...partial, signature };
}
export function openPrivateEnvelope(
envelope: HeimdallPrivateEnvelope,
secret: string,
now = Date.now(),
): Record<string, unknown> {
if (envelope.schema !== "heimdall.private_command_envelope.v1") throw new Error("Unsupported private command envelope.");
const issuedAt = Date.parse(envelope.issuedAt);
const expiresAt = Date.parse(envelope.expiresAt);
if (!Number.isFinite(issuedAt) || !Number.isFinite(expiresAt) || expiresAt <= issuedAt) {
throw new Error("Private command has invalid time bounds.");
}
if (issuedAt > now + 30_000 || expiresAt <= now || expiresAt - issuedAt > 120_000) {
throw new Error("Private command is expired or outside the accepted clock window.");
}
const { signature, ...unsigned } = envelope;
const expected = createHmac("sha256", secret).update(authenticatedFields(unsigned)).digest();
const provided = Buffer.from(signature, "base64url");
if (expected.length !== provided.length || !timingSafeEqual(expected, provided)) {
throw new Error("Private command signature is invalid.");
}
const decipher = createDecipheriv("aes-256-gcm", keyFor(secret), Buffer.from(envelope.iv, "base64url"));
decipher.setAAD(aad(envelope));
decipher.setAuthTag(Buffer.from(envelope.authTag, "base64url"));
const plaintext = Buffer.concat([
decipher.update(Buffer.from(envelope.ciphertext, "base64url")),
decipher.final(),
]);
const payload = decode(plaintext) as unknown;
if (!payload || typeof payload !== "object" || Array.isArray(payload)) throw new Error("Private command payload is not an object.");
return payload as Record<string, unknown>;
}

View file

@ -2,17 +2,21 @@ import { randomUUID } from "node:crypto";
import { type AppSlug, type LinkedIdentityInput, type Provider } from "../contracts.js";
import {
type CreateAccountInput,
type CreateAuthAttemptInput,
type CreateAuthCompletionInput,
type CreateAuditEventInput,
type CreateCapabilityGrantInput,
type CreateEntitlementSnapshotInput,
type CreateSessionInput,
type CreatePrivateCommandReceiptInput,
type HeimdallStore,
type StoredAccount,
type StoredAuthAttempt,
type StoredAuthCompletion,
type StoredCapabilityGrant,
type StoredLinkedIdentity,
type StoredSession,
type StoredPrivateCommandReceipt,
type UpsertLinkedIdentityInput,
} from "./types.js";
@ -37,6 +41,8 @@ export class InMemoryStore implements HeimdallStore {
private readonly linkedIdentities = new Map<string, StoredLinkedIdentity>();
private readonly grants = new Map<string, StoredCapabilityGrant>();
private readonly sessions = new Map<string, StoredSession>();
private readonly authAttempts = new Map<string, StoredAuthAttempt>();
private readonly privateCommandReceipts = new Map<string, StoredPrivateCommandReceipt>();
private readonly authCompletions = new Map<string, StoredAuthCompletion>();
private readonly entitlementSnapshots = new Map<string, CreateEntitlementSnapshotInput>();
private readonly auditEvents = new Map<string, CreateAuditEventInput>();
@ -228,6 +234,64 @@ export class InMemoryStore implements HeimdallStore {
return clone(session);
}
async createAuthAttempt(input: CreateAuthAttemptInput): Promise<StoredAuthAttempt> {
const attempt: StoredAuthAttempt = {
handle: input.handle ?? randomUUID(),
appSlug: input.appSlug,
provider: input.provider,
mode: input.mode,
returnTo: input.returnTo,
status: "pending",
createdAt: input.createdAt,
expiresAt: input.expiresAt,
};
if (this.authAttempts.has(attempt.handle)) throw new Error("Auth attempt handle already exists.");
this.authAttempts.set(attempt.handle, clone(attempt));
return clone(attempt);
}
async findAuthAttempt(appSlug: AppSlug, handle: string): Promise<StoredAuthAttempt | null> {
const attempt = this.authAttempts.get(handle);
return attempt?.appSlug === appSlug ? clone(attempt) : null;
}
async updateAuthAttempt(
appSlug: AppSlug,
handle: string,
update: { status: import("../contracts.js").HeimdallAuthAttemptStatus; at: string; denialCode?: string },
): Promise<StoredAuthAttempt | null> {
const attempt = this.authAttempts.get(handle);
if (!attempt || attempt.appSlug !== appSlug) return null;
const allowed = attempt.status === update.status ||
(attempt.status === "pending" && ["completed", "denied", "expired"].includes(update.status)) ||
(attempt.status === "completed" && update.status === "consumed");
if (!allowed) return clone(attempt);
attempt.status = update.status;
if (update.status === "completed") attempt.completedAt = update.at;
if (update.status === "consumed") attempt.consumedAt = update.at;
if (update.denialCode !== undefined) attempt.denialCode = update.denialCode;
this.authAttempts.set(handle, clone(attempt));
return clone(attempt);
}
async createPrivateCommandReceipt(input: CreatePrivateCommandReceiptInput): Promise<StoredPrivateCommandReceipt> {
const key = `${input.appSlug}:${input.idempotencyKey}`;
const existing = this.privateCommandReceipts.get(key);
if (existing) {
if (existing.requestFingerprint !== input.requestFingerprint) {
throw new Error("Idempotency key was reused with different command content.");
}
return clone(existing);
}
this.privateCommandReceipts.set(key, clone(input));
return clone(input);
}
async findPrivateCommandReceipt(appSlug: AppSlug, idempotencyKey: string): Promise<StoredPrivateCommandReceipt | null> {
const receipt = this.privateCommandReceipts.get(`${appSlug}:${idempotencyKey}`);
return receipt ? clone(receipt) : null;
}
async createAuthCompletion(input: CreateAuthCompletionInput): Promise<StoredAuthCompletion> {
const completion: StoredAuthCompletion = {
code: input.code ?? randomUUID(),

View file

@ -1,20 +1,24 @@
import { randomUUID } from "node:crypto";
import { Pool, type PoolClient, type QueryResultRow } from "pg";
import { type AppSlug, type LinkedIdentityInput, type Provider } from "../contracts.js";
import { type AppSlug, type HeimdallAuthAttemptStatus, type LinkedIdentityInput, type Provider } from "../contracts.js";
import { CREATE_SCHEMA_SQL } from "./schema.js";
import {
type CreateAccountInput,
type CreateAuthAttemptInput,
type CreateAuthCompletionInput,
type CreateAuditEventInput,
type CreateCapabilityGrantInput,
type CreateEntitlementSnapshotInput,
type CreateSessionInput,
type CreatePrivateCommandReceiptInput,
type HeimdallStore,
type StoredAccount,
type StoredAuthAttempt,
type StoredAuthCompletion,
type StoredCapabilityGrant,
type StoredLinkedIdentity,
type StoredSession,
type StoredPrivateCommandReceipt,
type UpsertLinkedIdentityInput,
} from "./types.js";
@ -82,6 +86,31 @@ interface AuthCompletionRow extends QueryResultRow {
consumed_at: string | Date | null;
}
interface AuthAttemptRow extends QueryResultRow {
handle: string;
app_slug: AppSlug;
provider: Provider;
mode: "sign_in" | "link" | "connect";
return_to: string;
status: HeimdallAuthAttemptStatus;
created_at: string | Date;
expires_at: string | Date;
completed_at: string | Date | null;
consumed_at: string | Date | null;
denial_code: string | null;
}
interface PrivateCommandReceiptRow extends QueryResultRow {
app_slug: AppSlug;
idempotency_key: string;
request_fingerprint: string;
status: string;
content_schema: string;
envelope_base64: string;
created_at: string | Date;
expires_at: string | Date;
}
function expectRow<T>(row: T | undefined, label: string): T {
if (!row) {
throw new Error(`${label} query returned no rows.`);
@ -220,6 +249,36 @@ function mapAuthCompletionRow(row: AuthCompletionRow): StoredAuthCompletion {
return completion;
}
function mapPrivateCommandReceiptRow(row: PrivateCommandReceiptRow): StoredPrivateCommandReceipt {
return {
appSlug: row.app_slug,
idempotencyKey: row.idempotency_key,
requestFingerprint: row.request_fingerprint,
status: row.status,
contentSchema: row.content_schema,
envelopeBase64: row.envelope_base64,
createdAt: normalizeTimestamp(row.created_at),
expiresAt: normalizeTimestamp(row.expires_at),
};
}
function mapAuthAttemptRow(row: AuthAttemptRow): StoredAuthAttempt {
const attempt: StoredAuthAttempt = {
handle: row.handle,
appSlug: row.app_slug,
provider: row.provider,
mode: row.mode,
returnTo: row.return_to,
status: row.status,
createdAt: normalizeTimestamp(row.created_at),
expiresAt: normalizeTimestamp(row.expires_at),
};
if (row.completed_at) attempt.completedAt = normalizeTimestamp(row.completed_at);
if (row.consumed_at) attempt.consumedAt = normalizeTimestamp(row.consumed_at);
if (row.denial_code) attempt.denialCode = row.denial_code;
return attempt;
}
export class PostgresStore implements HeimdallStore {
constructor(private readonly pool: Pick<Pool, "query" | "end">) {}
@ -501,6 +560,88 @@ export class PostgresStore implements HeimdallStore {
return mapSessionRow(expectRow(result.rows[0], "createSession"));
}
async createAuthAttempt(input: CreateAuthAttemptInput): Promise<StoredAuthAttempt> {
const handle = input.handle ?? randomUUID();
const result = await this.pool.query<AuthAttemptRow>(
`INSERT INTO auth_attempts (
handle, app_slug, provider, mode, return_to, status, created_at, expires_at
) VALUES ($1, $2, $3, $4, $5, 'pending', $6, $7) RETURNING *`,
[handle, input.appSlug, input.provider, input.mode, input.returnTo, input.createdAt, input.expiresAt],
);
return mapAuthAttemptRow(expectRow(result.rows[0], "createAuthAttempt"));
}
async findAuthAttempt(appSlug: AppSlug, handle: string): Promise<StoredAuthAttempt | null> {
const result = await this.pool.query<AuthAttemptRow>(
"SELECT * FROM auth_attempts WHERE app_slug = $1 AND handle = $2",
[appSlug, handle],
);
return result.rowCount ? mapAuthAttemptRow(expectRow(result.rows[0], "findAuthAttempt")) : null;
}
async updateAuthAttempt(
appSlug: AppSlug,
handle: string,
update: { status: HeimdallAuthAttemptStatus; at: string; denialCode?: string },
): Promise<StoredAuthAttempt | null> {
const result = await this.pool.query<AuthAttemptRow>(
`UPDATE auth_attempts SET
status = $3,
completed_at = CASE WHEN $3 = 'completed' THEN $4 ELSE completed_at END,
consumed_at = CASE WHEN $3 = 'consumed' THEN $4 ELSE consumed_at END,
denial_code = COALESCE($5, denial_code)
WHERE app_slug = $1 AND handle = $2
AND (
status = $3 OR
(status = 'pending' AND $3 IN ('completed', 'denied', 'expired')) OR
(status = 'completed' AND $3 = 'consumed')
)
RETURNING *`,
[appSlug, handle, update.status, update.at, nullable(update.denialCode)],
);
if (result.rowCount) return mapAuthAttemptRow(expectRow(result.rows[0], "updateAuthAttempt"));
return await this.findAuthAttempt(appSlug, handle);
}
async createPrivateCommandReceipt(input: CreatePrivateCommandReceiptInput): Promise<StoredPrivateCommandReceipt> {
const result = await this.pool.query<PrivateCommandReceiptRow>(
`INSERT INTO private_command_receipts (
app_slug, idempotency_key, request_fingerprint, status,
content_schema, envelope_base64, created_at, expires_at
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
ON CONFLICT (app_slug, idempotency_key) DO NOTHING
RETURNING *`,
[
input.appSlug,
input.idempotencyKey,
input.requestFingerprint,
input.status,
input.contentSchema,
input.envelopeBase64,
input.createdAt,
input.expiresAt,
],
);
const existing = result.rowCount
? mapPrivateCommandReceiptRow(expectRow(result.rows[0], "createPrivateCommandReceipt"))
: await this.findPrivateCommandReceipt(input.appSlug, input.idempotencyKey);
if (!existing) throw new Error("Private command receipt conflict returned no record.");
if (existing.requestFingerprint !== input.requestFingerprint) {
throw new Error("Idempotency key was reused with different command content.");
}
return existing;
}
async findPrivateCommandReceipt(appSlug: AppSlug, idempotencyKey: string): Promise<StoredPrivateCommandReceipt | null> {
const result = await this.pool.query<PrivateCommandReceiptRow>(
"SELECT * FROM private_command_receipts WHERE app_slug = $1 AND idempotency_key = $2",
[appSlug, idempotencyKey],
);
return result.rowCount
? mapPrivateCommandReceiptRow(expectRow(result.rows[0], "findPrivateCommandReceipt"))
: null;
}
async createAuthCompletion(input: CreateAuthCompletionInput): Promise<StoredAuthCompletion> {
const code = input.code ?? randomUUID();
const result = await this.pool.query<AuthCompletionRow>(

View file

@ -42,6 +42,38 @@ CREATE TABLE IF NOT EXISTS sessions (
CREATE INDEX IF NOT EXISTS sessions_account_id_idx
ON sessions(account_id);
CREATE TABLE IF NOT EXISTS auth_attempts (
handle TEXT PRIMARY KEY,
app_slug TEXT NOT NULL,
provider TEXT NOT NULL,
mode TEXT NOT NULL,
return_to TEXT NOT NULL,
status TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
expires_at TIMESTAMPTZ NOT NULL,
completed_at TIMESTAMPTZ,
consumed_at TIMESTAMPTZ,
denial_code TEXT
);
CREATE INDEX IF NOT EXISTS auth_attempts_lookup_idx
ON auth_attempts(app_slug, expires_at, status);
CREATE TABLE IF NOT EXISTS private_command_receipts (
app_slug TEXT NOT NULL,
idempotency_key TEXT NOT NULL,
request_fingerprint TEXT NOT NULL,
status TEXT NOT NULL,
content_schema TEXT NOT NULL,
envelope_base64 TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
expires_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (app_slug, idempotency_key)
);
CREATE INDEX IF NOT EXISTS private_command_receipts_expiry_idx
ON private_command_receipts(expires_at);
CREATE TABLE IF NOT EXISTS auth_completions (
code TEXT PRIMARY KEY,
app_slug TEXT NOT NULL,

View file

@ -1,4 +1,10 @@
import { type AppSlug, type LinkedIdentityInput, type OAuthMode, type Provider } from "../contracts.js";
import {
type AppSlug,
type HeimdallAuthAttemptStatus,
type LinkedIdentityInput,
type OAuthMode,
type Provider,
} from "../contracts.js";
export interface StoredAccount {
id: string;
@ -148,6 +154,43 @@ export interface CreateAuthCompletionInput {
payloadJson: Record<string, unknown>;
}
export interface StoredAuthAttempt {
handle: string;
appSlug: AppSlug;
provider: Provider;
mode: OAuthMode;
returnTo: string;
status: HeimdallAuthAttemptStatus;
createdAt: string;
expiresAt: string;
completedAt?: string;
consumedAt?: string;
denialCode?: string;
}
export interface CreateAuthAttemptInput {
handle?: string;
appSlug: AppSlug;
provider: Provider;
mode: OAuthMode;
returnTo: string;
createdAt: string;
expiresAt: string;
}
export interface StoredPrivateCommandReceipt {
appSlug: AppSlug;
idempotencyKey: string;
requestFingerprint: string;
status: string;
contentSchema: string;
envelopeBase64: string;
createdAt: string;
expiresAt: string;
}
export type CreatePrivateCommandReceiptInput = StoredPrivateCommandReceipt;
export interface HeimdallStore {
ensureSchema(): Promise<void>;
close(): Promise<void>;
@ -163,6 +206,15 @@ export interface HeimdallStore {
createCapabilityGrant(input: CreateCapabilityGrantInput): Promise<StoredCapabilityGrant>;
listActiveGrants(accountId: string, appSlug: AppSlug, at: string): Promise<StoredCapabilityGrant[]>;
createSession(input: CreateSessionInput): Promise<StoredSession>;
createAuthAttempt(input: CreateAuthAttemptInput): Promise<StoredAuthAttempt>;
findAuthAttempt(appSlug: AppSlug, handle: string): Promise<StoredAuthAttempt | null>;
updateAuthAttempt(
appSlug: AppSlug,
handle: string,
update: { status: HeimdallAuthAttemptStatus; at: string; denialCode?: string },
): Promise<StoredAuthAttempt | null>;
createPrivateCommandReceipt(input: CreatePrivateCommandReceiptInput): Promise<StoredPrivateCommandReceipt>;
findPrivateCommandReceipt(appSlug: AppSlug, idempotencyKey: string): Promise<StoredPrivateCommandReceipt | null>;
createAuthCompletion(input: CreateAuthCompletionInput): Promise<StoredAuthCompletion>;
consumeAuthCompletion(appSlug: AppSlug, code: string, at: string): Promise<StoredAuthCompletion | null>;
upsertEntitlementSnapshot(input: CreateEntitlementSnapshotInput): Promise<void>;

View file

@ -2,6 +2,7 @@ import { mkdir, rename, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { encode } from "@msgpack/msgpack";
import { appSlugs, providers } from "./contracts.js";
import { buildHeimdallAccessPluginAdvertisement } from "./access-plugin.js";
import type { HeimdallConfig } from "./config.js";
import { buildHeimdallProviderAdvertisement } from "./verse-witness.js";
@ -55,6 +56,14 @@ export async function publishHeimdallVerseState(config: HeimdallConfig, pulse: H
payload: buildCommandBoundary(config, pulse),
storedAt: pulse.updatedAt,
},
{
key: "gamecult.heimdall.access",
schemaId: "gamecult.eve.plugin_advertisement.v1",
schemaName: "gamecult.eve.plugin_advertisement",
schemaVersion: "gamecult.eve.plugin_advertisement.v1",
payload: buildHeimdallAccessPluginAdvertisement(),
storedAt: pulse.updatedAt,
},
{
key: "heimdall",
schemaId: "heimdall.transport_profile.v1",
@ -98,7 +107,7 @@ function buildRuntimeProviderAdvertisement(config: HeimdallConfig, pulse: Heimda
...advertisement.controlSurface,
controls: {
...advertisement.controlSurface.controls,
reason: "This runtime publication advertises provider shape and lifecycle boundaries. Auth mutation remains behind explicit Heimdall HTTP APIs.",
reason: "This runtime publication advertises provider, plugin, and lifecycle boundaries. Auth mutation remains behind Heimdall's authenticated private command plane or retained HTTP compatibility APIs.",
},
},
runtime: {
@ -108,6 +117,7 @@ function buildRuntimeProviderAdvertisement(config: HeimdallConfig, pulse: Heimda
cultCachePath: witnessPath,
idunnHealthContract: config.idunnHealthContract,
idunnRudpHealth: config.idunnRudpHealth ?? null,
privateCommandRoute: `rudp://${config.privateCommandHost ?? "127.0.0.1"}:${config.privateCommandPort ?? 4101}`,
},
};
}
@ -127,7 +137,24 @@ function buildCommandBoundary(config: HeimdallConfig, pulse: HeimdallRuntimePuls
publicationSource: config.idunnRudpHealth ? "daemon-published" : "daemon-published-cultcache",
stateOwner: "Heimdall auth runtime",
},
commands: [],
commands: [
{
operation: "heimdall.auth.begin",
requestSchema: "heimdall.private_command_envelope.v1",
responseSchema: "heimdall.auth_begin_receipt.v1",
},
{
operation: "heimdall.auth.complete",
requestSchema: "heimdall.private_command_envelope.v1",
responseSchema: "heimdall.auth_completion_receipt.v1",
},
],
privateRoute: {
endpoint: `rudp://${config.privateCommandHost ?? "127.0.0.1"}:${config.privateCommandPort ?? 4101}`,
exposure: "loopback-only",
authentication: "app-bound HMAC + AES-256-GCM envelope",
secretBearing: false,
},
forbiddenWriters: [
"Odin and Idunn may observe Heimdall boundary state but do not mutate auth/control-plane truth.",
"HTTP /healthz, JWKS, discovery, systemd, and nginx routing are compatibility witnesses, not daemon truth.",

View file

@ -8,6 +8,7 @@ export const heimdallWitnessSchemaIds = [
"heimdall.capability_grant.v0",
"heimdall.session.v0",
"heimdall.entitlement_snapshot.v0",
"heimdall.auth_attempt.v1",
"heimdall.auth_completion.v0",
"heimdall.audit_event.v0",
"heimdall.app_profile.v0",
@ -66,6 +67,14 @@ export const heimdallWitnessDocuments: readonly HeimdallWitnessDocumentDescripto
ownedTruth: "Cached provider entitlement evaluation result.",
forbiddenFields: ["rawProviderResponse", "providerAccessToken", "providerRefreshToken"],
},
{
schemaId: "heimdall.auth_attempt.v1",
documentType: "heimdall.auth_attempt.v1",
cultCachePath: "cultcache/heimdall/auth-attempts/{attemptHandleHash}.cc",
redaction: "Attempt handles, return URLs, nonces, signatures, and policy contents stay private; export only app, provider, status, and expiry.",
ownedTruth: "Persistent Heimdall-owned OAuth attempt lifecycle.",
forbiddenFields: ["handle", "returnTo", "nonce", "signature", "entitlementPolicy"],
},
{
schemaId: "heimdall.auth_completion.v0",
documentType: "heimdall.auth_completion.v0",
@ -160,6 +169,7 @@ export interface EveProviderAdvertisementDocument {
providers: HeimdallAdvertisedProvider[];
appProfiles: HeimdallAdvertisedAppProfile[];
documents: HeimdallWitnessDocumentDescriptor[];
plugins: Array<Record<string, unknown>>;
}
export function buildHeimdallProviderAdvertisement(options: { updatedAt: string }): EveProviderAdvertisementDocument {
@ -172,7 +182,7 @@ export function buildHeimdallProviderAdvertisement(options: { updatedAt: string
locatedService: "asgard.yggdrasil.heimdall",
cultMeshAddress: "asgard.yggdrasil.heimdall/eve/tui",
title: "Heimdall",
description: "Shared GameCult auth/control-plane authority with redacted CultCache witness projections.",
description: "Shared GameCult auth/control-plane authority with a reusable Eve access plugin and redacted CultCache witness projections.",
version: "read-only-witness-v0",
status: "read_only_witness_planned",
updatedAt: options.updatedAt,
@ -188,6 +198,8 @@ export function buildHeimdallProviderAdvertisement(options: { updatedAt: string
"session-claims",
"managed-credential-custody",
"redacted-cultcache-witness",
"eve-access-plugin",
"private-cultnet-auth-commands",
],
usesCultMesh: true,
transport: "CultMesh provider advertisement; first cut is a read-only fixture/export.",
@ -244,5 +256,17 @@ export function buildHeimdallProviderAdvertisement(options: { updatedAt: string
};
}),
documents: [...heimdallWitnessDocuments],
plugins: [
{
schema: "gamecult.eve.plugin_advertisement.v1",
pluginId: "gamecult.heimdall.access",
ownerService: "asgard.heimdall",
version: "0.1.0",
manifestAddress: "cultmesh://gamecult/heimdall/plugins/access/manifest",
capabilities: ["auth.gate", "auth.begin", "auth.complete", "auth.logout"],
componentKinds: ["heimdall.access_gate", "heimdall.identity", "heimdall.access_status"],
commands: ["heimdall.auth.begin", "heimdall.auth.complete", "app.auth.logout"],
},
],
};
}