Land Heimdall service skeleton
This commit is contained in:
parent
49fb467950
commit
58a12a2835
20 changed files with 3001 additions and 33 deletions
172
src/app-profiles.ts
Normal file
172
src/app-profiles.ts
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
import { type AppSlug, type LinkedIdentityInput, type Provider } from "./contracts.js";
|
||||
|
||||
export type CapabilityMode = "shared" | "hybrid";
|
||||
|
||||
export interface CapabilityDefinition {
|
||||
key: string;
|
||||
mode: CapabilityMode;
|
||||
summary: string;
|
||||
sharedRule?: string;
|
||||
localRequirement?: string;
|
||||
}
|
||||
|
||||
export interface ClaimEvaluationContext {
|
||||
accountId: string;
|
||||
facts: Set<string>;
|
||||
identities: LinkedIdentityInput[];
|
||||
}
|
||||
|
||||
export interface AppProfile {
|
||||
slug: AppSlug;
|
||||
displayName: string;
|
||||
profileVersion: string;
|
||||
identityProviders: Provider[];
|
||||
entitlementSources: Provider[];
|
||||
managedConnectionProviders: Provider[];
|
||||
capabilities: CapabilityDefinition[];
|
||||
evaluateSharedCapabilities(context: ClaimEvaluationContext): string[];
|
||||
}
|
||||
|
||||
function hasAnyFact(facts: Set<string>, values: readonly string[]): boolean {
|
||||
return values.some((value) => facts.has(value));
|
||||
}
|
||||
|
||||
const repixelizerProfile: AppProfile = {
|
||||
slug: "repixelizer",
|
||||
displayName: "Repixelizer",
|
||||
profileVersion: "2026-04-26",
|
||||
identityProviders: ["discord", "patreon"],
|
||||
entitlementSources: ["discord", "patreon"],
|
||||
managedConnectionProviders: [],
|
||||
capabilities: [
|
||||
{
|
||||
key: "app_access",
|
||||
mode: "shared",
|
||||
summary: "May load the protected hosted GUI.",
|
||||
sharedRule:
|
||||
"discord.allowed_role || patreon.allowed_tier || grant.global_member || grant.app_access",
|
||||
},
|
||||
{
|
||||
key: "queue_submit",
|
||||
mode: "shared",
|
||||
summary: "May create a repixelizer job.",
|
||||
sharedRule: "app_access",
|
||||
},
|
||||
{
|
||||
key: "job_read_own",
|
||||
mode: "hybrid",
|
||||
summary: "May read own job state, event stream, and final output.",
|
||||
localRequirement: "Host app must combine app_access with job ownership.",
|
||||
},
|
||||
{
|
||||
key: "job_cancel_own",
|
||||
mode: "hybrid",
|
||||
summary: "May cancel own queued or running job.",
|
||||
localRequirement: "Host app must combine app_access with job ownership.",
|
||||
},
|
||||
{
|
||||
key: "admin_access",
|
||||
mode: "shared",
|
||||
summary: "May inspect grant/admin surfaces.",
|
||||
sharedRule: "grant.operator || grant.admin_access",
|
||||
},
|
||||
],
|
||||
evaluateSharedCapabilities(context) {
|
||||
const capabilities: string[] = [];
|
||||
const appAccess = hasAnyFact(context.facts, [
|
||||
"discord.allowed_role",
|
||||
"patreon.allowed_tier",
|
||||
"grant.global_member",
|
||||
"grant.app_access",
|
||||
]);
|
||||
|
||||
if (appAccess) {
|
||||
capabilities.push("app_access", "queue_submit");
|
||||
}
|
||||
|
||||
if (hasAnyFact(context.facts, ["grant.operator", "grant.admin_access"])) {
|
||||
capabilities.push("admin_access");
|
||||
}
|
||||
|
||||
return capabilities;
|
||||
},
|
||||
};
|
||||
|
||||
const streampixelsProfile: AppProfile = {
|
||||
slug: "streampixels",
|
||||
displayName: "StreamPixels",
|
||||
profileVersion: "2026-04-26",
|
||||
identityProviders: ["twitch", "youtube"],
|
||||
entitlementSources: [],
|
||||
managedConnectionProviders: ["twitch", "youtube"],
|
||||
capabilities: [
|
||||
{
|
||||
key: "viewer_access",
|
||||
mode: "shared",
|
||||
summary: "Authenticated viewer session for control-plane surfaces.",
|
||||
sharedRule: "identity.authenticated",
|
||||
},
|
||||
{
|
||||
key: "creator_access",
|
||||
mode: "hybrid",
|
||||
summary: "Creator-scoped route access.",
|
||||
localRequirement:
|
||||
"Host app must combine authenticated session claims with local creator membership.",
|
||||
},
|
||||
{
|
||||
key: "creator_admin",
|
||||
mode: "hybrid",
|
||||
summary: "Creator-scoped write/admin access.",
|
||||
localRequirement:
|
||||
"Host app must combine authenticated session claims with local creator admin membership.",
|
||||
},
|
||||
{
|
||||
key: "operator_access",
|
||||
mode: "shared",
|
||||
summary: "Global operator access.",
|
||||
sharedRule: "grant.operator",
|
||||
},
|
||||
],
|
||||
evaluateSharedCapabilities(context) {
|
||||
const capabilities: string[] = [];
|
||||
|
||||
if (context.facts.has("identity.authenticated")) {
|
||||
capabilities.push("viewer_access");
|
||||
}
|
||||
|
||||
if (context.facts.has("grant.operator")) {
|
||||
capabilities.push("operator_access");
|
||||
}
|
||||
|
||||
return capabilities;
|
||||
},
|
||||
};
|
||||
|
||||
export const appProfiles: Record<AppSlug, AppProfile> = {
|
||||
repixelizer: repixelizerProfile,
|
||||
streampixels: streampixelsProfile,
|
||||
};
|
||||
|
||||
export function getAppProfile(appSlug: AppSlug): AppProfile {
|
||||
return appProfiles[appSlug];
|
||||
}
|
||||
|
||||
export function serializeAppProfile(profile: AppProfile): Record<string, unknown> {
|
||||
return {
|
||||
slug: profile.slug,
|
||||
displayName: profile.displayName,
|
||||
profileVersion: profile.profileVersion,
|
||||
identityProviders: profile.identityProviders,
|
||||
entitlementSources: profile.entitlementSources,
|
||||
managedConnectionProviders: profile.managedConnectionProviders,
|
||||
capabilities: profile.capabilities,
|
||||
};
|
||||
}
|
||||
|
||||
export function supportsProvider(profile: AppProfile, provider: Provider): boolean {
|
||||
return (
|
||||
profile.identityProviders.includes(provider) ||
|
||||
profile.managedConnectionProviders.includes(provider) ||
|
||||
profile.entitlementSources.includes(provider)
|
||||
);
|
||||
}
|
||||
418
src/app.ts
Normal file
418
src/app.ts
Normal file
|
|
@ -0,0 +1,418 @@
|
|||
import { randomUUID } from "node:crypto";
|
||||
import cors from "@fastify/cors";
|
||||
import Fastify, { type FastifyInstance } from "fastify";
|
||||
import {
|
||||
appSlugs,
|
||||
connectionKinds,
|
||||
oauthModes,
|
||||
providers,
|
||||
type AccessClaimPayload,
|
||||
type AppSlug,
|
||||
type IssueClaimRequest,
|
||||
type OAuthConnectionBinding,
|
||||
type OAuthStartRequest,
|
||||
type Provider,
|
||||
} from "./contracts.js";
|
||||
import { getAppProfile, serializeAppProfile, supportsProvider } from "./app-profiles.js";
|
||||
import { type HeimdallConfig, loadConfig } from "./config.js";
|
||||
import { buildAuthorizationUrl, providerCatalog, providerExpectedEnv } from "./providers.js";
|
||||
import { createRuntimeKeyMaterial, signJwt, verifyJwt } from "./signing.js";
|
||||
|
||||
interface BuildAppOptions {
|
||||
config?: HeimdallConfig;
|
||||
}
|
||||
|
||||
function nowEpochSeconds(): number {
|
||||
return Math.floor(Date.now() / 1000);
|
||||
}
|
||||
|
||||
function clampTtlSeconds(value: number, fallback: number): number {
|
||||
if (!Number.isFinite(value)) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
return Math.max(60, Math.min(86_400, Math.trunc(value)));
|
||||
}
|
||||
|
||||
function normalizeFacts(request: IssueClaimRequest): string[] {
|
||||
const facts = new Set(request.facts ?? []);
|
||||
if (request.accountId.trim() || request.linkedIdentities?.length) {
|
||||
facts.add("identity.authenticated");
|
||||
}
|
||||
return [...facts].sort();
|
||||
}
|
||||
|
||||
function buildDiscovery(config: HeimdallConfig) {
|
||||
return {
|
||||
issuer: config.issuer,
|
||||
jwksUri: `${config.publicBaseUrl}/.well-known/jwks.json`,
|
||||
configurationUri: `${config.publicBaseUrl}/.well-known/heimdall-configuration`,
|
||||
oauthStartEndpoint: `${config.publicBaseUrl}/v1/oauth/{provider}/start`,
|
||||
oauthCallbackEndpoint: `${config.publicBaseUrl}/v1/oauth/{provider}/callback`,
|
||||
claimIssueEndpoint: `${config.publicBaseUrl}/v1/apps/{appSlug}/claims/issue`,
|
||||
supportedProviders: providers.map((provider) => ({
|
||||
key: provider,
|
||||
displayName: providerCatalog[provider].displayName,
|
||||
roles: providerCatalog[provider].roles,
|
||||
})),
|
||||
apps: appSlugs.map((appSlug) => serializeAppProfile(getAppProfile(appSlug))),
|
||||
};
|
||||
}
|
||||
|
||||
function buildOAuthStateToken(options: {
|
||||
config: HeimdallConfig;
|
||||
provider: Provider;
|
||||
appSlug: AppSlug;
|
||||
mode: OAuthStartRequest["mode"];
|
||||
returnTo: string;
|
||||
connection: OAuthConnectionBinding | undefined;
|
||||
keys: ReturnType<typeof createRuntimeKeyMaterial>;
|
||||
}): { token: string; expiresAt: string } {
|
||||
const issuedAt = nowEpochSeconds();
|
||||
const expiresAtEpoch = issuedAt + options.config.stateTtlSeconds;
|
||||
|
||||
const token = signJwt(
|
||||
{
|
||||
iss: options.config.issuer,
|
||||
sub: options.appSlug,
|
||||
aud: options.provider,
|
||||
jti: randomUUID(),
|
||||
iat: issuedAt,
|
||||
nbf: issuedAt,
|
||||
exp: expiresAtEpoch,
|
||||
typ: "heimdall_oauth_state",
|
||||
provider: options.provider,
|
||||
app_slug: options.appSlug,
|
||||
mode: options.mode,
|
||||
return_to: options.returnTo,
|
||||
connection: options.connection ?? null,
|
||||
},
|
||||
options.keys
|
||||
);
|
||||
|
||||
return {
|
||||
token,
|
||||
expiresAt: new Date(expiresAtEpoch * 1000).toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyInstance> {
|
||||
const config = options.config ?? loadConfig();
|
||||
const keys = createRuntimeKeyMaterial(config);
|
||||
const app = Fastify({ logger: false });
|
||||
app.decorate("heimdallContext", { config, keys });
|
||||
|
||||
await app.register(cors, {
|
||||
origin: true,
|
||||
credentials: true,
|
||||
});
|
||||
|
||||
app.get("/healthz", async () => ({
|
||||
ok: true,
|
||||
service: config.serviceName,
|
||||
issuer: config.issuer,
|
||||
now: new Date().toISOString(),
|
||||
}));
|
||||
|
||||
app.get("/.well-known/jwks.json", async () => ({
|
||||
keys: [keys.publicJwk],
|
||||
}));
|
||||
|
||||
app.get("/.well-known/heimdall-configuration", async () => buildDiscovery(config));
|
||||
|
||||
app.get("/v1/apps", async () => ({
|
||||
apps: appSlugs.map((appSlug) => serializeAppProfile(getAppProfile(appSlug))),
|
||||
}));
|
||||
|
||||
app.get<{ Params: { appSlug: AppSlug } }>(
|
||||
"/v1/apps/:appSlug",
|
||||
{
|
||||
schema: {
|
||||
params: {
|
||||
type: "object",
|
||||
required: ["appSlug"],
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
appSlug: { type: "string", enum: [...appSlugs] },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
async (request) => serializeAppProfile(getAppProfile(request.params.appSlug))
|
||||
);
|
||||
|
||||
app.post<{ Params: { provider: Provider }; Body: OAuthStartRequest }>(
|
||||
"/v1/oauth/:provider/start",
|
||||
{
|
||||
schema: {
|
||||
params: {
|
||||
type: "object",
|
||||
required: ["provider"],
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
provider: { type: "string", enum: [...providers] },
|
||||
},
|
||||
},
|
||||
body: {
|
||||
type: "object",
|
||||
required: ["appSlug", "mode", "returnTo"],
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
appSlug: { type: "string", enum: [...appSlugs] },
|
||||
mode: { type: "string", enum: [...oauthModes] },
|
||||
returnTo: { type: "string", format: "uri" },
|
||||
requestedScopes: {
|
||||
type: "array",
|
||||
items: { type: "string" },
|
||||
uniqueItems: true,
|
||||
},
|
||||
connection: {
|
||||
type: "object",
|
||||
required: ["kind", "targetId"],
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
kind: { type: "string", enum: [...connectionKinds] },
|
||||
targetId: { type: "string", minLength: 1 },
|
||||
summary: { type: "string" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
async (request, reply) => {
|
||||
const { provider } = request.params;
|
||||
const profile = getAppProfile(request.body.appSlug);
|
||||
|
||||
if (!supportsProvider(profile, provider)) {
|
||||
reply.code(400);
|
||||
return {
|
||||
error: "provider_not_supported_for_app",
|
||||
provider,
|
||||
appSlug: profile.slug,
|
||||
};
|
||||
}
|
||||
|
||||
const providerConfig = config.providers[provider];
|
||||
if (!providerConfig.clientId) {
|
||||
reply.code(503);
|
||||
return {
|
||||
error: "provider_not_configured",
|
||||
provider,
|
||||
expectedEnv: providerExpectedEnv(provider),
|
||||
};
|
||||
}
|
||||
|
||||
const callbackUrl = `${config.publicBaseUrl}/v1/oauth/${provider}/callback`;
|
||||
const state = buildOAuthStateToken({
|
||||
config,
|
||||
provider,
|
||||
appSlug: profile.slug,
|
||||
mode: request.body.mode,
|
||||
returnTo: request.body.returnTo,
|
||||
connection: request.body.connection,
|
||||
keys,
|
||||
});
|
||||
|
||||
reply.code(201);
|
||||
return {
|
||||
provider,
|
||||
appSlug: profile.slug,
|
||||
mode: request.body.mode,
|
||||
callbackUrl,
|
||||
authorizationUrl: buildAuthorizationUrl({
|
||||
provider,
|
||||
clientId: providerConfig.clientId,
|
||||
redirectUri: callbackUrl,
|
||||
state: state.token,
|
||||
requestedScopes: request.body.requestedScopes,
|
||||
}),
|
||||
stateToken: state.token,
|
||||
stateExpiresAt: state.expiresAt,
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
app.get<{
|
||||
Params: { provider: Provider };
|
||||
Querystring: { code?: string; state?: string; error?: string; error_description?: string };
|
||||
}>(
|
||||
"/v1/oauth/:provider/callback",
|
||||
{
|
||||
schema: {
|
||||
params: {
|
||||
type: "object",
|
||||
required: ["provider"],
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
provider: { type: "string", enum: [...providers] },
|
||||
},
|
||||
},
|
||||
querystring: {
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
code: { type: "string" },
|
||||
state: { type: "string" },
|
||||
error: { type: "string" },
|
||||
error_description: { type: "string" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
async (request, reply) => {
|
||||
if (!request.query.state) {
|
||||
reply.code(400);
|
||||
return { error: "missing_state" };
|
||||
}
|
||||
|
||||
const verification = verifyJwt(request.query.state, keys.publicKey);
|
||||
if (!verification.valid) {
|
||||
reply.code(400);
|
||||
return { error: "invalid_state", detail: verification.error };
|
||||
}
|
||||
|
||||
const statePayload = verification.payload;
|
||||
if (statePayload.typ !== "heimdall_oauth_state" || statePayload.provider !== request.params.provider) {
|
||||
reply.code(400);
|
||||
return { error: "state_provider_mismatch" };
|
||||
}
|
||||
|
||||
if (request.query.error) {
|
||||
reply.code(400);
|
||||
return {
|
||||
error: "provider_error",
|
||||
provider: request.params.provider,
|
||||
providerError: request.query.error,
|
||||
providerErrorDescription: request.query.error_description,
|
||||
};
|
||||
}
|
||||
|
||||
if (!request.query.code) {
|
||||
reply.code(400);
|
||||
return { error: "missing_code" };
|
||||
}
|
||||
|
||||
reply.code(501);
|
||||
return {
|
||||
error: "token_exchange_not_implemented",
|
||||
provider: request.params.provider,
|
||||
appSlug: statePayload.app_slug,
|
||||
mode: statePayload.mode,
|
||||
returnTo: statePayload.return_to,
|
||||
connection: statePayload.connection,
|
||||
codeReceived: true,
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
app.post<{ Params: { appSlug: AppSlug }; Body: IssueClaimRequest }>(
|
||||
"/v1/apps/:appSlug/claims/issue",
|
||||
{
|
||||
schema: {
|
||||
params: {
|
||||
type: "object",
|
||||
required: ["appSlug"],
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
appSlug: { type: "string", enum: [...appSlugs] },
|
||||
},
|
||||
},
|
||||
body: {
|
||||
type: "object",
|
||||
required: ["accountId"],
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
accountId: { type: "string", minLength: 1 },
|
||||
sessionId: { type: "string", minLength: 1 },
|
||||
displayName: { type: "string", minLength: 1 },
|
||||
facts: {
|
||||
type: "array",
|
||||
items: { type: "string" },
|
||||
uniqueItems: true,
|
||||
},
|
||||
accessRevision: { type: "integer", minimum: 1 },
|
||||
ttlSeconds: { type: "integer", minimum: 60, maximum: 86400 },
|
||||
linkedIdentities: {
|
||||
type: "array",
|
||||
items: {
|
||||
type: "object",
|
||||
required: ["provider", "providerUserId"],
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
provider: { type: "string", enum: [...providers] },
|
||||
providerUserId: { type: "string", minLength: 1 },
|
||||
username: { type: "string" },
|
||||
displayName: { type: "string" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
async (request, reply) => {
|
||||
const profile = getAppProfile(request.params.appSlug);
|
||||
const facts = normalizeFacts(request.body);
|
||||
const factSet = new Set(facts);
|
||||
const linkedIdentities = request.body.linkedIdentities ?? [];
|
||||
const sharedCapabilities = profile.evaluateSharedCapabilities({
|
||||
accountId: request.body.accountId,
|
||||
facts: factSet,
|
||||
identities: linkedIdentities,
|
||||
});
|
||||
|
||||
const issuedAt = nowEpochSeconds();
|
||||
const ttlSeconds = clampTtlSeconds(request.body.ttlSeconds ?? config.sessionTtlSeconds, config.sessionTtlSeconds);
|
||||
const expiresAtEpoch = issuedAt + ttlSeconds;
|
||||
const sessionId = request.body.sessionId ?? randomUUID();
|
||||
const accessClaim: AccessClaimPayload = {
|
||||
iss: config.issuer,
|
||||
aud: profile.slug,
|
||||
sub: request.body.accountId,
|
||||
sid: sessionId,
|
||||
jti: randomUUID(),
|
||||
iat: issuedAt,
|
||||
nbf: issuedAt,
|
||||
exp: expiresAtEpoch,
|
||||
typ: "heimdall_access",
|
||||
account_id: request.body.accountId,
|
||||
access_revision: request.body.accessRevision ?? 1,
|
||||
app: {
|
||||
slug: profile.slug,
|
||||
profile_version: profile.profileVersion,
|
||||
},
|
||||
facts,
|
||||
capabilities: sharedCapabilities,
|
||||
identities: linkedIdentities,
|
||||
};
|
||||
|
||||
if (request.body.displayName) {
|
||||
accessClaim.display_name = request.body.displayName;
|
||||
}
|
||||
|
||||
reply.code(201);
|
||||
return {
|
||||
session: {
|
||||
accountId: request.body.accountId,
|
||||
sessionId,
|
||||
appSlug: profile.slug,
|
||||
accessRevision: accessClaim.access_revision,
|
||||
expiresAt: new Date(expiresAtEpoch * 1000).toISOString(),
|
||||
},
|
||||
accessToken: signJwt(accessClaim as unknown as Record<string, unknown>, keys),
|
||||
claimSet: accessClaim,
|
||||
verification: {
|
||||
issuer: config.issuer,
|
||||
jwksUri: `${config.publicBaseUrl}/.well-known/jwks.json`,
|
||||
alg: keys.alg,
|
||||
kid: keys.kid,
|
||||
},
|
||||
sharedCapabilities,
|
||||
hybridCapabilities: profile.capabilities.filter((capability) => capability.mode === "hybrid"),
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
return app;
|
||||
}
|
||||
81
src/config.ts
Normal file
81
src/config.ts
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
import { providers, type Provider } from "./contracts.js";
|
||||
|
||||
export interface ProviderClientConfig {
|
||||
clientId?: string;
|
||||
clientSecret?: string;
|
||||
}
|
||||
|
||||
export interface HeimdallConfig {
|
||||
serviceName: string;
|
||||
host: string;
|
||||
port: number;
|
||||
publicBaseUrl: string;
|
||||
issuer: string;
|
||||
sessionTtlSeconds: number;
|
||||
stateTtlSeconds: number;
|
||||
signingPrivateKeyPem?: string;
|
||||
signingKeyId?: string;
|
||||
providers: Record<Provider, ProviderClientConfig>;
|
||||
}
|
||||
|
||||
function trimTrailingSlash(value: string): string {
|
||||
return value.replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
function readInt(envValue: string | undefined, fallback: number): number {
|
||||
if (!envValue) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const parsed = Number.parseInt(envValue, 10);
|
||||
return Number.isFinite(parsed) ? parsed : fallback;
|
||||
}
|
||||
|
||||
function readProviderConfig(env: NodeJS.ProcessEnv, provider: Provider): ProviderClientConfig {
|
||||
const prefix = `GC_ACCESS_PROVIDER_${provider.toUpperCase()}`;
|
||||
const config: ProviderClientConfig = {};
|
||||
const clientId = env[`${prefix}_CLIENT_ID`];
|
||||
const clientSecret = env[`${prefix}_CLIENT_SECRET`];
|
||||
|
||||
if (clientId) {
|
||||
config.clientId = clientId;
|
||||
}
|
||||
|
||||
if (clientSecret) {
|
||||
config.clientSecret = clientSecret;
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
export function loadConfig(env: NodeJS.ProcessEnv = process.env): HeimdallConfig {
|
||||
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 providersConfig = Object.fromEntries(
|
||||
providers.map((provider) => [provider, readProviderConfig(env, provider)])
|
||||
) as Record<Provider, ProviderClientConfig>;
|
||||
|
||||
const config: HeimdallConfig = {
|
||||
serviceName: "heimdall",
|
||||
host,
|
||||
port,
|
||||
publicBaseUrl,
|
||||
issuer,
|
||||
sessionTtlSeconds: readInt(env.GC_ACCESS_SESSION_TTL_SECONDS, 3600),
|
||||
stateTtlSeconds: readInt(env.GC_ACCESS_STATE_TTL_SECONDS, 600),
|
||||
providers: providersConfig,
|
||||
};
|
||||
|
||||
const signingPrivateKeyPem = env.GC_ACCESS_SIGNING_PRIVATE_KEY_PEM?.replace(/\\n/g, "\n");
|
||||
if (signingPrivateKeyPem) {
|
||||
config.signingPrivateKeyPem = signingPrivateKeyPem;
|
||||
}
|
||||
|
||||
if (env.GC_ACCESS_SIGNING_KEY_ID) {
|
||||
config.signingKeyId = env.GC_ACCESS_SIGNING_KEY_ID;
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
68
src/contracts.ts
Normal file
68
src/contracts.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
export const providers = ["discord", "patreon", "github", "twitch", "youtube"] as const;
|
||||
|
||||
export type Provider = (typeof providers)[number];
|
||||
|
||||
export const appSlugs = ["repixelizer", "streampixels"] as const;
|
||||
|
||||
export type AppSlug = (typeof appSlugs)[number];
|
||||
|
||||
export const oauthModes = ["sign_in", "link", "connect"] as const;
|
||||
|
||||
export type OAuthMode = (typeof oauthModes)[number];
|
||||
|
||||
export const connectionKinds = ["account", "creator", "workspace", "project", "channel"] as const;
|
||||
|
||||
export type ConnectionKind = (typeof connectionKinds)[number];
|
||||
|
||||
export interface OAuthConnectionBinding {
|
||||
kind: ConnectionKind;
|
||||
targetId: string;
|
||||
summary?: string;
|
||||
}
|
||||
|
||||
export interface OAuthStartRequest {
|
||||
appSlug: AppSlug;
|
||||
mode: OAuthMode;
|
||||
returnTo: string;
|
||||
connection?: OAuthConnectionBinding;
|
||||
requestedScopes?: string[];
|
||||
}
|
||||
|
||||
export interface LinkedIdentityInput {
|
||||
provider: Provider;
|
||||
providerUserId: string;
|
||||
username?: string;
|
||||
displayName?: string;
|
||||
}
|
||||
|
||||
export interface IssueClaimRequest {
|
||||
accountId: string;
|
||||
sessionId?: string;
|
||||
displayName?: string;
|
||||
facts?: string[];
|
||||
linkedIdentities?: LinkedIdentityInput[];
|
||||
accessRevision?: number;
|
||||
ttlSeconds?: number;
|
||||
}
|
||||
|
||||
export interface AccessClaimPayload {
|
||||
iss: string;
|
||||
aud: AppSlug;
|
||||
sub: string;
|
||||
sid: string;
|
||||
jti: string;
|
||||
iat: number;
|
||||
nbf: number;
|
||||
exp: number;
|
||||
typ: "heimdall_access";
|
||||
account_id: string;
|
||||
access_revision: number;
|
||||
display_name?: string;
|
||||
app: {
|
||||
slug: AppSlug;
|
||||
profile_version: string;
|
||||
};
|
||||
facts: string[];
|
||||
capabilities: string[];
|
||||
identities: LinkedIdentityInput[];
|
||||
}
|
||||
13
src/index.ts
Normal file
13
src/index.ts
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import { buildApp } from "./app.js";
|
||||
import { loadConfig } from "./config.js";
|
||||
|
||||
const config = loadConfig();
|
||||
const app = await buildApp({ config });
|
||||
|
||||
try {
|
||||
await app.listen({ host: config.host, port: config.port });
|
||||
app.log.info(`Heimdall listening on ${config.host}:${config.port}`);
|
||||
} catch (error) {
|
||||
app.log.error(error);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
101
src/providers.ts
Normal file
101
src/providers.ts
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
import { type Provider } from "./contracts.js";
|
||||
|
||||
export type ProviderRole = "identity" | "entitlement" | "managed_credential";
|
||||
|
||||
export interface ProviderDescriptor {
|
||||
key: Provider;
|
||||
displayName: string;
|
||||
authorizationEndpoint: string;
|
||||
defaultScopes: string[];
|
||||
roles: ProviderRole[];
|
||||
clientIdEnv: string;
|
||||
clientSecretEnv: string;
|
||||
additionalAuthorizationParams?: Record<string, string>;
|
||||
}
|
||||
|
||||
export const providerCatalog: Record<Provider, ProviderDescriptor> = {
|
||||
discord: {
|
||||
key: "discord",
|
||||
displayName: "Discord",
|
||||
authorizationEndpoint: "https://discord.com/oauth2/authorize",
|
||||
defaultScopes: ["identify", "guilds"],
|
||||
roles: ["identity", "entitlement"],
|
||||
clientIdEnv: "GC_ACCESS_PROVIDER_DISCORD_CLIENT_ID",
|
||||
clientSecretEnv: "GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET",
|
||||
},
|
||||
patreon: {
|
||||
key: "patreon",
|
||||
displayName: "Patreon",
|
||||
authorizationEndpoint: "https://www.patreon.com/oauth2/authorize",
|
||||
defaultScopes: ["identity", "identity[email]", "campaigns.members"],
|
||||
roles: ["identity", "entitlement"],
|
||||
clientIdEnv: "GC_ACCESS_PROVIDER_PATREON_CLIENT_ID",
|
||||
clientSecretEnv: "GC_ACCESS_PROVIDER_PATREON_CLIENT_SECRET",
|
||||
},
|
||||
github: {
|
||||
key: "github",
|
||||
displayName: "GitHub",
|
||||
authorizationEndpoint: "https://github.com/login/oauth/authorize",
|
||||
defaultScopes: ["read:user", "user:email"],
|
||||
roles: ["identity", "managed_credential"],
|
||||
clientIdEnv: "GC_ACCESS_PROVIDER_GITHUB_CLIENT_ID",
|
||||
clientSecretEnv: "GC_ACCESS_PROVIDER_GITHUB_CLIENT_SECRET",
|
||||
},
|
||||
twitch: {
|
||||
key: "twitch",
|
||||
displayName: "Twitch",
|
||||
authorizationEndpoint: "https://id.twitch.tv/oauth2/authorize",
|
||||
defaultScopes: ["user:read:email"],
|
||||
roles: ["identity", "managed_credential"],
|
||||
clientIdEnv: "GC_ACCESS_PROVIDER_TWITCH_CLIENT_ID",
|
||||
clientSecretEnv: "GC_ACCESS_PROVIDER_TWITCH_CLIENT_SECRET",
|
||||
},
|
||||
youtube: {
|
||||
key: "youtube",
|
||||
displayName: "YouTube",
|
||||
authorizationEndpoint: "https://accounts.google.com/o/oauth2/v2/auth",
|
||||
defaultScopes: [
|
||||
"openid",
|
||||
"email",
|
||||
"profile",
|
||||
"https://www.googleapis.com/auth/youtube.readonly",
|
||||
],
|
||||
roles: ["identity", "managed_credential"],
|
||||
clientIdEnv: "GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_ID",
|
||||
clientSecretEnv: "GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_SECRET",
|
||||
additionalAuthorizationParams: {
|
||||
access_type: "offline",
|
||||
include_granted_scopes: "true",
|
||||
prompt: "consent",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export function buildAuthorizationUrl(options: {
|
||||
provider: Provider;
|
||||
clientId: string;
|
||||
redirectUri: string;
|
||||
state: string;
|
||||
requestedScopes: string[] | undefined;
|
||||
}): string {
|
||||
const descriptor = providerCatalog[options.provider];
|
||||
const url = new URL(descriptor.authorizationEndpoint);
|
||||
const scopes = options.requestedScopes?.length ? options.requestedScopes : descriptor.defaultScopes;
|
||||
|
||||
url.searchParams.set("client_id", options.clientId);
|
||||
url.searchParams.set("redirect_uri", options.redirectUri);
|
||||
url.searchParams.set("response_type", "code");
|
||||
url.searchParams.set("scope", scopes.join(" "));
|
||||
url.searchParams.set("state", options.state);
|
||||
|
||||
for (const [key, value] of Object.entries(descriptor.additionalAuthorizationParams ?? {})) {
|
||||
url.searchParams.set(key, value);
|
||||
}
|
||||
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
export function providerExpectedEnv(provider: Provider): string[] {
|
||||
const descriptor = providerCatalog[provider];
|
||||
return [descriptor.clientIdEnv, descriptor.clientSecretEnv];
|
||||
}
|
||||
120
src/signing.ts
Normal file
120
src/signing.ts
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
import {
|
||||
createHash,
|
||||
createPrivateKey,
|
||||
createPublicKey,
|
||||
generateKeyPairSync,
|
||||
sign,
|
||||
verify,
|
||||
type KeyObject,
|
||||
} from "node:crypto";
|
||||
import { type HeimdallConfig } from "./config.js";
|
||||
|
||||
type Jwk = {
|
||||
crv?: string;
|
||||
kty?: string;
|
||||
x?: string;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
export interface RuntimeKeyMaterial {
|
||||
alg: "EdDSA";
|
||||
kid: string;
|
||||
privateKey: KeyObject;
|
||||
publicKey: KeyObject;
|
||||
publicJwk: Jwk & { alg: "EdDSA"; kid: string; use: "sig" };
|
||||
}
|
||||
|
||||
function encodeBase64Url(input: string | Buffer): string {
|
||||
return Buffer.from(input).toString("base64url");
|
||||
}
|
||||
|
||||
function decodeBase64Url(input: string): string {
|
||||
return Buffer.from(input, "base64url").toString("utf8");
|
||||
}
|
||||
|
||||
function buildKeyId(publicJwk: Jwk, explicitKeyId?: string): string {
|
||||
if (explicitKeyId) {
|
||||
return explicitKeyId;
|
||||
}
|
||||
|
||||
const thumbprint = createHash("sha256")
|
||||
.update(JSON.stringify({ crv: publicJwk.crv, kty: publicJwk.kty, x: publicJwk.x }))
|
||||
.digest("hex");
|
||||
return `ed25519-${thumbprint.slice(0, 12)}`;
|
||||
}
|
||||
|
||||
export function createRuntimeKeyMaterial(config: HeimdallConfig): RuntimeKeyMaterial {
|
||||
const privateKey = config.signingPrivateKeyPem
|
||||
? createPrivateKey(config.signingPrivateKeyPem)
|
||||
: generateKeyPairSync("ed25519").privateKey;
|
||||
const publicKey = createPublicKey(privateKey);
|
||||
const exportedJwk = publicKey.export({ format: "jwk" }) as Jwk;
|
||||
const kid = buildKeyId(exportedJwk, config.signingKeyId);
|
||||
|
||||
return {
|
||||
alg: "EdDSA",
|
||||
kid,
|
||||
privateKey,
|
||||
publicKey,
|
||||
publicJwk: {
|
||||
...exportedJwk,
|
||||
alg: "EdDSA",
|
||||
kid,
|
||||
use: "sig",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function signJwt(payload: Record<string, unknown>, keys: RuntimeKeyMaterial): string {
|
||||
const header = {
|
||||
alg: keys.alg,
|
||||
kid: keys.kid,
|
||||
typ: "JWT",
|
||||
};
|
||||
|
||||
const encodedHeader = encodeBase64Url(JSON.stringify(header));
|
||||
const encodedPayload = encodeBase64Url(JSON.stringify(payload));
|
||||
const signingInput = `${encodedHeader}.${encodedPayload}`;
|
||||
const signature = sign(null, Buffer.from(signingInput, "utf8"), keys.privateKey);
|
||||
|
||||
return `${signingInput}.${encodeBase64Url(signature)}`;
|
||||
}
|
||||
|
||||
export function decodeJwt(token: string): {
|
||||
header: Record<string, unknown>;
|
||||
payload: Record<string, unknown>;
|
||||
} {
|
||||
const [encodedHeader, encodedPayload] = token.split(".");
|
||||
if (!encodedHeader || !encodedPayload) {
|
||||
throw new Error("Malformed JWT.");
|
||||
}
|
||||
|
||||
return {
|
||||
header: JSON.parse(decodeBase64Url(encodedHeader)) as Record<string, unknown>,
|
||||
payload: JSON.parse(decodeBase64Url(encodedPayload)) as Record<string, unknown>,
|
||||
};
|
||||
}
|
||||
|
||||
export function verifyJwt(
|
||||
token: string,
|
||||
publicKey: KeyObject
|
||||
): { valid: true; header: Record<string, unknown>; payload: Record<string, unknown> } | {
|
||||
valid: false;
|
||||
error: string;
|
||||
} {
|
||||
const [encodedHeader, encodedPayload, encodedSignature] = token.split(".");
|
||||
if (!encodedHeader || !encodedPayload || !encodedSignature) {
|
||||
return { valid: false, error: "Malformed JWT." };
|
||||
}
|
||||
|
||||
const signingInput = `${encodedHeader}.${encodedPayload}`;
|
||||
const signature = Buffer.from(encodedSignature, "base64url");
|
||||
const valid = verify(null, Buffer.from(signingInput, "utf8"), publicKey, signature);
|
||||
|
||||
if (!valid) {
|
||||
return { valid: false, error: "Invalid JWT signature." };
|
||||
}
|
||||
|
||||
const { header, payload } = decodeJwt(token);
|
||||
return { valid: true, header, payload };
|
||||
}
|
||||
Loading…
Reference in a new issue