Publish Heimdall daemon boundary state for Idunn

This commit is contained in:
Meta Vens 2026-06-16 18:01:07 +01:00
commit 758892db87
17 changed files with 638 additions and 40 deletions

View file

@ -525,6 +525,10 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
service: config.serviceName,
issuer: config.issuer,
storageBackend: config.storage.backend,
cultCachePath: config.cultCachePath,
idunnDaemon: config.daemonId,
idunnHealthContract: config.idunnHealthContract,
idunnRudpHealth: config.idunnRudpHealth ?? null,
signingKeySource: keys.source,
tokenCustodySource: tokenCustody.source,
now: new Date().toISOString(),

View file

@ -1,3 +1,5 @@
import path from "node:path";
import { fileURLToPath } from "node:url";
import { appSlugs, providers, type AppSlug, type Provider } from "./contracts.js";
export interface ProviderClientConfig {
@ -15,8 +17,14 @@ export interface HeimdallConfig {
serviceName: string;
host: string;
port: number;
workspaceRoot: string;
dataRoot: string;
cultCachePath: string;
publicBaseUrl: string;
issuer: string;
daemonId: string;
idunnRudpHealth: string | undefined;
idunnHealthContract: string;
sessionTtlSeconds: number;
refreshTtlSeconds: number;
stateTtlSeconds: number;
@ -85,11 +93,19 @@ function readList(envValue: string | undefined): string[] {
return envValue?.split(",").map((entry) => entry.trim()).filter(Boolean) ?? [];
}
function readOptionalString(envValue: string | undefined): string | undefined {
const value = envValue?.trim();
return value ? value : undefined;
}
export function loadConfig(env: NodeJS.ProcessEnv = process.env): HeimdallConfig {
const sourceRoot = fileURLToPath(new URL("../", import.meta.url));
const workspaceRoot = path.resolve(sourceRoot, "..");
const host = env.HOST ?? "127.0.0.1";
const port = readInt(env.PORT, 4100);
const publicBaseUrl = trimTrailingSlash(env.GC_ACCESS_BASE_URL ?? `http://${host}:${port}`);
const issuer = trimTrailingSlash(env.GC_ACCESS_ISSUER ?? publicBaseUrl);
const dataRoot = env.GC_ACCESS_DATA_ROOT ?? path.join(workspaceRoot, ".heimdall-data");
const storageBackend =
env.GC_ACCESS_STORAGE_BACKEND === "postgres" || env.GC_ACCESS_DATABASE_URL ? "postgres" : "memory";
const providersConfig = Object.fromEntries(
@ -116,8 +132,14 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): HeimdallConfig
serviceName: "heimdall",
host,
port,
workspaceRoot,
dataRoot,
cultCachePath: env.GC_ACCESS_CULTCACHE_PATH ?? path.join(dataRoot, "cultcache", "heimdall.service.cc"),
publicBaseUrl,
issuer,
daemonId: env.GC_ACCESS_IDUNN_DAEMON ?? "yggdrasil-heimdall",
idunnRudpHealth: readOptionalString(env.GC_ACCESS_IDUNN_RUDP_HEALTH),
idunnHealthContract: env.GC_ACCESS_IDUNN_HEALTH_CONTRACT ?? "heimdall.cultnet-rudp-provider-health",
sessionTtlSeconds: readInt(env.GC_ACCESS_SESSION_TTL_SECONDS, 3600),
refreshTtlSeconds: readInt(env.GC_ACCESS_REFRESH_TTL_SECONDS, 60 * 60 * 24 * 30),
stateTtlSeconds: readInt(env.GC_ACCESS_STATE_TTL_SECONDS, 600),

190
src/idunn-rudp-health.ts Normal file
View file

@ -0,0 +1,190 @@
import dgram from "node:dgram";
import { encode } from "@msgpack/msgpack";
import {
encodeCultNetMessageForWire,
encodeRudpPacket,
type CultNetDocumentPutRawMessage,
type CultNetRudpPacket,
} from "cultnet-ts";
import type { HeimdallConfig } from "./config.js";
const CULTNET_RUDP_PROTOCOL_ID = "cultnet.transport.rudp.v0";
const IDUNN_HEALTH_RUDP_CONNECTION_ID = 0x1d0d0001;
const RUDP_HEALTH_CONNECT_ATTEMPTS = 3;
const RUDP_PULSE_POST_SEND_GRACE_MS = 1000;
const RUDP_CONNECT_TO_DATA_GRACE_MS = 300;
type Endpoint = {
host: string;
port: number;
};
type IdunnHealthInput = {
daemonId: string;
state: string;
detail: string;
observedAt: string;
};
export async function publishIdunnRudpHealth(config: HeimdallConfig, health: IdunnHealthInput): Promise<void> {
if (!config.idunnRudpHealth) {
return;
}
const endpoint = parseEndpoint(config.idunnRudpHealth);
let lastError: unknown;
for (let attempt = 1; attempt <= RUDP_HEALTH_CONNECT_ATTEMPTS; attempt += 1) {
try {
await publishIdunnRudpHealthOnce(endpoint, config, health);
return;
} catch (error) {
lastError = error;
if ((error as Error & { code?: string }).code !== "ETIMEDOUT") {
throw error;
}
}
}
throw lastError;
}
async function publishIdunnRudpHealthOnce(
endpoint: Endpoint,
config: HeimdallConfig,
health: IdunnHealthInput,
): Promise<void> {
const socket = dgram.createSocket(endpointFamily(endpoint.host));
try {
await bindSocket(socket, endpoint);
const connect = buildConnectPacket();
await sendPacket(socket, endpoint, connect);
await sleep(RUDP_CONNECT_TO_DATA_GRACE_MS);
const payload = buildDocumentPutPayload(config, health);
await sendPacket(socket, endpoint, buildSchemaDataPacket(payload));
await sleep(RUDP_PULSE_POST_SEND_GRACE_MS);
} finally {
socket.close();
}
}
function buildDocumentPutPayload(config: HeimdallConfig, health: IdunnHealthInput): Uint8Array {
const recordPayload = encode([
health.daemonId,
health.state,
health.detail,
health.observedAt,
config.idunnHealthContract,
"daemon-published",
CULTNET_RUDP_PROTOCOL_ID,
]);
const message: CultNetDocumentPutRawMessage = {
schemaVersion: "cultnet.document_put_raw.v0",
messageId: `heimdall-health:${health.daemonId}:${health.observedAt.replace(/[:.]/g, "-")}`,
document: {
schemaId: "idunn.daemon_health",
recordKey: health.daemonId,
storedAt: health.observedAt,
payloadEncoding: "messagepack",
payload: recordPayload,
sourceRuntimeId: "heimdall-service",
sourceRole: "daemon-health-publisher",
tags: [CULTNET_RUDP_PROTOCOL_ID],
},
};
return encode(encodeCultNetMessageForWire(message, "cultnet.schema.v0"));
}
function buildConnectPacket(): CultNetRudpPacket {
return {
packetType: "connect",
connectionId: IDUNN_HEALTH_RUDP_CONNECTION_ID,
sequence: 1,
ack: 0,
ackMask: 0,
channelId: "control",
reliable: true,
ordered: true,
sequenced: false,
payload: new Uint8Array(),
};
}
function buildSchemaDataPacket(payload: Uint8Array): CultNetRudpPacket {
return {
packetType: "data",
connectionId: IDUNN_HEALTH_RUDP_CONNECTION_ID,
sequence: 2,
ack: 0,
ackMask: 0,
channelId: "schema",
reliable: true,
ordered: true,
sequenced: false,
payload,
};
}
async function bindSocket(socket: dgram.Socket, endpoint: Endpoint): Promise<void> {
await new Promise<void>((resolve, reject) => {
socket.once("error", reject);
socket.bind(0, localBindHost(endpoint.host), () => {
socket.off("error", reject);
resolve();
});
});
}
function localBindHost(remoteHost: string): string {
if (remoteHost === "localhost" || remoteHost.startsWith("127.")) {
return "127.0.0.1";
}
if (remoteHost === "::1") {
return "::1";
}
return remoteHost.includes(":") ? "::" : "0.0.0.0";
}
async function sendPacket(socket: dgram.Socket, endpoint: Endpoint, input: CultNetRudpPacket): Promise<void> {
const wire = encodeRudpPacket(input);
await new Promise<void>((resolve, reject) => {
socket.send(wire, endpoint.port, endpoint.host, (error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
});
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function endpointFamily(host: string): "udp4" | "udp6" {
return host.includes(":") ? "udp6" : "udp4";
}
function parseEndpoint(value: string): Endpoint {
const text = value.trim();
const ipv6 = text.match(/^\[([^\]]+)\]:(\d+)$/);
if (ipv6) {
return { host: ipv6[1]!, port: parsePort(ipv6[2]!) };
}
const index = text.lastIndexOf(":");
if (index <= 0) {
throw new Error(`Idunn RUDP endpoint must be host:port, got "${value}".`);
}
return {
host: text.slice(0, index),
port: parsePort(text.slice(index + 1)),
};
}
function parsePort(value: string): number {
const port = Number(value);
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
throw new Error(`Idunn RUDP endpoint port is invalid: ${value}`);
}
return port;
}

View file

@ -1,13 +1,36 @@
import { buildApp } from "./app.js";
import { loadConfig } from "./config.js";
import { publishIdunnRudpHealth } from "./idunn-rudp-health.js";
import { createHeimdallRuntimePulse, buildHeimdallHealthDetail, publishHeimdallVerseState } from "./verse-state.js";
const config = loadConfig();
const app = await buildApp({ config });
const versePulseIntervalMs = 60_000;
try {
await app.listen({ host: config.host, port: config.port });
app.log.info(`Heimdall listening on ${config.host}:${config.port}`);
await publishVerseState().catch((error) => {
console.error("Heimdall verse publication failed on startup:", error);
});
const timer = setInterval(() => {
void publishVerseState().catch((error) => {
console.error("Heimdall verse publication failed on interval:", error);
});
}, versePulseIntervalMs);
timer.unref?.();
} catch (error) {
app.log.error(error);
process.exitCode = 1;
}
async function publishVerseState(): Promise<void> {
const pulse = createHeimdallRuntimePulse(config);
await publishHeimdallVerseState(config, pulse);
await publishIdunnRudpHealth(config, {
daemonId: config.daemonId,
state: "active",
detail: buildHeimdallHealthDetail(config, pulse),
observedAt: pulse.updatedAt,
});
}

203
src/verse-state.ts Normal file
View file

@ -0,0 +1,203 @@
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 type { HeimdallConfig } from "./config.js";
import { buildHeimdallProviderAdvertisement } from "./verse-witness.js";
const STORE_FORMAT_VERSION = "cultcache.store.v1";
type CultCacheRecord = {
key: string;
schemaId: string;
schemaName: string;
schemaVersion: string;
payload: unknown;
storedAt: string;
};
export type HeimdallRuntimePulse = {
updatedAt: string;
configuredProviders: string[];
storageBackend: string;
appProfileCount: number;
cultCachePath: string;
};
export function createHeimdallRuntimePulse(config: HeimdallConfig, updatedAt = new Date().toISOString()): HeimdallRuntimePulse {
return {
updatedAt,
configuredProviders: providers.filter((provider) => {
const entry = config.providers[provider];
return Boolean(entry?.clientId && entry.clientSecret);
}),
storageBackend: config.storage.backend,
appProfileCount: appSlugs.length,
cultCachePath: config.cultCachePath,
};
}
export async function publishHeimdallVerseState(config: HeimdallConfig, pulse: HeimdallRuntimePulse): Promise<void> {
const records: CultCacheRecord[] = [
{
key: "heimdall",
schemaId: "gamecult.eve.provider_advertisement.v1",
schemaName: "gamecult.eve.provider_advertisement",
schemaVersion: "gamecult.eve.provider_advertisement.v1",
payload: buildRuntimeProviderAdvertisement(config, pulse),
storedAt: pulse.updatedAt,
},
{
key: "heimdall",
schemaId: "heimdall.command_boundary.v1",
schemaName: "heimdall.command_boundary",
schemaVersion: "heimdall.command_boundary.v1",
payload: buildCommandBoundary(config, pulse),
storedAt: pulse.updatedAt,
},
{
key: "heimdall",
schemaId: "heimdall.transport_profile.v1",
schemaName: "heimdall.transport_profile",
schemaVersion: "heimdall.transport_profile.v1",
payload: buildTransportProfile(config, pulse),
storedAt: pulse.updatedAt,
},
{
key: config.daemonId,
schemaId: "idunn.daemon_health",
schemaName: "idunn.daemon_health",
schemaVersion: "idunn.daemon_health.v1",
payload: buildDaemonHealthRecord(config, pulse),
storedAt: pulse.updatedAt,
},
];
await writeCultCacheSnapshot(config.cultCachePath, records);
}
export function buildHeimdallHealthDetail(config: HeimdallConfig, pulse: HeimdallRuntimePulse): string {
const healthTransport = config.idunnRudpHealth ? "CultNet/RUDP" : "CultCache witness only";
return `Heimdall auth runtime active; storage=${pulse.storageBackend}; providers=${pulse.configuredProviders.length}/${providers.length}; apps=${pulse.appProfileCount}; healthTransport=${healthTransport}`;
}
function buildRuntimeProviderAdvertisement(config: HeimdallConfig, pulse: HeimdallRuntimePulse) {
const advertisement = buildHeimdallProviderAdvertisement({ updatedAt: pulse.updatedAt });
const witnessPath = path.relative(config.workspaceRoot, config.cultCachePath).replace(/\\/g, "/");
return {
...advertisement,
status: "daemon_live" as const,
version: "daemon-live-v1",
provider: {
...advertisement.provider,
transport: config.idunnRudpHealth
? "CultCache witness store + daemon-published Idunn health over CultNet/RUDP."
: "CultCache witness store; Idunn health still falls back to local witness publication.",
},
controlSurface: {
...advertisement.controlSurface,
controls: {
...advertisement.controlSurface.controls,
reason: "This runtime publication advertises provider shape and lifecycle boundaries. Auth mutation remains behind explicit Heimdall HTTP APIs.",
},
},
runtime: {
storageBackend: pulse.storageBackend,
configuredProviders: pulse.configuredProviders,
appProfileCount: pulse.appProfileCount,
cultCachePath: witnessPath,
idunnHealthContract: config.idunnHealthContract,
idunnRudpHealth: config.idunnRudpHealth ?? null,
},
};
}
function buildCommandBoundary(config: HeimdallConfig, pulse: HeimdallRuntimePulse) {
return {
schema: "heimdall.command_boundary.v1",
boundaryId: "heimdall",
daemonId: config.daemonId,
providerId: "heimdall",
updatedAt: pulse.updatedAt,
owner: "Heimdall auth runtime",
lifecycleAuthority: "idunn.yggdrasil-source-app.deploy",
healthPublication: {
contract: config.idunnHealthContract,
transport: config.idunnRudpHealth ? "cultnet.transport.rudp.v0" : "cultcache-store",
publicationSource: config.idunnRudpHealth ? "daemon-published" : "daemon-published-cultcache",
stateOwner: "Heimdall auth runtime",
},
commands: [],
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.",
],
compatibility: {
httpHealth: "/healthz",
jwks: "/.well-known/jwks.json",
discovery: "/.well-known/heimdall-configuration",
yggdrasilDeployLane: "E:/Projects/Odin/scripts/deploy-yggdrasil-heimdall.cmd",
status: "fallback-witness-only",
},
};
}
function buildTransportProfile(config: HeimdallConfig, pulse: HeimdallRuntimePulse) {
return {
schema: "heimdall.transport_profile.v1",
profileId: "heimdall",
daemonId: config.daemonId,
providerId: "heimdall",
updatedAt: pulse.updatedAt,
targetTransport: "cultnet.transport.rudp.v0",
currentTransport: config.idunnRudpHealth
? "cultcache-redacted-witness + daemon-published-rudp-health + compatibility-http"
: "cultcache-redacted-witness + compatibility.ssh-systemd-http",
healthTransport: config.idunnRudpHealth ? "cultnet.transport.rudp.v0" : "cultcache-store",
stateTransport: "cultcache-store",
rendererTransport: "browser-http-jwks-discovery-lowering",
storageBackend: pulse.storageBackend,
cutLine: config.idunnRudpHealth
? "Heimdall now publishes daemon-owned witness state and Idunn health; systemd, /healthz, JWKS, discovery, and nginx routing can be demoted to deployment/debug witnesses once Odin consumes the typed store."
: "Heimdall now publishes a daemon-owned witness store; the remaining transport debt is Idunn health publication over CultNet/RUDP and Odin ingestion of the typed witness surface.",
};
}
function buildDaemonHealthRecord(config: HeimdallConfig, pulse: HeimdallRuntimePulse) {
return [
config.daemonId,
"active",
buildHeimdallHealthDetail(config, pulse),
pulse.updatedAt,
config.idunnHealthContract,
config.idunnRudpHealth ? "daemon-published" : "daemon-published-cultcache",
config.idunnRudpHealth ? "cultnet.transport.rudp.v0" : "cultcache-store",
];
}
async function writeCultCacheSnapshot(filePath: string, records: CultCacheRecord[]): Promise<void> {
await mkdir(path.dirname(filePath), { recursive: true });
const catalog = records.map((record) => [
record.schemaId,
record.schemaName,
record.schemaVersion,
record.schemaId,
JSON.stringify({
schemaName: record.schemaName,
schemaVersion: record.schemaVersion,
members: [],
}),
[record.schemaId],
[],
]);
const entries = records.map((record) => [record.key, record.schemaId, record.storedAt, encode(record.payload)]);
const tempPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
try {
await writeFile(tempPath, encode([STORE_FORMAT_VERSION, catalog, entries]));
await rename(tempPath, filePath);
} catch (error) {
await rm(tempPath, { force: true }).catch(() => undefined);
throw error;
}
}

View file

@ -128,12 +128,12 @@ export interface EveProviderAdvertisementDocument {
verseId: "gamecult";
rootVerse: "asgard";
canonicalService: "asgard.heimdall";
locatedService: "asgard.starfire.heimdall";
cultMeshAddress: "asgard.starfire.heimdall/eve/tui";
locatedService: "asgard.yggdrasil.heimdall";
cultMeshAddress: "asgard.yggdrasil.heimdall/eve/tui";
title: "Heimdall";
description: string;
version: string;
status: "read_only_witness_planned";
status: "read_only_witness_planned" | "daemon_live";
updatedAt: string;
provider: {
id: "heimdall";
@ -169,8 +169,8 @@ export function buildHeimdallProviderAdvertisement(options: { updatedAt: string
verseId: "gamecult",
rootVerse: "asgard",
canonicalService: "asgard.heimdall",
locatedService: "asgard.starfire.heimdall",
cultMeshAddress: "asgard.starfire.heimdall/eve/tui",
locatedService: "asgard.yggdrasil.heimdall",
cultMeshAddress: "asgard.yggdrasil.heimdall/eve/tui",
title: "Heimdall",
description: "Shared GameCult auth/control-plane authority with redacted CultCache witness projections.",
version: "read-only-witness-v0",
@ -193,7 +193,7 @@ export function buildHeimdallProviderAdvertisement(options: { updatedAt: string
transport: "CultMesh provider advertisement; first cut is a read-only fixture/export.",
},
controlSurface: {
primary: "asgard.starfire.heimdall/eve/tui",
primary: "asgard.yggdrasil.heimdall/eve/tui",
controls: {
mode: "read-only",
writes: false,
@ -201,9 +201,9 @@ export function buildHeimdallProviderAdvertisement(options: { updatedAt: string
},
},
endpoints: [
"asgard.starfire.heimdall/eve/tui",
"asgard.starfire.heimdall/eve/gui",
"asgard.starfire.heimdall/witness",
"asgard.yggdrasil.heimdall/eve/tui",
"asgard.yggdrasil.heimdall/eve/gui",
"asgard.yggdrasil.heimdall/witness",
],
routes: [
{