import { DomainError, type Actor } from '@wishforge/contracts'; import type { Authenticator } from './auth.js'; /** * Static service identities act for every run of a tenant, so each reaches only what its * role needs: the workflow coordinator reads state, records waits and requests repairs; * the deployer leases a built run and requests its release. */ const STATIC_ROUTES: Partial> = { worker: [/^\/runs\/[^/]+\/(state|wait|repair)$/], deployer: [/^\/runs\/[^/]+\/(lease|lease\/release|transition)$/, /^\/releases$/], }; /** * Resolves the identity behind an `/internal` request and confines it: run-scoped * execution tokens address only their own run, static service identities only their * routes, the IDE gateway only workspace authorization and Git credentials, and environment runners only * their deployment tasks. */ export async function internalActor( auth: Authenticator, request: { authorization?: string; tenant?: string; path: string; body?: unknown }, ): Promise { const actor = await auth.internal(request.authorization, request.tenant); if (actor.runId) { const addressed = /^\/runs\/([^/]+)\//.exec(request.path)?.[1] ?? (request.path === '/evidence' ? (request.body as { runId?: unknown } | undefined)?.runId : undefined); if (addressed !== actor.runId) throw new DomainError('FORBIDDEN', 'Execution token is scoped to a single run', 403); } if (actor.userId === 'workspace-gateway') { if (!/^\/workspaces\/[^/]+\/(authorize|git-credential)$/.test(request.path)) throw new DomainError('FORBIDDEN', 'Gateway identity is limited to workspace authorization', 403); } else if (actor.userId.startsWith('runner:')) { if (!request.path.startsWith('/runner/')) throw new DomainError('FORBIDDEN', 'Runner identity is limited to assigned deployment tasks', 403); } else if (!actor.runId && !(STATIC_ROUTES[actor.kind] ?? []).some(route => route.test(request.path))) throw new DomainError('FORBIDDEN', `The ${actor.kind} service identity cannot call this route`, 403); return actor; }