@burdenoff/be-sdk 2026.1202.8 → 2026.1202.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +23 -2
  2. package/dist/{EventQueueFactory-0XHOTKEv.js → EventQueueFactory-BUcnSkMy.js} +60 -16
  3. package/dist/EventQueueFactory-BUcnSkMy.js.map +1 -0
  4. package/dist/event-queue/index.d.ts +1 -1
  5. package/dist/event-queue/index.js +3 -3
  6. package/dist/{event-queue-CpVi7BET.js → event-queue-BQHi00yQ.js} +3 -3
  7. package/dist/{event-queue-CpVi7BET.js.map → event-queue-BQHi00yQ.js.map} +1 -1
  8. package/dist/graph/index.d.ts +1 -1
  9. package/dist/graph/index.js +2 -2
  10. package/dist/{graph-hPqNRoKC.js → graph-DN7nlVMg.js} +4 -4
  11. package/dist/{graph-hPqNRoKC.js.map → graph-DN7nlVMg.js.map} +1 -1
  12. package/dist/{graph-emitter-CtfPpHxL.js → graph-emitter-XCOZXOYq.js} +2 -2
  13. package/dist/{graph-emitter-CtfPpHxL.js.map → graph-emitter-XCOZXOYq.js.map} +1 -1
  14. package/dist/{index-B30y7Yry.d.ts → index-BBWo5BHp.d.ts} +1 -1
  15. package/dist/{index-Cx77z1cc.d.ts → index-C-W7uyiC.d.ts} +2 -1
  16. package/dist/{index-ChJqXbVL.d.ts → index-JlHKUsI7.d.ts} +5 -1
  17. package/dist/index.d.ts +3 -3
  18. package/dist/index.js +5 -5
  19. package/dist/init/index.js +1 -1
  20. package/dist/{init-CsfDrW9M.js → init-CCyWYElr.js} +2 -2
  21. package/dist/{init-CsfDrW9M.js.map → init-CCyWYElr.js.map} +1 -1
  22. package/dist/{middleware-aO50bLUO.js → middleware-e-1MpGtY.js} +2 -2
  23. package/dist/{middleware-aO50bLUO.js.map → middleware-e-1MpGtY.js.map} +1 -1
  24. package/dist/migration-url-CAxM9cDi.d.ts +5 -0
  25. package/dist/prisma/index.d.ts +3 -2
  26. package/dist/prisma/index.js +4 -3
  27. package/dist/prisma/migration-url.d.ts +2 -0
  28. package/dist/prisma/migration-url.js +34 -0
  29. package/dist/prisma/migration-url.js.map +1 -0
  30. package/dist/{prisma-BlB0aalN.js → prisma-B55-vKaU.js} +5 -3
  31. package/dist/{prisma-BlB0aalN.js.map → prisma-B55-vKaU.js.map} +1 -1
  32. package/dist/server/index.js +1 -1
  33. package/dist/server/index.js.map +1 -1
  34. package/package.json +6 -2
  35. package/dist/EventQueueFactory-0XHOTKEv.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["isRecord","elysiaApp"],"sources":["../../src/server/delegated-identity.ts","../../src/server/auth.ts","../../src/server/verified-delegation.ts","../../src/server/context.ts","../../src/server/workspace-execution-context.ts","../../src/server/security.ts","../../src/server/quotaGaugeRefresh.ts","../../src/server/raw-body-routes.ts","../../src/server/readiness.ts","../../src/server/dependency-watchdog.ts","../../src/server/errors.ts","../../src/server/server.ts","../../src/server/workspace-guard.ts","../../src/server/mutation-audit.ts"],"sourcesContent":["/**\n * Delegated identity helpers (BOFF-9962).\n *\n * The only trustworthy source of \"an app or agent acting for a user\" is the\n * signed `app_as_user` token issued by global-auth (App + AppUserDelegation).\n * A gateway verifies that token and forwards the decoded facts as\n * `x-verified-delegation`, which `buildContext` turns into\n * `ctx.verifiedDelegation`. The legacy `x-consent-*` headers are plain caller\n * input: every gateway strips them, and this SDK no longer reads them, so they\n * can never decide audit attribution.\n *\n * @module server/delegated-identity\n */\n\nimport type { IActor, VerifiedDelegationContext } from './types.js';\n\n/**\n * The principal recorded as `onBehalfOf` for an operation.\n *\n * With a verified delegation the gateway has already authenticated the\n * represented user as the actor, so the represented user is the principal.\n * Without one the actor acts for itself. Caller-supplied consent headers are\n * never consulted.\n */\nexport function resolveOnBehalfOf(\n actor: IActor | null,\n verifiedDelegation: VerifiedDelegationContext | undefined\n): string | undefined {\n if (verifiedDelegation && actor && verifiedDelegation.representedUserId === actor.id) {\n return verifiedDelegation.representedUserId;\n }\n return actor?.id;\n}\n\n/**\n * The verified \"agent for user\" pair behind a request, in the shape the audit\n * helpers need (for example `trackAgentActivity({ agentId, onBehalfOf })`).\n */\nexport interface DelegatedPrincipal {\n /** The global-auth App (agent) that acts. */\n agentAppId: string;\n /** The user the agent acts for; also the authenticated actor. */\n onBehalfOfUserId: string;\n /** The AppUserDelegation grant the token was issued from. */\n delegationId: string;\n /** Scopes the signed token carries. */\n scopes: readonly string[];\n /** Workspaces the grant is bound to; empty means unrestricted. */\n allowedWorkspaceIds: readonly string[];\n /** Who granted the delegation, when the token carries signed consent facts. */\n grantedBy: string | null;\n /** When the grant itself expires; null for an unbounded grant or unknown consent. */\n grantExpiresAt: Date | null;\n /** When the presented token stops being valid. */\n tokenExpiresAt: Date;\n}\n\n/**\n * Returns the verified delegated principal for a request context, or null when\n * the request was not made under a verified `app_as_user` delegation.\n */\nexport function getDelegatedPrincipal(context: {\n actor: IActor | null;\n verifiedDelegation?: VerifiedDelegationContext;\n}): DelegatedPrincipal | null {\n const delegation = context.verifiedDelegation;\n if (!delegation || !context.actor || delegation.representedUserId !== context.actor.id) {\n return null;\n }\n return {\n agentAppId: delegation.originatingAppId,\n onBehalfOfUserId: delegation.representedUserId,\n delegationId: delegation.delegationId,\n scopes: delegation.scopes,\n allowedWorkspaceIds: delegation.allowedWorkspaceIds,\n grantedBy: delegation.consent?.grantedBy ?? null,\n grantExpiresAt: delegation.consent?.expiresAt ?? null,\n tokenExpiresAt: delegation.tokenExpiresAt,\n };\n}\n","/**\n * Server Auth Module\n *\n * JWT verification with workspace secret fetching for microservices.\n * Handles HS256 tokens with secrets stored in workspace database.\n */\n\nimport { logger } from '../logger/index.js';\nimport type { IActor, JWTPayload, VerifiedDelegationContext, WorkspaceSecret } from './types.js';\nimport { resolveOnBehalfOf } from './delegated-identity.js';\n\n// Type imports from packages\nimport type * as jose from 'jose';\nimport type { VerifyOptions, Jwt, JwtPayload } from 'jsonwebtoken';\n\n/**\n * Workspace model interface for fetching JWT secrets\n */\ninterface WorkspaceModel {\n findUnique: (args: { where: { id: string } }) => Promise<{ jwtSecret?: unknown } | null>;\n}\n\ninterface DbClient {\n client: {\n workspace: WorkspaceModel;\n };\n}\n\n// Import getDb dynamically to avoid circular dependencies\nlet getDbFn: (() => DbClient) | null = null;\n\nasync function getDb(): Promise<DbClient> {\n if (!getDbFn) {\n const prismaModule = await import('../prisma/index.js');\n // Use unknown first then cast to avoid type inference issues\n getDbFn = prismaModule.getDb as unknown as () => DbClient;\n }\n return getDbFn();\n}\n\n// Interface for the subset of jsonwebtoken we use\ninterface JwtModule {\n decode(token: string, options?: { complete?: boolean }): string | Jwt | JwtPayload | null;\n verify(token: string, secretOrPublicKey: string, options?: VerifyOptions): string | JwtPayload;\n}\n\n// Module cache for dynamic imports\nlet joseModule: typeof jose | null = null;\nlet jwtModule: JwtModule | null = null;\n\nasync function getJose(): Promise<typeof jose> {\n if (!joseModule) {\n joseModule = await import('jose');\n }\n return joseModule;\n}\n\nasync function getJwt(): Promise<JwtModule> {\n if (!jwtModule) {\n const jwt = await import('jsonwebtoken');\n // Handle both ESM and CJS module formats\n jwtModule = (jwt as { default?: JwtModule }).default ?? jwt;\n }\n return jwtModule;\n}\n\n/**\n * Fetch workspace secret callback type\n */\nexport type FetchWorkspaceSecretFn = (workspaceId: string) => Promise<WorkspaceSecret | null>;\n\n/**\n * Auth configuration\n */\nexport interface AuthConfig {\n /** Function to fetch workspace JWT secret from database */\n fetchWorkspaceSecret: FetchWorkspaceSecretFn;\n}\n\nlet authConfig: AuthConfig | null = null;\n\n/**\n * Configure auth module with workspace secret fetching\n */\nexport function configureAuth(config: AuthConfig): void {\n authConfig = config;\n logger.debug('[ServerAuth] Auth configured');\n}\n\n/**\n * Default workspace secret fetcher\n *\n * Fetches JWT secret from workspace database. This is the standard implementation\n * that works with any microservice that has access to the workspace model.\n *\n * @param workspaceId - Workspace ID from JWT\n * @returns WorkspaceSecret or null if not found\n */\nexport async function fetchWorkspaceSecret(workspaceId: string): Promise<WorkspaceSecret | null> {\n try {\n const db = await getDb();\n const workspace = await db.client.workspace.findUnique({\n where: { id: workspaceId },\n });\n\n if (!workspace?.jwtSecret) {\n logger.debug('[ServerAuth] No JWT secret found for workspace', { workspaceId });\n return null;\n }\n\n return JSON.parse(JSON.stringify(workspace.jwtSecret)) as WorkspaceSecret;\n } catch (error) {\n logger.warn('[ServerAuth] Error fetching workspace secret', { workspaceId, error });\n return null;\n }\n}\n\n/**\n * Configure auth with default workspace secret fetcher\n *\n * This is automatically called by createServer if no custom auth is configured.\n */\nexport function configureDefaultAuth(): void {\n if (!authConfig) {\n configureAuth({ fetchWorkspaceSecret });\n logger.debug('[ServerAuth] Default auth configured with built-in workspace secret fetcher');\n }\n}\n\n/**\n * Generate a symmetric secret key for JWT signing\n * @returns JWK object with the generated key\n */\nexport async function generateSymmetricSecret(): Promise<jose.JWK> {\n const joseLib = await getJose();\n const secret = await joseLib.generateSecret('HS256');\n const jwk = await joseLib.exportJWK(secret);\n return jwk;\n}\n\n/**\n * Verify JWT token for workspace-scoped authentication\n *\n * @param token - JWT token to verify\n * @param secret - Optional secret for verification (if not provided, fetches from workspace)\n * @param options - JWT verification options\n * @returns Verified actor information or null if invalid\n */\nexport async function verifyJWT(token: string, secret?: string, options: VerifyOptions = {}): Promise<IActor | null> {\n try {\n const jwt = await getJwt();\n const joseLib = await getJose();\n\n // Decode to check algorithm and extract workspace_id\n const decoded = jwt.decode(token, { complete: true });\n\n if (!decoded || typeof decoded === 'string' || !decoded.payload || typeof decoded.payload !== 'object') {\n logger.warn('[ServerAuth] Invalid token format');\n return null;\n }\n\n // For workspace-scoped HS256 tokens\n if (secret) {\n // Use provided secret\n const verifiedJwt = jwt.verify(token, secret, options) as JWTPayload;\n return mapPayloadToActor(verifiedJwt);\n }\n\n // Fetch secret from workspace database\n const decodedJwt = joseLib.decodeJwt(token) as JWTPayload;\n if (!decodedJwt.workspace_id) {\n logger.warn('[ServerAuth] No workspace_id found in token');\n return null;\n }\n\n if (!authConfig?.fetchWorkspaceSecret) {\n logger.error('[ServerAuth] Auth not configured - call configureAuth() first');\n return null;\n }\n\n const workspaceSecret = await authConfig.fetchWorkspaceSecret(decodedJwt.workspace_id);\n if (!workspaceSecret) {\n logger.warn('[ServerAuth] Workspace secret not found');\n return null;\n }\n\n const keyLikeSecret = await joseLib.importJWK(workspaceSecret, 'HS256');\n const verifiedJwt = await joseLib.jwtVerify(token, keyLikeSecret, options as jose.JWTVerifyOptions);\n return mapPayloadToActor(verifiedJwt.payload as unknown as JWTPayload);\n } catch (err) {\n logger.warn('[ServerAuth] Error verifying JWT:', err);\n return null;\n }\n}\n\n/**\n * Decode JWT without verification (for extracting claims)\n */\nexport async function decodeJWT(token: string): Promise<JWTPayload | null> {\n try {\n const joseLib = await getJose();\n return joseLib.decodeJwt<JWTPayload>(token);\n } catch {\n return null;\n }\n}\n\n/**\n * Map JWT payload to IActor interface\n */\nfunction mapPayloadToActor(payload: JWTPayload): IActor {\n return {\n id: payload.sub,\n type: payload.actor_type ?? 'user',\n workspace_id: payload.workspace_id,\n tenant_id: payload.tenant_id,\n org_id: payload.org_id,\n isAdmin: payload['isAdmin'] as boolean | undefined,\n };\n}\n\n/**\n * Check if actor is authenticated\n */\nexport function authCheck(actor: IActor | null): IActor {\n if (!actor) {\n throw new Error('Please sign in');\n }\n return actor;\n}\n\n/**\n * Check workspace context and return actor ID and workspace ID\n */\nexport function workspaceCheck(context: { actor: IActor | null; workspace: { id: string } | null }): {\n actorId: string;\n workspaceId: string;\n} {\n const actor = authCheck(context.actor);\n\n if (!context.workspace?.id) {\n throw new Error('Please switch to a workspace');\n }\n\n return {\n actorId: actor.id,\n workspaceId: context.workspace.id,\n };\n}\n\n/**\n * Require workspace context - type narrowing guard for wspace layer services\n *\n * Validates that both actor and workspace are present in the context,\n * and returns a type-narrowed context where workspace and actor are guaranteed non-null.\n * Use this at the start of resolvers in wspace services to get typed access\n * to workspace context without optional chaining.\n *\n * @throws Error if actor is not authenticated\n * @throws Error if workspace context is missing\n *\n * @example\n * ```typescript\n * // In a resolver:\n * const ctx = requireWorkspace(context);\n * const workspaceId = ctx.workspace.id; // no optional chaining needed\n * const actorId = ctx.actor.id; // no optional chaining needed\n * ```\n */\nexport function requireWorkspace<T extends { actor: IActor | null; workspace: { id: string } | null }>(\n context: T\n): T & { actor: IActor; workspace: { id: string } } {\n // Validate actor is authenticated (throws if null)\n authCheck(context.actor);\n\n if (!context.workspace?.id) {\n throw new Error('Please switch to a workspace');\n }\n\n // Return the same context object with narrowed types\n return context as T & { actor: IActor; workspace: { id: string } };\n}\n\n/**\n * Check organization context and return actor ID and org ID\n */\nexport function orgCheck(context: { actor: IActor | null; organization: { id: string } | null }): {\n actorId: string;\n orgId: string;\n} {\n const actor = authCheck(context.actor);\n\n if (!context.organization?.id) {\n throw new Error('Please switch to an organization');\n }\n\n return {\n actorId: actor.id,\n orgId: context.organization.id,\n };\n}\n\n/**\n * Check tenant context and return tenant ID\n */\nexport function tenantCheck(context: { tenant: { id: string } | null }): string {\n if (!context.tenant?.id) {\n throw new Error('Tenant context is required');\n }\n return context.tenant.id;\n}\n\n/**\n * Get effective actor ID for \"on behalf of\" tracking\n *\n * Returns the principal an operation is performed for. With a verified\n * delegation (a signed `app_as_user` token checked by a gateway) that is the\n * represented user; otherwise it is the actor itself.\n *\n * Caller-supplied consent (`x-consent-*` headers or a hand-built\n * `consentContext`) is never consulted (BOFF-9962): it is unverified input\n * and would let any caller forge attribution.\n *\n * @param context - GraphQL context with actor and optional verified delegation\n * @returns Effective actor ID (the responsible principal)\n *\n * @example\n * ```typescript\n * // User acting directly\n * getEffectiveActorId({ actor: { id: \"user-123\", type: \"user\" } }) // → \"user-123\"\n *\n * // App acting for a user under a verified delegation: the gateway\n * // authenticates the represented user as the actor.\n * getEffectiveActorId({\n * actor: { id: \"user-789\", type: \"user\", provenance: \"delegated\" },\n * verifiedDelegation, // representedUserId \"user-789\", originatingAppId \"app-abc\"\n * }) // → \"user-789\"\n * ```\n */\nexport function getEffectiveActorId(context: {\n actor: IActor | null;\n verifiedDelegation?: VerifiedDelegationContext;\n}): string | null {\n return resolveOnBehalfOf(context.actor, context.verifiedDelegation) ?? null;\n}\n","import type { IActor, VerifiedDelegationContext } from './types.js';\n\n// Structural narrowing permits inspecting unknown properties without trusting their values.\nfunction object(value: unknown): Record<string, unknown> | null {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null;\n}\n\nfunction identifier(value: unknown): value is string {\n return (\n typeof value === 'string' &&\n value['length'] > 0 &&\n value['length'] <= 200 &&\n value['trim']() === value &&\n Array.from(value).every((character) => character.charCodeAt(0) >= 32 && character.charCodeAt(0) !== 127)\n );\n}\n\nfunction list(value: unknown): value is string[] {\n return Array.isArray(value) && value['length'] <= 1000 && value['every'](identifier);\n}\n\nfunction instant(value: unknown): Date | null {\n if (typeof value !== 'string') return null;\n const time = Date.parse(value);\n return Number.isFinite(time) && new Date(time).toISOString() === value ? new Date(time) : null;\n}\n\n/** Decodes transport only; JWT verification remains the gateway's responsibility. */\nexport function decodeVerifiedDelegation(\n header: string | undefined,\n actor: IActor | null,\n workspaceId: string | undefined,\n trustedGateway: boolean,\n now = Date.now()\n): VerifiedDelegationContext | undefined {\n if (\n !trustedGateway ||\n !actor ||\n actor.provenance !== 'delegated' ||\n !['user', 'super_admin'].includes(actor.type) ||\n header === undefined\n )\n return undefined;\n const invalid = () => new Error('Invalid verified delegation context');\n let raw: unknown;\n try {\n raw = JSON.parse(header);\n } catch {\n throw invalid();\n }\n const value = object(raw);\n const tokenExpiresAt = instant(value?.['tokenExpiresAt']);\n if (\n !value ||\n !identifier(value['representedUserId']) ||\n value['representedUserId'] !== actor.id ||\n !identifier(value['originatingAppId']) ||\n !identifier(value['delegationId']) ||\n !list(value['scopes']) ||\n !list(value['allowedWorkspaceIds']) ||\n !tokenExpiresAt ||\n tokenExpiresAt.getTime() <= now ||\n (workspaceId && value['allowedWorkspaceIds'].length > 0 && !value['allowedWorkspaceIds'].includes(workspaceId))\n )\n throw invalid();\n let consent: VerifiedDelegationContext['consent'] = null;\n if (value['consent'] !== null) {\n const facts = object(value['consent']);\n const grantedAt = instant(facts?.['grantedAt']);\n const expiresAt = facts?.['expiresAt'] === null ? null : instant(facts?.['expiresAt']);\n if (\n !facts ||\n !identifier(facts['grantedBy']) ||\n !grantedAt ||\n grantedAt.getTime() > now ||\n (facts['expiresAt'] !== null &&\n (!expiresAt || expiresAt.getTime() <= grantedAt.getTime() || tokenExpiresAt.getTime() > expiresAt.getTime()))\n )\n throw invalid();\n consent = { grantedBy: facts['grantedBy'], grantedAt, expiresAt };\n }\n return {\n representedUserId: value['representedUserId'],\n originatingAppId: value['originatingAppId'],\n delegationId: value['delegationId'],\n scopes: [...value['scopes']],\n allowedWorkspaceIds: [...value['allowedWorkspaceIds']],\n tokenExpiresAt,\n consent,\n };\n}\n","/**\n * Server Context Module\n *\n * Builds GraphQL context from request headers, JWT, and configuration.\n * Automatically populates actor, tenant, workspace, and tracking information.\n *\n * **Actor-Based Authentication:**\n * - Production: Gateway verifies JWT → populates x-actor-* headers → services trust headers\n * - Development: Services verify JWT directly and build actor from payload\n *\n * Uses standard Web API Request (compatible with Bun/Elysia).\n */\n\nimport { logger } from '../logger/index.js';\nimport crypto from 'node:crypto';\nimport { verifyJWT } from './auth.js';\nimport { decodeVerifiedDelegation } from './verified-delegation.js';\nimport { resolveOnBehalfOf } from './delegated-identity.js';\nimport { parseAssistantSessionHeaders } from '../activity/assistant-session.js';\nimport type {\n GraphQLContext,\n ActorProvenance,\n IActor,\n ITenant,\n IOrganization,\n IWorkspace,\n IProject,\n IProduct,\n ITracking,\n} from './types.js';\nimport type { I18n, I18nContext } from '../i18n/index.js';\nimport { setWorkspaceContext } from '../prisma/workspace-extension.js';\n\n/**\n * Context builder options\n */\nexport interface ContextBuilderOptions {\n /** Database getter function */\n getDb: () => unknown;\n /** Default tenant info (optional) */\n defaultTenant?: ITenant;\n /** I18n instance (optional) */\n i18n?: I18n;\n}\n\nlet contextOptions: ContextBuilderOptions | null = null;\n\n/**\n * Configure context builder\n */\nexport function configureContext(options: ContextBuilderOptions): void {\n contextOptions = options;\n logger.debug('[ServerContext] Context builder configured');\n}\n\n/**\n * Extract header value from standard Web API Request\n */\nfunction getHeader(request: Request, key: string): string | undefined {\n return request.headers.get(key.toLowerCase()) ?? undefined;\n}\n\nfunction compareSecret(provided: string, expected: string): boolean {\n const providedBuffer = Buffer.from(provided);\n const expectedBuffer = Buffer.from(expected);\n\n if (providedBuffer.length !== expectedBuffer.length) {\n return false;\n }\n\n return crypto.timingSafeEqual(providedBuffer, expectedBuffer);\n}\n\nexport function shouldTrustActorHeaders(\n request: Request,\n nodeEnv: string | undefined = process.env['NODE_ENV'],\n expectedGatewayToken: string | undefined = process.env['TRUSTED_GATEWAY_TOKEN'] ??\n process.env['INTERNAL_SERVICE_TOKEN']\n): boolean {\n if (!getHeader(request, 'x-actor-id')) {\n return false;\n }\n\n if (nodeEnv === 'production') {\n return true;\n }\n\n const providedGatewayToken =\n getHeader(request, 'x-internal-service-token') || getHeader(request, 'x-gateway-auth-token');\n if (!expectedGatewayToken || !providedGatewayToken) {\n return false;\n }\n\n return compareSecret(providedGatewayToken, expectedGatewayToken);\n}\n\n/**\n * Extract tracking information from request\n */\nfunction extractTracking(request: Request): ITracking {\n // Get IP from various possible headers\n const forwardedFor = getHeader(request, 'x-forwarded-for');\n const realIp = getHeader(request, 'x-real-ip');\n const ip = forwardedFor?.split(',')[0]?.trim() || realIp || undefined;\n\n return {\n ip,\n userAgent: getHeader(request, 'user-agent'),\n };\n}\n\n/**\n * Extract actor from gateway-injected headers or authorization header\n *\n * **Actor-Based Authentication:**\n * - If x-actor-id header exists, trust it (gateway-authenticated)\n * - Otherwise fall back to JWT verification (direct access in dev)\n *\n * This allows:\n * - Production: Gateway verifies JWT → populates x-actor-* headers → services trust headers\n * - Development: Direct service access with JWT → service verifies JWT itself\n * - Development testing: Direct headers → service trusts headers\n */\nfunction actorProvenance(request: Request): ActorProvenance {\n const value = getHeader(request, 'x-verified-actor-provenance');\n return value === 'direct_human' || value === 'delegated' || value === 'non_human' ? value : 'unknown';\n}\n\nasync function extractActor(request: Request): Promise<IActor | null> {\n // Check for gateway-injected actor headers first\n const actorId = getHeader(request, 'x-actor-id');\n\n if (actorId && shouldTrustActorHeaders(request)) {\n // Gateway has already verified JWT and populated context headers\n // Trust the headers (gateway is the security perimeter)\n logger.debug('[ServerContext] Using gateway-authenticated actor from headers');\n\n const actorType = getHeader(request, 'x-actor-type') || 'user';\n const userRole = getHeader(request, 'x-user-role');\n const verifiedServiceIdentity = getHeader(request, 'x-verified-service-identity')?.trim() || undefined;\n\n return {\n id: actorId,\n type: actorType,\n provenance: actorProvenance(request),\n ...(verifiedServiceIdentity ? { verifiedServiceIdentity } : {}),\n workspace_id: getHeader(request, 'x-workspace-id'),\n tenant_id: getHeader(request, 'x-tenant-id'),\n org_id: getHeader(request, 'x-org-id') || getHeader(request, 'x-organization-id'),\n isAdmin:\n actorType === 'super_admin' ||\n userRole === 'TENANT_ADMIN' ||\n userRole === 'SUPER_ADMIN' ||\n userRole === 'PLATFORM_ADMIN',\n };\n }\n\n if (actorId) {\n logger.warn('[ServerContext] Ignoring untrusted actor headers and falling back to JWT verification');\n }\n\n // FALLBACK: No gateway headers, verify JWT directly (dev/testing mode)\n const authHeader = getHeader(request, 'authorization');\n\n if (!authHeader?.startsWith('Bearer ')) {\n return null;\n }\n\n const token = authHeader.substring(7);\n\n try {\n logger.debug('[ServerContext] No gateway headers, verifying JWT directly for actor (dev mode)');\n const payload = await verifyJWT(token);\n\n if (!payload) {\n return null;\n }\n\n // Build actor from JWT payload\n return {\n id: payload.id,\n type: 'user', // Default to 'user' if not specified\n provenance: 'unknown', // Development fallback does not attest gateway provenance.\n workspace_id: payload.workspace_id,\n };\n } catch (error) {\n logger.warn('[ServerContext] Invalid JWT token:', error);\n return null;\n }\n}\n\n/**\n * Extract tenant from headers\n */\nfunction extractTenant(request: Request): ITenant | null {\n // Check headers\n const tenantId = getHeader(request, 'x-tenant-id');\n const tenantEndpoint = getHeader(request, 'x-tenant-endpoint');\n\n if (tenantId) {\n return {\n id: tenantId,\n endpoint: tenantEndpoint || '',\n };\n }\n\n // Fall back to default tenant if configured\n return contextOptions?.defaultTenant || null;\n}\n\n/**\n * Extract organization from headers\n */\nfunction extractOrganization(request: Request): IOrganization | null {\n const orgId = getHeader(request, 'x-org-id') || getHeader(request, 'x-organization-id');\n\n if (orgId) {\n return { id: orgId };\n }\n\n return null;\n}\n\n/**\n * Extract workspace from headers or actor\n */\nfunction extractWorkspace(request: Request, actor: IActor | null): IWorkspace | null {\n // Check headers first\n const workspaceId = getHeader(request, 'x-workspace-id');\n\n if (workspaceId) {\n return { id: workspaceId };\n }\n\n // Fall back to workspace_id from actor\n if (actor?.workspace_id) {\n return { id: actor.workspace_id };\n }\n\n return null;\n}\n\n/**\n * Extract project from headers\n */\nfunction extractProject(request: Request): IProject | null {\n const projectId = getHeader(request, 'x-project-id');\n\n if (projectId) {\n return { id: projectId };\n }\n\n return null;\n}\n\n/**\n * Extract product from headers\n */\nfunction extractProduct(request: Request): IProduct | null {\n const productId = getHeader(request, 'x-product-id');\n\n if (productId) {\n return { id: productId };\n }\n\n return null;\n}\n\n/**\n * Extract geography context from headers\n *\n * Geography headers carry the user's selected location context,\n * used for currency defaults, tax calculations, payment routing,\n * data residency, and regional support.\n *\n * Headers:\n * - x-geo-country: ISO 3166-1 alpha-2 country code (e.g., 'IN', 'US', 'DE')\n * - x-geo-currency: ISO 4217 currency code (e.g., 'INR', 'USD', 'EUR')\n * - x-geo-timezone: IANA timezone (e.g., 'Asia/Kolkata', 'America/New_York')\n */\nfunction extractGeography(request: Request): { country?: string; currency?: string; timezone?: string } {\n const country = getHeader(request, 'x-geo-country');\n const currency = getHeader(request, 'x-geo-currency');\n const timezone = getHeader(request, 'x-geo-timezone');\n\n return {\n country: country?.toUpperCase() || undefined,\n currency: currency?.toUpperCase() || undefined,\n timezone: timezone || undefined,\n };\n}\n\n/**\n * Build GraphQL context from standard Web Request\n *\n * Also sets the workspace context in AsyncLocalStorage for automatic\n * Prisma workspaceId injection via the workspace extension.\n */\nexport async function buildContext(request: Request): Promise<GraphQLContext> {\n if (!contextOptions) {\n throw new Error('[ServerContext] Context not configured - call configureContext() first');\n }\n\n // Extract actor from headers/JWT\n const actor = await extractActor(request);\n\n // Extract all context parts\n const tenant = extractTenant(request);\n const organization = extractOrganization(request);\n const workspace = extractWorkspace(request, actor);\n const project = extractProject(request);\n const product = extractProduct(request);\n const tracking = extractTracking(request);\n const trustedGatewayHeaders = shouldTrustActorHeaders(request);\n const verifiedDelegation = decodeVerifiedDelegation(\n getHeader(request, 'x-verified-delegation'),\n actor,\n workspace?.id,\n trustedGatewayHeaders\n );\n // BOFF-9649: the AI assistant session behind this request, as the public gateway verified it\n // from the session relay's signed marker. Read only with an actor whose gateway headers this\n // service already trusts; the public gateways strip any client-supplied copy.\n const assistantSession =\n actor && trustedGatewayHeaders ? parseAssistantSessionHeaders((name) => getHeader(request, name)) : undefined;\n const verifiedServiceIdentity =\n actor && trustedGatewayHeaders ? getHeader(request, 'x-verified-service-identity')?.trim() || undefined : undefined;\n\n // Build i18n context if configured\n let i18n: I18nContext | undefined;\n if (contextOptions.i18n) {\n i18n = contextOptions.i18n.createContextFromRequest(request);\n }\n\n // Merge geography context from x-geo-* headers into i18n\n const geo = extractGeography(request);\n if (geo.country || geo.currency || geo.timezone) {\n if (i18n) {\n // Merge geography fields into existing i18n context\n if (geo.country) i18n.country = geo.country;\n if (geo.currency) i18n.currency = geo.currency;\n if (geo.timezone) i18n.timezone = geo.timezone;\n } else {\n // Create minimal i18n context with geography only (when i18n module not configured)\n i18n = {\n locale: 'en-US',\n language: 'en',\n country: geo.country,\n currency: geo.currency,\n timezone: geo.timezone,\n t: (key: string) => key,\n tp: (key: string) => key,\n formatNumber: (value: number) => String(value),\n formatCurrency: (value: number, currency: string) => `${currency} ${value}`,\n formatDate: (date: Date | string) => String(date),\n formatRelativeTime: (value: number, unit: Intl.RelativeTimeFormatUnit) => `${value} ${unit}`,\n };\n }\n }\n\n // Determine onBehalfOf for audit trails (BOFF-9962). Only a verified\n // delegation (signed app_as_user token checked by a gateway) may name a\n // principal other than the actor. Raw x-consent-* headers are caller input\n // and are deliberately not read: they could otherwise forge attribution.\n const onBehalfOf = resolveOnBehalfOf(actor, verifiedDelegation);\n\n // Set workspace context in AsyncLocalStorage for Prisma workspace extension\n // This enables automatic workspaceId injection on create/update operations\n const wsCtxPayload = {\n workspaceId: workspace?.id,\n tenantId: tenant?.id,\n actorId: actor?.id,\n actorType: actor?.type,\n organizationId: organization?.id,\n projectId: project?.id,\n onBehalfOf,\n ...(assistantSession ? { assistantSession } : {}),\n };\n\n logger.debug('[ServerContext] Setting workspace context', {\n workspaceId: wsCtxPayload.workspaceId ?? 'NONE',\n actorId: wsCtxPayload.actorId ?? 'NONE',\n rawHeader: getHeader(request, 'x-workspace-id') ?? 'MISSING',\n });\n\n setWorkspaceContext(wsCtxPayload);\n\n // The Cloudflare Access credentials this request presented are not stored here. The\n // execution plugin and the REST/raw-body/graph-export handlers bind them from this context's\n // `request` together with the rest of the request scope (workspaceContextFromServerContext),\n // so ContextManager.getCfAccessHeaders() sees them only inside this request's own scope.\n\n return {\n request,\n actor,\n tenant,\n organization,\n workspace,\n project,\n product,\n tracking,\n verifiedDelegation,\n ...(verifiedServiceIdentity ? { verifiedServiceIdentity } : {}),\n ...(assistantSession ? { assistantSession } : {}),\n onBehalfOf: onBehalfOf || actor?.id || '',\n db: contextOptions.getDb(),\n i18n,\n responseHeaders: new Headers(),\n };\n}\n\n/**\n * Get context options\n */\nexport function getContextOptions(): ContextBuilderOptions | null {\n return contextOptions;\n}\n","import type { Plugin } from 'graphql-yoga';\n\nimport { readAssistantSessionAttribution } from '../activity/assistant-session.js';\nimport { withWorkspaceContext, type WorkspaceContext } from '../prisma/workspace-extension.js';\nimport type { CfAccessCredentials } from '../types/index.js';\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction string(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction id(value: unknown): string | undefined {\n return record(value) ? string(value['id']) : undefined;\n}\n\nfunction header(request: unknown, name: string): string | undefined {\n if (!record(request)) return undefined;\n const headers = request['headers'];\n if (!record(headers) || typeof headers['get'] !== 'function') return undefined;\n // Duck-typed so any Fetch-API `Headers` implementation (Bun, undici, Yoga's) is accepted.\n return string((headers as unknown as Headers).get(name));\n}\n\n/**\n * The Cloudflare Access credentials the request itself presented, read from its own headers.\n * The public gateway forwards them only for requests that transited Cloudflare. A lone\n * service-token half is dropped, since it can never pass Access on its own.\n */\nexport function cfAccessFromRequest(request: unknown): CfAccessCredentials | undefined {\n const clientId = header(request, 'cf-access-client-id');\n const clientSecret = header(request, 'cf-access-client-secret');\n const authorization = header(request, 'x-cf-authorization');\n const pair = clientId && clientSecret ? { clientId, clientSecret } : undefined;\n if (!pair && !authorization) return undefined;\n return { ...pair, ...(authorization ? { authorization } : {}) };\n}\n\n/**\n * The workspace context for a request, read from the verified server context\n * (`buildContext`'s result or a Yoga `contextValue`). Unknown shapes yield an\n * empty context: no workspace, so the extension's strict mode applies. The\n * Cloudflare Access credentials come from the context's own `request`, so the\n * bound scope carries exactly the credentials that request presented.\n */\nexport function workspaceContextFromServerContext(value: unknown): WorkspaceContext {\n if (!record(value)) return {};\n const assistantSession = readAssistantSessionAttribution(value['assistantSession']);\n const cfAccess = cfAccessFromRequest(value['request']);\n return {\n ...(assistantSession ? { assistantSession } : {}),\n ...(cfAccess ? { cfAccess } : {}),\n workspaceId: id(value['workspace']),\n tenantId: id(value['tenant']),\n organizationId: id(value['organization']),\n projectId: id(value['project']),\n actorId: id(value['actor']),\n actorType: record(value['actor']) ? string(value['actor']['type']) : undefined,\n onBehalfOf: string(value['onBehalfOf']),\n };\n}\n\nfunction scopedIterable<T>(source: AsyncIterable<T>, scope: WorkspaceContext): AsyncIterable<T> {\n return {\n [Symbol.asyncIterator]() {\n const iterator = source[Symbol.asyncIterator]();\n const finish = iterator.return?.bind(iterator);\n const fail = iterator.throw?.bind(iterator);\n return {\n next: (...args: [] | [unknown]) => withWorkspaceContext(scope, async () => iterator.next(...args)),\n return: finish ? (value?: unknown) => withWorkspaceContext(scope, async () => finish(value)) : undefined,\n throw: fail ? (error?: unknown) => withWorkspaceContext(scope, async () => fail(error)) : undefined,\n };\n },\n };\n}\n\n/** Context creation and GraphQL execution may run in different async chains.\n * Bind execution to its own verified context instead of the most recent request's fallback.\n */\nexport function createWorkspaceExecutionContextPlugin(): Plugin {\n return {\n onExecute({ executeFn, setExecuteFn }) {\n setExecuteFn((args) => {\n const scope = workspaceContextFromServerContext(args.contextValue);\n return withWorkspaceContext(scope, async () => {\n const result = await executeFn(args);\n return Symbol.asyncIterator in result ? scopedIterable(result, scope) : result;\n });\n });\n },\n onSubscribe({ subscribeFn, setSubscribeFn }) {\n setSubscribeFn((args) => {\n const scope = workspaceContextFromServerContext(args.contextValue);\n return withWorkspaceContext(scope, async () => {\n const result = await subscribeFn(args);\n return Symbol.asyncIterator in result ? scopedIterable(result, scope) : result;\n });\n });\n },\n };\n}\n\n/**\n * Run a REST or raw-body endpoint handler inside its own request's verified\n * workspace context. `buildContext` binds the context with `enterWith`, which\n * does not reach the caller that awaited it, so without this the handler would\n * run with no bound context.\n */\nexport function runWithServerWorkspaceContext<T>(serverContext: unknown, fn: () => Promise<T>): Promise<T> {\n return withWorkspaceContext(workspaceContextFromServerContext(serverContext), fn);\n}\n","import type { IActor } from './types.js';\n\nconst LOCALHOST_ORIGINS = [\n 'http://localhost:3000',\n 'http://localhost:4000',\n 'http://localhost:5173',\n 'http://127.0.0.1:3000',\n 'http://127.0.0.1:4000',\n 'http://127.0.0.1:5173',\n];\n\nexport function normalizeCorsOrigins(\n origins: string | string[] | undefined,\n environment: 'development' | 'staging' | 'production' | undefined\n): string[] {\n const normalized = (Array.isArray(origins) ? origins : origins?.split(',') || [])\n .map((origin) => origin.trim())\n .filter(Boolean);\n\n if (normalized.length === 0) {\n return environment === 'production' ? [] : LOCALHOST_ORIGINS;\n }\n\n if (normalized.includes('*')) {\n return environment === 'production' ? [] : LOCALHOST_ORIGINS;\n }\n\n return normalized;\n}\n\nexport function resolveAllowedCorsOrigin(requestOrigin: string | null, allowedOrigins: string[]): string | null {\n if (!requestOrigin) {\n return allowedOrigins[0] ?? null;\n }\n\n return allowedOrigins.includes(requestOrigin) ? requestOrigin : null;\n}\n\nexport function canAccessGraphExport(actor: IActor | null): boolean {\n if (!actor) {\n return false;\n }\n\n return actor.isAdmin === true || ['service', 'super_admin'].includes(actor.type);\n}\n","/**\n * Workspace quota gauge refresh throttling for the `/metrics` route.\n *\n * `WorkspaceQuotaRegistry.collectAll()` issues Prisma groupBy queries. Running\n * it inline on every Prometheus scrape made `/metrics` exactly as slow as the\n * database: services that registered quota collectors routinely exceeded a 30s\n * `scrape_timeout` and were recorded as down, even though the endpoint itself\n * was healthy.\n *\n * Scrapes are far more frequent than these values meaningfully change, so\n * refresh on a TTL, bound each refresh, and let concurrent scrapes share one\n * in-flight attempt. A slow or unavailable database then degrades gauge\n * freshness instead of failing the scrape.\n *\n * @module server/quotaGaugeRefresh\n */\n\n/**\n * Read a positive-integer millisecond setting from the environment.\n *\n * Anything unset, non-numeric, or <= 0 falls back to the default: an operator\n * typo must not silently disable the throttle that keeps `/metrics` fast.\n */\nexport function envMs(name: string, fallback: number): number {\n const raw = process.env[name];\n if (!raw) return fallback;\n const parsed = Number.parseInt(raw, 10);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;\n}\n\n/**\n * How long a gauge snapshot is considered fresh.\n *\n * Override with `BOFF_QUOTA_GAUGE_TTL_MS` — raise it when the database is under\n * load and quota freshness matters less than scrape latency.\n */\nexport const QUOTA_GAUGE_TTL_MS = envMs('BOFF_QUOTA_GAUGE_TTL_MS', 60_000);\n\n/**\n * Upper bound on a single refresh, so a slow database cannot stall a scrape.\n *\n * Override with `BOFF_QUOTA_GAUGE_TIMEOUT_MS`. Keep it comfortably below the\n * Prometheus `scrape_timeout`, or a slow refresh still fails the scrape.\n */\nexport const QUOTA_GAUGE_REFRESH_TIMEOUT_MS = envMs('BOFF_QUOTA_GAUGE_TIMEOUT_MS', 5_000);\n\nexport interface QuotaGaugeRefresherOptions {\n /** Performs the actual (expensive) collection. */\n collect: () => Promise<unknown>;\n ttlMs?: number;\n timeoutMs?: number;\n /** Injectable clock, for tests. */\n now?: () => number;\n}\n\nexport interface QuotaGaugeRefresher {\n /** Refresh if stale. Never rejects. */\n refresh: () => Promise<void>;\n /** Epoch ms of the last completed attempt (0 when never run). */\n lastRefreshedAt: () => number;\n}\n\n/**\n * Build a TTL-throttled, timeout-bounded, single-flight refresher.\n *\n * `refresh()` never rejects — `/metrics` must keep serving prom-client and SDK\n * registry output even when the quota registry is unconfigured or erroring.\n * A failed attempt does not advance the TTL, so the next scrape retries.\n */\nexport function createQuotaGaugeRefresher(opts: QuotaGaugeRefresherOptions): QuotaGaugeRefresher {\n const ttlMs = opts.ttlMs ?? QUOTA_GAUGE_TTL_MS;\n const timeoutMs = opts.timeoutMs ?? QUOTA_GAUGE_REFRESH_TIMEOUT_MS;\n const now = opts.now ?? ((): number => Date.now());\n\n let refreshedAt = 0;\n let inFlight: Promise<void> | null = null;\n\n const refresh = async (): Promise<void> => {\n if (refreshedAt !== 0 && now() - refreshedAt < ttlMs) return;\n\n if (!inFlight) {\n inFlight = (async (): Promise<void> => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n Promise.resolve(opts.collect()).then(() => undefined),\n new Promise<void>((resolve) => {\n timer = setTimeout(resolve, timeoutMs);\n }),\n ]);\n // Stamp only on a completed attempt; a throw leaves the TTL expired\n // so the next scrape retries rather than serving a stale snapshot\n // forever.\n refreshedAt = now();\n } catch {\n /* unconfigured registry or failed query — keep the previous snapshot */\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n inFlight = null;\n }\n })();\n }\n\n await inFlight;\n };\n\n return { refresh, lastRefreshedAt: (): number => refreshedAt };\n}\n","/**\n * Raw-body REST route resolution (BOFF-7766).\n *\n * Raw-body endpoints (webhooks: `rawBody: true`) are intercepted in `onRequest`, before Elysia\n * parses the body, so they cannot use Elysia's own router. They used to be resolved by PATH alone\n * — a Map keyed by path, then the first matching pattern — and only then compared to the request\n * method. Registering one path for several verbs therefore served exactly one of them; every other\n * verb fell through and 404'd. The method check could only reject, never select.\n *\n * Resolution is now keyed on path AND method:\n * - a registration for the request's method wins (HEAD falls back to GET, as HTTP allows);\n * - a path that is registered, but not for this method, answers 405 with an `Allow` header —\n * unless an ordinary route serves that method on the same path, in which case the request\n * falls through to Elysia exactly as before (e.g. a GET page next to a raw POST);\n * - an unknown path is not ours, and falls through.\n */\nimport type { RESTEndpoint } from './types.js';\n\nexport type RawBodyResolution =\n { kind: 'endpoint'; endpoint: RESTEndpoint } | { kind: 'method-not-allowed'; allowed: string[] };\n\n/** An ordinary (body-parsed) route, as Elysia lists it in `app.routes`. */\nexport interface OrdinaryRoute {\n method: string;\n path: string;\n}\n\ninterface PathMatcher {\n exact: string | null;\n regex: RegExp | null;\n}\n\ninterface CompiledRoute extends PathMatcher {\n byMethod: Map<string, RESTEndpoint>;\n}\n\nconst REGEX_SPECIAL = /[.*+?^${}()|[\\]\\\\]/g;\n\nfunction compile(path: string): PathMatcher {\n if (!path.includes(':') && !path.includes('*')) return { exact: path, regex: null };\n const pattern = path\n .split('/')\n .map((segment) => {\n if (segment === '*') return '.*';\n if (segment.startsWith(':')) return '[^/]+';\n return segment.replace(REGEX_SPECIAL, '\\\\$&');\n })\n .join('/');\n return { exact: null, regex: new RegExp(`^${pattern}$`) };\n}\n\nfunction matches(route: PathMatcher, pathname: string): boolean {\n return route.exact !== null ? route.exact === pathname : (route.regex?.test(pathname) ?? false);\n}\n\nfunction keyOf(route: PathMatcher): string {\n return route.exact ?? route.regex?.source ?? '';\n}\n\n/** Order the methods an `Allow` header lists: the usual verbs first, then anything else. */\nconst METHOD_ORDER = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];\nconst rank = (method: string): number => {\n const index = METHOD_ORDER.indexOf(method);\n return index === -1 ? METHOD_ORDER.length : index;\n};\n\nexport interface RawBodyRouter {\n /** How many distinct raw-body paths are registered (0 lets a service without any skip the work). */\n readonly size: number;\n /** Whether a raw-body route is registered on this path, for any method (CORS preflight). */\n hasPath(pathname: string): boolean;\n resolve(pathname: string, method: string): RawBodyResolution | null;\n}\n\n/**\n * Build the resolver for a service's raw-body endpoints. `ordinaryRoutes` lists the routes Elysia\n * itself serves; it is read lazily, only when a method misses, so routes a service registers after\n * `createServer` still count.\n */\nexport function createRawBodyRouter(\n endpoints: readonly RESTEndpoint[],\n ordinaryRoutes: () => readonly OrdinaryRoute[] = () => []\n): RawBodyRouter {\n const routes: CompiledRoute[] = [];\n for (const endpoint of endpoints.filter((ep) => ep.rawBody)) {\n const method = endpoint.method.toUpperCase();\n const compiled = compile(endpoint.path);\n let route = routes.find((candidate) => keyOf(candidate) === keyOf(compiled));\n if (!route) {\n route = { ...compiled, byMethod: new Map() };\n routes.push(route);\n }\n // First registration of a path + method wins, as Elysia's own router does.\n if (!route.byMethod.has(method)) route.byMethod.set(method, endpoint);\n }\n\n // Ordinary routes are listed lazily (a service may add some after createServer), so their\n // matchers are compiled on first sight and cached by path.\n const ordinaryMatchers = new Map<string, PathMatcher>();\n const ordinaryVerbsOn = (pathname: string): Set<string> => {\n const verbs = new Set<string>();\n for (const route of ordinaryRoutes()) {\n let matcher = ordinaryMatchers.get(route.path);\n if (!matcher) {\n matcher = compile(route.path);\n ordinaryMatchers.set(route.path, matcher);\n }\n if (matches(matcher, pathname)) verbs.add(route.method.toUpperCase());\n }\n return verbs;\n };\n\n return {\n size: routes.length,\n hasPath(pathname: string): boolean {\n return routes.some((route) => matches(route, pathname));\n },\n resolve(pathname: string, rawMethod: string): RawBodyResolution | null {\n const method = rawMethod.toUpperCase();\n // Exact paths before patterns, so `/webhooks/health` beats `/webhooks/:id`.\n const candidates = [\n ...routes.filter((route) => route.exact !== null && matches(route, pathname)),\n ...routes.filter((route) => route.exact === null && matches(route, pathname)),\n ];\n if (candidates.length === 0) return null;\n\n for (const route of candidates) {\n const endpoint = route.byMethod.get(method) ?? (method === 'HEAD' ? route.byMethod.get('GET') : undefined);\n if (endpoint) return { kind: 'endpoint', endpoint };\n }\n\n // Registered for other verbs only. An ordinary route may still serve this one.\n const ordinaryVerbs = ordinaryVerbsOn(pathname);\n const servedElsewhere =\n ordinaryVerbs.has(method) || ordinaryVerbs.has('ALL') || (method === 'HEAD' && ordinaryVerbs.has('GET'));\n if (servedElsewhere) return null;\n\n // `Allow` lists every verb the resource serves — raw-body and ordinary alike.\n const allowed = new Set<string>(ordinaryVerbs);\n for (const route of candidates) for (const verb of route.byMethod.keys()) allowed.add(verb);\n if (allowed.has('GET')) allowed.add('HEAD');\n allowed.add('OPTIONS');\n return { kind: 'method-not-allowed', allowed: [...allowed].sort((a, b) => rank(a) - rank(b)) };\n },\n };\n}\n\ninterface TimeoutCapableServer {\n timeout(request: Request, seconds: number): void;\n}\n\n/**\n * The Bun server that accepted each in-flight raw-body request, so a handler can extend its idle\n * timeout (see `extendRequestIdleTimeout`). A WeakMap: entries die with the request.\n */\nconst requestServers = new WeakMap<Request, TimeoutCapableServer>();\n\nfunction canTimeout(server: unknown): server is TimeoutCapableServer {\n return typeof (server as { timeout?: unknown } | null | undefined)?.timeout === 'function';\n}\n\nexport function rememberRequestServer(request: Request, server: unknown): void {\n if (canTimeout(server)) requestServers.set(request, server);\n}\n\n/** Bun caps a connection's idle timeout at 255 seconds. */\nexport const MAX_IDLE_TIMEOUT_SECONDS = 255;\n\n/** Default maximum body size buffered for `rawBody: true` REST endpoints (1 MiB). */\nexport const DEFAULT_RAW_BODY_MAX_BYTES = 1024 * 1024;\n\n/** Default server-wide Bun `maxRequestBodySize` ceiling (10 MiB, down from Bun's 128 MiB default). */\nexport const DEFAULT_MAX_REQUEST_BODY_SIZE = 10 * 1024 * 1024;\n\n/**\n * Thrown by {@link readBoundedRawBody} when a `rawBody: true` request declares\n * or streams more bytes than its configured limit.\n */\nexport class PayloadTooLargeError extends Error {\n public readonly status = 413;\n public readonly code = 'PAYLOAD_TOO_LARGE';\n public readonly maxBodyBytes: number;\n\n constructor(maxBodyBytes: number) {\n super(`Request body exceeds maximum allowed size of ${maxBodyBytes} bytes`);\n this.name = 'PayloadTooLargeError';\n this.maxBodyBytes = maxBodyBytes;\n }\n}\n\n/**\n * Validate and normalize a configured byte cap. Rejects negative, NaN, or\n * non-finite values by falling back to `fallback`.\n */\nexport function resolveBodyLimitBytes(configured: number | undefined, fallback: number): number {\n if (typeof configured === 'number' && Number.isFinite(configured) && configured >= 0) {\n return Math.floor(configured);\n }\n return fallback;\n}\n\n/**\n * Compute the explicit `maxRequestBodySize` to pass to `app.listen()` /\n * `Bun.serve()`, honoring an explicit server override or automatically sizing\n * to fit any opted-in large `rawBody` endpoint while staying well below Bun's\n * 128 MiB default.\n */\nexport function resolveMaxRequestBodySize(\n config: { maxBodyBytes?: number; maxRequestBodySize?: number },\n endpoints: readonly RESTEndpoint[] = []\n): number {\n if (\n typeof config.maxRequestBodySize === 'number' &&\n Number.isFinite(config.maxRequestBodySize) &&\n config.maxRequestBodySize > 0\n ) {\n return Math.floor(config.maxRequestBodySize);\n }\n const defaultRawLimit = resolveBodyLimitBytes(config.maxBodyBytes, DEFAULT_RAW_BODY_MAX_BYTES);\n let highestRawLimit = defaultRawLimit;\n for (const endpoint of endpoints) {\n if (!endpoint.rawBody) continue;\n const limit = resolveBodyLimitBytes(endpoint.maxBodyBytes, defaultRawLimit);\n if (limit > highestRawLimit) highestRawLimit = limit;\n }\n return Math.max(DEFAULT_MAX_REQUEST_BODY_SIZE, highestRawLimit);\n}\n\n/**\n * Read a request's raw body as UTF-8 while strictly enforcing `maxBodyBytes`.\n *\n * 1. Pre-rejects immediately on an oversized `Content-Length` header without\n * buffering any chunks.\n * 2. Streams `request.body` chunk-by-chunk, counting raw UTF-8 bytes and\n * cancelling the stream immediately on overflow (handles chunked transfer\n * encoding and spoofed/missing `Content-Length`).\n */\nexport async function readBoundedRawBody(\n request: Request,\n maxBodyBytes: number = DEFAULT_RAW_BODY_MAX_BYTES\n): Promise<string> {\n const limit = resolveBodyLimitBytes(maxBodyBytes, DEFAULT_RAW_BODY_MAX_BYTES);\n\n const contentLengthHeader = request.headers.get('content-length')?.trim();\n if (contentLengthHeader && /^\\d+$/.test(contentLengthHeader)) {\n const declaredBytes = Number.parseInt(contentLengthHeader, 10);\n if (declaredBytes > limit) {\n if (request.body) {\n await request.body.cancel().catch(() => undefined);\n }\n throw new PayloadTooLargeError(limit);\n }\n }\n\n if (!request.body) {\n return '';\n }\n\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let totalBytes = 0;\n\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (!value || value.byteLength === 0) continue;\n\n totalBytes += value.byteLength;\n if (totalBytes > limit) {\n await reader.cancel().catch(() => undefined);\n throw new PayloadTooLargeError(limit);\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n if (totalBytes === 0) {\n return '';\n }\n\n const combined = new Uint8Array(totalBytes);\n let offset = 0;\n for (const chunk of chunks) {\n combined.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return new TextDecoder('utf-8').decode(combined);\n}\n\n/**\n * Let one raw-body request stay idle for longer than the server default (Elysia's Bun adapter sets\n * 30 s). For handlers that legitimately hold a request open — a webhook answering with its\n * workflow's result. `seconds` is clamped to Bun's 255 s cap; 0 disables the timeout for the\n * request. Returns false when the request was not served by a Bun server that supports it.\n */\nexport function extendRequestIdleTimeout(request: Request, seconds: number): boolean {\n const server = requestServers.get(request);\n if (!server || !Number.isFinite(seconds) || seconds < 0) return false;\n server.timeout(request, Math.min(Math.floor(seconds), MAX_IDLE_TIMEOUT_SECONDS));\n return true;\n}\n","/**\n * Dependency-aware readiness for `createServer`.\n *\n * WHY THIS EXISTS\n * `createServer` used to answer `/health`, `/health/live`, `/health/ready` and\n * `/health/startup` with a hardcoded `{ status: 'healthy' }`. Nothing was ever\n * checked. Combined with gitops pointing BOTH Kubernetes probes at `/health`,\n * that meant a pod whose database or cache had gone away stayed in the Service\n * endpoints and kept answering requests with errors, and a rolling deploy could\n * report success while every replica was broken.\n *\n * gitops now splits the probes — liveness on `/health/live`, readiness on\n * `/health/ready` — and this module is what makes readiness mean something.\n *\n * THE REQUIRED / OPTIONAL SPLIT IS THE WHOLE DESIGN\n * Postgres is REQUIRED: a subgraph that cannot reach its database can serve\n * nothing, so it should leave rotation and let its siblings take the traffic.\n * Valkey and the event queue are OPTIONAL by default: they are a cache and an\n * async publisher, the service degrades rather than fails without them, and\n * making them required would take the entire fleet out of rotation\n * simultaneously the moment one shared ElastiCache cluster blinked — turning a\n * cache incident into a total outage. A service that genuinely cannot function\n * without one can promote it via `requiredDependencies`.\n *\n * Liveness deliberately checks NOTHING. If liveness were deep, a shared\n * dependency blip would restart every pod in the fleet at once, which is\n * strictly worse than serving degraded.\n */\n\n/** Minimal Prisma surface used for the readiness query — keeps this testable. */\nexport interface ReadinessPrisma {\n $queryRaw: (strings: TemplateStringsArray, ...values: unknown[]) => Promise<unknown>;\n}\n\n/** Minimal Valkey/Redis surface. */\nexport interface ReadinessCache {\n ping: () => Promise<unknown>;\n}\n\n/** Minimal event-queue surface (be-sdk `IEventPublisher` implementations). */\nexport interface ReadinessEventQueue {\n isConnected?: () => boolean | Promise<boolean>;\n healthCheck?: () => Promise<{ ok: boolean }>;\n}\n\n/**\n * Minimal GraphQL subscription pubsub surface (see `graphql/pubsub-health`).\n * `undefined` means the process has no Redis-backed pubsub to report on.\n */\nexport interface ReadinessPubSub {\n ok: boolean;\n unhealthy: string[];\n}\n\n/**\n * Supervised event consumers (see `event-queue/consumer-health`).\n * `undefined` means the process has no supervised consumer to report on.\n */\nexport interface ReadinessConsumers {\n ok: boolean;\n unhealthy: string[];\n}\n\nexport type DependencyName = 'postgres' | 'valkey' | 'eventQueue' | 'pubsub' | 'consumers';\n\nexport interface ReadinessDeps {\n prisma?: () => ReadinessPrisma | undefined;\n valkey?: () => Promise<ReadinessCache | undefined> | ReadinessCache | undefined;\n eventQueue?: () => ReadinessEventQueue | undefined;\n /**\n * GraphQL subscription pubsub. Optional by default like Valkey: while it is\n * degraded the pod still serves queries and mutations, and subscribers\n * recover once the transport reconnects (BOFF-17232).\n */\n pubsub?: () => ReadinessPubSub | undefined;\n /**\n * Supervised Redis Streams consumers. Optional by default: a consumer whose\n * start is being retried does not stop the pod serving queries, and the\n * supervisor brings it back once Valkey is reachable (BOFF-17231). A\n * service whose API is useless without its consumer can promote it.\n */\n consumers?: () => ReadinessConsumers | undefined;\n /**\n * Dependencies whose failure makes the pod NOT ready. Defaults to\n * `['postgres']`. Anything checked but not listed here is reported and\n * degrades `status`, but still answers 200 so the pod stays in rotation.\n */\n requiredDependencies?: DependencyName[];\n}\n\nexport interface DependencyResult {\n ok: boolean;\n required: boolean;\n error?: string;\n /** Milliseconds the check took — surfaces a slow dependency before it fails. */\n latencyMs: number;\n}\n\nexport interface ReadinessSnapshot {\n /** True when every REQUIRED dependency is healthy. Drives the HTTP status. */\n ready: boolean;\n /** True when every checked dependency is healthy, required or not. */\n healthy: boolean;\n checks: Partial<Record<DependencyName, DependencyResult>>;\n}\n\n/**\n * Result cache TTL. Kubernetes probes every 10s across N replicas, Gatus every\n * 300s, plus any load balancer — without this each of them becomes a `SELECT 1`\n * on a connection from the same bounded pool the application needs.\n */\nexport const READINESS_CACHE_MS = 1000;\n\n/** Hard ceiling on a single dependency check, so readiness cannot hang. */\nexport const READINESS_PROBE_TIMEOUT_MS = 2000;\n\nconst DEFAULT_REQUIRED: DependencyName[] = ['postgres'];\n\nasync function withTimeout<T>(work: Promise<T>, ms: number, label: string): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n work,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(`${label} check timed out after ${ms}ms`)), ms);\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nasync function runCheck(\n name: DependencyName,\n required: boolean,\n work: () => Promise<unknown>,\n now: () => number\n): Promise<DependencyResult> {\n const started = now();\n try {\n await withTimeout(Promise.resolve(work()), READINESS_PROBE_TIMEOUT_MS, name);\n return { ok: true, required, latencyMs: now() - started };\n } catch (err) {\n return {\n ok: false,\n required,\n error: err instanceof Error ? err.message : String(err),\n latencyMs: now() - started,\n };\n }\n}\n\n/**\n * Build a cached readiness prober. Each call site gets its own cache so tests\n * never share state with a running server.\n */\nexport function createReadinessProbe(\n deps: ReadinessDeps,\n now: () => number = Date.now\n): () => Promise<ReadinessSnapshot> {\n const required = new Set<DependencyName>(deps.requiredDependencies ?? DEFAULT_REQUIRED);\n let cache: { snapshot: ReadinessSnapshot; at: number } | null = null;\n let inFlight: Promise<ReadinessSnapshot> | null = null;\n\n async function probe(): Promise<ReadinessSnapshot> {\n const checks: Partial<Record<DependencyName, DependencyResult>> = {};\n\n const jobs: Array<Promise<void>> = [];\n\n if (deps.prisma) {\n jobs.push(\n runCheck(\n 'postgres',\n required.has('postgres'),\n async () => {\n const client = deps.prisma?.();\n if (!client) throw new Error('prisma client not initialised');\n await client.$queryRaw`SELECT 1`;\n },\n now\n ).then((r) => {\n checks.postgres = r;\n })\n );\n }\n\n if (deps.valkey) {\n jobs.push(\n runCheck(\n 'valkey',\n required.has('valkey'),\n async () => {\n const client = await deps.valkey?.();\n if (!client) throw new Error('valkey client not initialised');\n await client.ping();\n },\n now\n ).then((r) => {\n checks.valkey = r;\n })\n );\n }\n\n if (deps.eventQueue) {\n jobs.push(\n runCheck(\n 'eventQueue',\n required.has('eventQueue'),\n async () => {\n const q = deps.eventQueue?.();\n if (!q) throw new Error('event queue not initialised');\n if (typeof q.isConnected === 'function') {\n const connected = await Promise.resolve(q.isConnected());\n if (!connected) throw new Error('event queue reports disconnected');\n return;\n }\n if (typeof q.healthCheck === 'function') {\n const res = await q.healthCheck();\n if (!res.ok) throw new Error('event queue health check failed');\n }\n // A queue exposing neither hook is treated as healthy rather than\n // failed — inventing a failure would take pods out of rotation for\n // a dependency we cannot actually interrogate.\n },\n now\n ).then((r) => {\n checks.eventQueue = r;\n })\n );\n }\n\n const pubsub = deps.pubsub?.();\n if (pubsub) {\n jobs.push(\n runCheck(\n 'pubsub',\n required.has('pubsub'),\n async () => {\n if (!pubsub.ok) throw new Error(`pubsub degraded (${pubsub.unhealthy.join('; ')})`);\n },\n now\n ).then((r) => {\n checks.pubsub = r;\n })\n );\n }\n\n const consumers = deps.consumers?.();\n if (consumers) {\n jobs.push(\n runCheck(\n 'consumers',\n required.has('consumers'),\n async () => {\n if (!consumers.ok) throw new Error(`event consumer degraded (${consumers.unhealthy.join('; ')})`);\n },\n now\n ).then((r) => {\n checks.consumers = r;\n })\n );\n }\n\n await Promise.all(jobs);\n\n const results = Object.values(checks);\n return {\n ready: results.every((c) => c.ok || !c.required),\n healthy: results.every((c) => c.ok),\n checks,\n };\n }\n\n return async function getReadiness(): Promise<ReadinessSnapshot> {\n const at = now();\n if (cache && at - cache.at < READINESS_CACHE_MS) return cache.snapshot;\n // Collapse concurrent probes (three probes can land in the same tick).\n if (inFlight) return inFlight;\n inFlight = probe()\n .then((snapshot) => {\n cache = { snapshot, at: now() };\n return snapshot;\n })\n .finally(() => {\n inFlight = null;\n });\n return inFlight;\n };\n}\n\nexport interface HealthBody {\n status: 'healthy' | 'degraded' | 'unavailable';\n service: string;\n version: string;\n timestamp: string;\n checks?: Partial<Record<DependencyName, DependencyResult>>;\n uptimeSeconds?: number;\n}\n\n/** HTTP status for the readiness and aggregate endpoints. */\nexport function readinessStatusCode(snapshot: ReadinessSnapshot): 200 | 503 {\n return snapshot.ready ? 200 : 503;\n}\n\nexport function readinessBody(\n snapshot: ReadinessSnapshot,\n service: string,\n version: string,\n timestamp: string,\n uptimeSeconds?: number\n): HealthBody {\n const status: HealthBody['status'] = !snapshot.ready ? 'unavailable' : snapshot.healthy ? 'healthy' : 'degraded';\n return {\n status,\n service,\n version,\n timestamp,\n checks: snapshot.checks,\n ...(uptimeSeconds === undefined ? {} : { uptimeSeconds }),\n };\n}\n\n/** Liveness body — deliberately free of any dependency information. */\nexport function livenessBody(service: string, version: string, timestamp: string): HealthBody {\n return { status: 'healthy', service, version, timestamp };\n}\n","/**\n * Dependency watchdog for the liveness probe (BOFF-17229, generalised into the\n * SDK by BOFF-17231; `createServer` wires it through `health.watchdog`).\n *\n * Readiness answers \"can this pod serve right now?\" and covers short\n * datastore blips by taking the pod out of the Service. It cannot help a\n * process that got stuck: on 2026-11-28 the alpha pod hit `EAI_AGAIN` at boot,\n * its readiness stayed 503 for hours, and because liveness always passed\n * Kubernetes never restarted it.\n *\n * The watchdog probes each critical dependency in the background and\n * remembers since when it has been unhealthy. Liveness fails only once a\n * dependency has been unhealthy for longer than a bounded window (5 minutes by\n * default, plus up to 1 minute of per-process jitter), so kubelet restarts a\n * stuck process while a short outage never restarts anything. The jitter keeps\n * a fleet that lost the same datastore together from restarting in lockstep.\n *\n * The liveness handler only reads in-memory state, so the probe stays cheap\n * and never waits on the datastore itself.\n */\nimport { logger } from '../logger/index.js';\nimport type { ReadinessCache, ReadinessPrisma } from './readiness.js';\n\nexport interface DependencyProbe {\n /** Stable name reported in liveness output and logs. */\n name: string;\n /** Resolves true when healthy. `false`, a rejection or a timeout is unhealthy. */\n check: () => Promise<boolean> | boolean;\n}\n\nexport interface DependencyWatchdogConfig {\n /** When false, liveness never fails (the watchdog still records state). */\n enabled: boolean;\n /** How long a dependency may stay unhealthy before liveness fails. */\n unhealthyThresholdMs: number;\n /** Upper bound of the random per-process extension of the threshold. */\n jitterMs: number;\n /** Interval between background probe rounds. */\n intervalMs: number;\n /** Bound on a single probe; a slower probe counts as unhealthy. */\n checkTimeoutMs: number;\n}\n\nexport interface DependencyWatchdogOptions extends Partial<DependencyWatchdogConfig> {\n probes: DependencyProbe[];\n /** Clock; injectable for tests. */\n now?: () => number;\n /** Jitter source in [0, 1); injectable for tests. */\n random?: () => number;\n}\n\nexport interface FailingDependency {\n name: string;\n unhealthyForMs: number;\n}\n\nexport interface LivenessReport {\n alive: boolean;\n thresholdMs: number;\n failing: FailingDependency[];\n}\n\ninterface DependencyState {\n /** Start of the current unhealthy streak; null while healthy. */\n unhealthySince: number | null;\n lastError: string | null;\n}\n\nexport const DEFAULT_DEPENDENCY_WATCHDOG_CONFIG: DependencyWatchdogConfig = {\n enabled: true,\n unhealthyThresholdMs: 5 * 60_000,\n jitterMs: 60_000,\n intervalMs: 15_000,\n checkTimeoutMs: 5_000,\n};\n\n/**\n * The shortest threshold the env may configure. A smaller value would let a\n * routine datastore failover restart the whole fleet.\n */\nexport const MIN_UNHEALTHY_THRESHOLD_MS = 60_000;\n\nfunction readPositiveInt(raw: string | undefined, fallback: number): number {\n if (raw === undefined || raw.trim() === '') return fallback;\n const value = Number(raw);\n return Number.isInteger(value) && value > 0 ? value : fallback;\n}\n\n/**\n * Read the watchdog settings from the environment:\n * `DEPENDENCY_WATCHDOG_ENABLED` (default true), `DEPENDENCY_WATCHDOG_THRESHOLD_MS`\n * (default 300000, minimum 60000), `DEPENDENCY_WATCHDOG_JITTER_MS` (default\n * 60000), `DEPENDENCY_WATCHDOG_INTERVAL_MS` (default 15000) and\n * `DEPENDENCY_WATCHDOG_CHECK_TIMEOUT_MS` (default 5000). Invalid values fall\n * back to the defaults. `base` replaces the built-in defaults (a service's\n * `health.watchdog` settings); the env still wins, so operators can tune or\n * disable the watchdog without a release.\n */\nexport function resolveDependencyWatchdogConfig(\n env: Record<string, string | undefined> = process.env,\n base: Partial<DependencyWatchdogConfig> = {}\n): DependencyWatchdogConfig {\n const defaults = { ...DEFAULT_DEPENDENCY_WATCHDOG_CONFIG, ...base };\n return {\n enabled: defaults.enabled && (env['DEPENDENCY_WATCHDOG_ENABLED'] ?? '').trim().toLowerCase() !== 'false',\n unhealthyThresholdMs: Math.max(\n MIN_UNHEALTHY_THRESHOLD_MS,\n readPositiveInt(env['DEPENDENCY_WATCHDOG_THRESHOLD_MS'], defaults.unhealthyThresholdMs)\n ),\n jitterMs: readPositiveInt(env['DEPENDENCY_WATCHDOG_JITTER_MS'], defaults.jitterMs),\n intervalMs: readPositiveInt(env['DEPENDENCY_WATCHDOG_INTERVAL_MS'], defaults.intervalMs),\n checkTimeoutMs: readPositiveInt(env['DEPENDENCY_WATCHDOG_CHECK_TIMEOUT_MS'], defaults.checkTimeoutMs),\n };\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport class DependencyWatchdog {\n /** Effective threshold for this process: configured value plus jitter. */\n readonly thresholdMs: number;\n\n private readonly config: DependencyWatchdogConfig;\n private readonly probes: DependencyProbe[];\n private readonly now: () => number;\n private readonly states = new Map<string, DependencyState>();\n private timer?: ReturnType<typeof setInterval>;\n private round: Promise<void> | null = null;\n private expiredLogged = false;\n\n constructor(options: DependencyWatchdogOptions) {\n const { probes, now, random, ...overrides } = options;\n this.config = { ...DEFAULT_DEPENDENCY_WATCHDOG_CONFIG, ...overrides };\n this.probes = probes;\n this.now = now ?? Date.now;\n const jitter = Math.floor((random ?? Math.random)() * this.config.jitterMs);\n this.thresholdMs = this.config.unhealthyThresholdMs + jitter;\n\n // A dependency counts as unhealthy until its first successful probe, so a\n // process that never reaches its datastore after boot is caught too.\n const startedAt = this.now();\n for (const probe of probes) {\n this.states.set(probe.name, { unhealthySince: startedAt, lastError: 'not checked yet' });\n }\n }\n\n /** Start background probing (an immediate round, then every `intervalMs`). */\n start(): void {\n if (this.timer) return;\n void this.checkNow();\n const timer = setInterval(() => {\n void this.checkNow();\n }, this.config.intervalMs);\n timer.unref?.();\n this.timer = timer;\n }\n\n stop(): void {\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = undefined;\n }\n }\n\n /** Run one probe round; concurrent callers share the round in flight. */\n checkNow(): Promise<void> {\n if (!this.round) {\n this.round = this.runRound().finally(() => {\n this.round = null;\n });\n }\n return this.round;\n }\n\n /** Record a probe outcome observed elsewhere (for example by readiness). */\n record(name: string, healthy: boolean, error?: unknown): void {\n const state = this.states.get(name);\n if (!state) return;\n if (healthy) {\n if (state.unhealthySince !== null) {\n logger.info('[DependencyWatchdog] Dependency recovered', {\n dependency: name,\n unhealthyForMs: this.now() - state.unhealthySince,\n });\n }\n state.unhealthySince = null;\n state.lastError = null;\n return;\n }\n state.unhealthySince ??= this.now();\n state.lastError = error === undefined ? 'reported unhealthy' : errorMessage(error);\n }\n\n /** Liveness verdict from in-memory state only; never touches a dependency. */\n liveness(): LivenessReport {\n const now = this.now();\n const failing: FailingDependency[] = [];\n for (const [name, state] of this.states) {\n if (state.unhealthySince === null) continue;\n const unhealthyForMs = now - state.unhealthySince;\n if (unhealthyForMs > this.thresholdMs) failing.push({ name, unhealthyForMs });\n }\n const alive = !this.config.enabled || failing.length === 0;\n\n if (failing.length > 0 && !this.expiredLogged) {\n this.expiredLogged = true;\n logger.error('[DependencyWatchdog] Dependency unhealthy beyond the watchdog window', {\n enforced: this.config.enabled,\n thresholdMs: this.thresholdMs,\n failing: failing.map((f) => ({\n ...f,\n lastError: this.states.get(f.name)?.lastError ?? null,\n })),\n });\n } else if (failing.length === 0) {\n this.expiredLogged = false;\n }\n\n return { alive, thresholdMs: this.thresholdMs, failing };\n }\n\n private async runRound(): Promise<void> {\n await Promise.all(\n this.probes.map(async (probe) => {\n try {\n const healthy = await this.withTimeout(probe);\n this.record(probe.name, healthy === true);\n } catch (error) {\n this.record(probe.name, false, error);\n }\n })\n );\n }\n\n private async withTimeout(probe: DependencyProbe): Promise<boolean> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n reject(new Error(`probe timed out after ${String(this.config.checkTimeoutMs)}ms`));\n }, this.config.checkTimeoutMs);\n timer.unref?.();\n });\n try {\n return await Promise.race([Promise.resolve().then(() => probe.check()), timeout]);\n } finally {\n clearTimeout(timer);\n }\n }\n}\n\n/** Dependencies the liveness watchdog can watch. */\nexport type WatchdogDependencyName = 'postgres' | 'valkey' | 'pubsub' | 'consumers';\n\n/** `health.watchdog` settings. Every field except `dependencies` is optional. */\nexport interface ServerWatchdogConfig {\n /**\n * Dependencies whose prolonged failure restarts the pod. `consumers` and\n * `pubsub` count as healthy when the process has none registered.\n */\n dependencies: WatchdogDependencyName[];\n /** Additional service-specific probes. */\n probes?: DependencyProbe[];\n /** How long a dependency may stay unhealthy before liveness fails, in ms (minimum 60000). */\n unhealthyThresholdMs?: number;\n /** Upper bound of the random per-process extension of the threshold, in ms. */\n jitterMs?: number;\n /** Interval between background probe rounds, in ms. */\n intervalMs?: number;\n /** Bound on a single probe, in ms. */\n checkTimeoutMs?: number;\n}\n\n/** Where `createServer` reads each watched dependency's health from. */\nexport interface WatchdogSources {\n prisma: () => ReadinessPrisma | undefined;\n valkey: () => Promise<ReadinessCache | undefined> | ReadinessCache | undefined;\n /** Aggregate pubsub health; `undefined` when the process has no pubsub. */\n pubsub: () => { ok: boolean } | undefined;\n /** Aggregate consumer health; `undefined` when the process has no supervised consumer. */\n consumers: () => { ok: boolean } | undefined;\n}\n\n/** Probes for the dependencies a service listed in `health.watchdog`. */\nexport function buildWatchdogProbes(config: ServerWatchdogConfig, sources: WatchdogSources): DependencyProbe[] {\n const probes: DependencyProbe[] = [];\n for (const name of new Set(config.dependencies)) {\n switch (name) {\n case 'postgres':\n probes.push({\n name,\n check: async () => {\n const client = sources.prisma();\n if (!client) return false;\n await client.$queryRaw`SELECT 1`;\n return true;\n },\n });\n break;\n case 'valkey':\n probes.push({\n name,\n check: async () => {\n const client = await sources.valkey();\n if (!client) return false;\n await client.ping();\n return true;\n },\n });\n break;\n case 'pubsub':\n probes.push({ name, check: () => sources.pubsub()?.ok ?? true });\n break;\n case 'consumers':\n probes.push({ name, check: () => sources.consumers()?.ok ?? true });\n break;\n }\n }\n return [...probes, ...(config.probes ?? [])];\n}\n\n/**\n * Build the watchdog for `createServer`, or `undefined` when the service did\n * not opt in. The env (`DEPENDENCY_WATCHDOG_*`) overrides the service settings.\n */\nexport function createServerWatchdog(\n config: ServerWatchdogConfig | undefined,\n sources: WatchdogSources,\n env: Record<string, string | undefined> = process.env\n): DependencyWatchdog | undefined {\n if (!config) return undefined;\n const probes = buildWatchdogProbes(config, sources);\n if (probes.length === 0) return undefined;\n const base: Partial<DependencyWatchdogConfig> = {};\n if (config.unhealthyThresholdMs !== undefined) base.unhealthyThresholdMs = config.unhealthyThresholdMs;\n if (config.jitterMs !== undefined) base.jitterMs = config.jitterMs;\n if (config.intervalMs !== undefined) base.intervalMs = config.intervalMs;\n if (config.checkTimeoutMs !== undefined) base.checkTimeoutMs = config.checkTimeoutMs;\n return new DependencyWatchdog({ ...resolveDependencyWatchdogConfig(env, base), probes });\n}\n\n/**\n * `/health/live` answer: the static liveness body while the watchdog (if any)\n * reports alive, else 503 with the failing dependencies. Reads in-memory state\n * only.\n */\nexport function watchdogLivenessResponse<B extends { status: string }>(\n body: B,\n watchdog: Pick<DependencyWatchdog, 'liveness'> | undefined\n): {\n status: 200 | 503;\n body: B | (Omit<B, 'status'> & { status: 'unavailable'; watchdog: Omit<LivenessReport, 'alive'> });\n} {\n if (!watchdog) return { status: 200, body };\n const report = watchdog.liveness();\n if (report.alive) return { status: 200, body };\n return {\n status: 503,\n body: { ...body, status: 'unavailable', watchdog: { thresholdMs: report.thresholdMs, failing: report.failing } },\n };\n}\n","import { GraphQLError } from 'graphql';\n\nimport type { YogaPlugin } from './types.js';\n\nexport interface UserFacingErrorOptions {\n code: string;\n userMessage: string;\n technicalMessage?: string;\n details?: Record<string, unknown>;\n httpStatus?: number;\n cause?: Error;\n}\n\nexport interface ErrorNormalizationOptions {\n serviceName?: string;\n environment?: string;\n}\n\nexport interface NormalizedErrorState {\n code: string;\n userMessage: string;\n technicalMessage: string;\n extensions: Record<string, unknown>;\n status: number;\n}\n\nexport interface HttpErrorPayload {\n error: string;\n message: string;\n userMessage: string;\n technicalMessage: string;\n code: string;\n extensions: Record<string, unknown>;\n}\n\nexport interface HttpErrorResult {\n status: number;\n body: HttpErrorPayload;\n}\n\nconst DEFAULT_ERROR_CODE = 'INTERNAL_SERVER_ERROR';\nconst DEFAULT_HTTP_STATUS = 500;\n\n// Held in a separately-named const so the literal isn't assigned directly to\n// the `INVALID_PASSWORD` key — that pattern trips sonarjs/no-hardcoded-passwords\n// (a false positive: this is a user-facing message, not a credential).\nconst INVALID_CREDENTIALS_USER_MESSAGE = 'The password you entered is incorrect.';\n\nconst DEFAULT_USER_MESSAGES: Record<string, string> = {\n BAD_REQUEST: 'Please check the request and try again.',\n BAD_USER_INPUT: 'Please check the information and try again.',\n CAPTCHA_FAILED: 'The verification failed. Please try again.',\n CAPTCHA_REQUIRED: 'Please complete the verification to continue.',\n COMPLEXITY_TOO_HIGH: 'This request is too large to process. Please simplify it and try again.',\n CONFLICT: 'This change conflicts with existing data. Please refresh and try again.',\n FORBIDDEN: 'You do not have permission to do that.',\n INTERNAL_SERVER_ERROR: 'Something went wrong. Please try again.',\n INVALID_PASSWORD: INVALID_CREDENTIALS_USER_MESSAGE,\n NOT_FOUND: 'We could not find the requested item.',\n PERMISSION_DENIED: 'You do not have permission to do that.',\n QUOTA_EXCEEDED: \"You've reached your usage limit.\",\n QUOTA_EXHAUSTED: \"You've reached your usage limit.\",\n RATE_LIMITED: 'Too many requests. Please wait a moment and try again.',\n RESOURCE_CAP_EXCEEDED: \"You've reached your plan limit. Upgrade your plan to continue.\",\n STORAGE_QUOTA_EXCEEDED: \"You've reached your storage limit. Upgrade your plan to continue.\",\n TIMEOUT: 'The request took too long. Please try again.',\n UNAUTHENTICATED: 'Please sign in to continue.',\n VALIDATION_ERROR: 'Please check the information and try again.',\n WORKSPACE_REQUIRED: 'Please choose a workspace and try again.',\n};\n\nconst DEFAULT_STATUS_BY_CODE: Record<string, number> = {\n BAD_REQUEST: 400,\n BAD_USER_INPUT: 400,\n CAPTCHA_FAILED: 400,\n CAPTCHA_REQUIRED: 400,\n COMPLEXITY_TOO_HIGH: 400,\n CONFLICT: 409,\n FORBIDDEN: 403,\n INVALID_PASSWORD: 400,\n NOT_FOUND: 404,\n PERMISSION_DENIED: 403,\n QUOTA_EXCEEDED: 429,\n QUOTA_EXHAUSTED: 429,\n RATE_LIMITED: 429,\n RESOURCE_CAP_EXCEEDED: 429,\n STORAGE_QUOTA_EXCEEDED: 429,\n TIMEOUT: 504,\n UNAUTHENTICATED: 401,\n VALIDATION_ERROR: 400,\n WORKSPACE_REQUIRED: 403,\n};\n\nconst SENSITIVE_EXTENSION_KEYS = new Set(['exception', 'originalError', 'stack', 'stacktrace']);\n\nconst TECHNICAL_MESSAGE_PATTERNS = [\n /\\bprisma\\b/i,\n /\\bsql\\b/i,\n /\\bconstraint\\b/i,\n /\\bstack\\b/i,\n /\\bundefined\\b/i,\n /\\bnull\\b/i,\n /\\bECONN[A-Z_]*\\b/,\n /\\bETIMEDOUT\\b/,\n /\\bENOTFOUND\\b/,\n /\\bP\\d{4}\\b/,\n /Cannot (read|set|find|access)/i,\n /Build failed \\(exit \\d+\\)/i,\n /JSON\\.stringify/i,\n];\n\nconst GRAPHQL_VALIDATION_MESSAGE_PATTERNS = [\n /^Syntax Error:/i,\n /^Cannot query field\\b/i,\n /^Cannot return null for non-nullable field\\b/i,\n /^Unknown (argument|directive|type)\\b/i,\n /^Variable \"\\$[^\"]+\" got invalid value/i,\n /^Field \"[^\"]+\" of required type/i,\n /^Field \"[^\"]+\" must not have a selection/i,\n /^Field \"[^\"]+\" must have a selection/i,\n /^Fragment \"[^\"]+\" cannot be spread here/i,\n /^There can be only one/i,\n /Did you mean /i,\n];\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction readString(record: Record<string, unknown>, key: string): string | null {\n const value = record[key];\n return typeof value === 'string' && value.trim().length > 0 ? value : null;\n}\n\nfunction readExtensions(error: unknown): Record<string, unknown> {\n if (!isRecord(error)) return {};\n const extensions = error['extensions'];\n return isRecord(extensions) ? extensions : {};\n}\n\nfunction readOriginalError(error: unknown): Error | undefined {\n if (error instanceof GraphQLError && error.originalError instanceof Error) {\n return error.originalError;\n }\n return undefined;\n}\n\nfunction sanitizeExtensions(extensions: Record<string, unknown>): Record<string, unknown> {\n const sanitized: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(extensions)) {\n if (!SENSITIVE_EXTENSION_KEYS.has(key)) {\n sanitized[key] = value;\n }\n }\n return sanitized;\n}\n\nfunction normalizeCode(code: string | null): string {\n if (!code) return DEFAULT_ERROR_CODE;\n return code\n .trim()\n .replace(/[\\s-]+/g, '_')\n .toUpperCase();\n}\n\nfunction inferCodeFromMessage(message: string): string {\n const lower = message.toLowerCase();\n\n if (GRAPHQL_VALIDATION_MESSAGE_PATTERNS.some((pattern) => pattern.test(message))) {\n return 'BAD_USER_INPUT';\n }\n\n if (\n lower.includes('unauthenticated') ||\n lower.includes('not authenticated') ||\n lower.includes('authentication required') ||\n lower.includes('unauthorized') ||\n lower.includes('please sign in') ||\n lower.includes('sign in to')\n ) {\n return 'UNAUTHENTICATED';\n }\n\n if (lower.includes('workspace context') || lower.includes('switch to a workspace')) {\n return 'WORKSPACE_REQUIRED';\n }\n\n if (\n lower.includes('forbidden') ||\n lower.includes('access denied') ||\n lower.includes('permission denied') ||\n lower.includes('not authorized')\n ) {\n return 'FORBIDDEN';\n }\n\n if (lower.includes('not found') || lower.includes('disappeared')) {\n return 'NOT_FOUND';\n }\n\n if (lower.includes('already exists') || lower.includes('already taken') || lower.includes('conflict')) {\n return 'CONFLICT';\n }\n\n if (lower.includes('quota') || lower.includes('cap exceeded') || lower.includes('limit reached')) {\n return 'QUOTA_EXCEEDED';\n }\n\n if (lower.includes('timeout') || lower.includes('timed out')) {\n return 'TIMEOUT';\n }\n\n if (\n lower.includes('required') ||\n lower.includes('invalid') ||\n lower.includes('missing') ||\n lower.includes('unsupported')\n ) {\n return 'BAD_USER_INPUT';\n }\n\n return DEFAULT_ERROR_CODE;\n}\n\nfunction inferCode(error: unknown, extensions: Record<string, unknown>, originalError: Error | undefined): string {\n const extensionCode = typeof extensions['code'] === 'string' ? extensions['code'] : null;\n if (extensionCode) return normalizeCode(extensionCode);\n\n if (isRecord(originalError)) {\n const originalCode = readString(originalError, 'code');\n if (originalCode) return normalizeCode(originalCode);\n }\n\n if (isRecord(error)) {\n const directCode = readString(error, 'code');\n if (directCode) return normalizeCode(directCode);\n }\n\n const message = readErrorMessage(error);\n return inferCodeFromMessage(message);\n}\n\nfunction readErrorMessage(error: unknown): string {\n if (error instanceof Error && error.message.trim().length > 0) {\n return error.message;\n }\n if (isRecord(error)) {\n const message = readString(error, 'message');\n if (message) return message;\n }\n return DEFAULT_USER_MESSAGES[DEFAULT_ERROR_CODE] ?? 'Something went wrong. Please try again.';\n}\n\nfunction isLikelyTechnicalMessage(message: string): boolean {\n if (message.length > 220) return true;\n if (message.includes('\\n')) return true;\n if (message.includes('{') && message.includes('}')) return true;\n if (GRAPHQL_VALIDATION_MESSAGE_PATTERNS.some((pattern) => pattern.test(message))) return true;\n return TECHNICAL_MESSAGE_PATTERNS.some((pattern) => pattern.test(message));\n}\n\nfunction readExplicitUserMessage(extensions: Record<string, unknown>): string | null {\n return (\n readString(extensions, 'userMessage') ??\n readString(extensions, 'humanMessage') ??\n readString(extensions, 'displayMessage')\n );\n}\n\nfunction resolveUserMessage(code: string, message: string, extensions: Record<string, unknown>): string {\n const explicit = readExplicitUserMessage(extensions);\n if (explicit) return explicit;\n\n const fallback =\n DEFAULT_USER_MESSAGES[code] ??\n DEFAULT_USER_MESSAGES[DEFAULT_ERROR_CODE] ??\n 'Something went wrong. Please try again.';\n if (code === DEFAULT_ERROR_CODE) {\n return fallback;\n }\n\n if (!isLikelyTechnicalMessage(message)) {\n return message;\n }\n\n return fallback;\n}\n\nfunction resolveTechnicalMessage(\n code: string,\n message: string,\n extensions: Record<string, unknown>,\n options: ErrorNormalizationOptions\n): string {\n const explicit = readString(extensions, 'technicalMessage');\n if (explicit) return explicit;\n\n if (options.environment === 'production' && code === DEFAULT_ERROR_CODE) {\n return options.serviceName ? `${options.serviceName} returned ${DEFAULT_ERROR_CODE}` : DEFAULT_ERROR_CODE;\n }\n\n return message;\n}\n\nfunction isValidHttpStatus(status: unknown): status is number {\n return typeof status === 'number' && Number.isInteger(status) && status >= 200 && status <= 599;\n}\n\nfunction isValidErrorStatus(status: unknown): status is number {\n return isValidHttpStatus(status) && status >= 400;\n}\n\nfunction readHttpStatus(extensions: Record<string, unknown>, code: string): number {\n const http = extensions['http'];\n if (isRecord(http) && isValidHttpStatus(http['status'])) {\n return http['status'];\n }\n // Known platform codes keep their canonical status so services that attach a\n // default `statusCode` (often 500) to every error cannot downgrade them.\n const byCode = DEFAULT_STATUS_BY_CODE[code];\n if (byCode !== undefined) {\n return byCode;\n }\n // Domain codes (e.g. E_DATASINK_KEY_EXISTS) are not in the table; honour the\n // `extensions.statusCode` the service attached so 400/409 are not reported as 500.\n const statusCode = extensions['statusCode'];\n if (isValidErrorStatus(statusCode)) {\n return statusCode;\n }\n return DEFAULT_HTTP_STATUS;\n}\n\nexport function normalizeError(error: unknown, options: ErrorNormalizationOptions = {}): NormalizedErrorState {\n const originalError = readOriginalError(error);\n const originalExtensions = readExtensions(originalError);\n const directExtensions = readExtensions(error);\n const mergedExtensions = sanitizeExtensions({ ...originalExtensions, ...directExtensions });\n const message = readErrorMessage(error);\n const code = inferCode(error, mergedExtensions, originalError);\n const userMessage = resolveUserMessage(code, message, mergedExtensions);\n const technicalMessage = resolveTechnicalMessage(code, message, mergedExtensions, options);\n const status = readHttpStatus(mergedExtensions, code);\n\n const extensions: Record<string, unknown> = {\n ...mergedExtensions,\n code,\n userMessage,\n technicalMessage,\n };\n\n if (options.serviceName) {\n extensions['serviceName'] = options.serviceName;\n }\n\n const http = extensions['http'];\n extensions['http'] = { ...(isRecord(http) ? http : {}), status };\n\n return {\n code,\n userMessage,\n technicalMessage,\n extensions,\n status,\n };\n}\n\nexport class UserFacingGraphQLError extends GraphQLError {\n constructor(options: UserFacingErrorOptions) {\n const extensions: Record<string, unknown> = {\n code: normalizeCode(options.code),\n userMessage: options.userMessage,\n technicalMessage: options.technicalMessage ?? options.userMessage,\n };\n\n if (options.details) {\n extensions['details'] = options.details;\n }\n\n if (options.httpStatus) {\n extensions['http'] = { status: options.httpStatus };\n }\n\n super(options.userMessage, {\n originalError: options.cause,\n extensions,\n });\n this.name = 'UserFacingGraphQLError';\n }\n}\n\nexport function toUserFacingGraphQLError(error: unknown, options: ErrorNormalizationOptions = {}): GraphQLError {\n const normalized = normalizeError(error, options);\n\n if (error instanceof GraphQLError) {\n return new GraphQLError(normalized.userMessage, {\n nodes: error.nodes,\n source: error.source,\n positions: error.positions,\n path: error.path,\n originalError: error.originalError,\n extensions: normalized.extensions,\n });\n }\n\n return new GraphQLError(normalized.userMessage, {\n originalError: error instanceof Error ? error : undefined,\n extensions: normalized.extensions,\n });\n}\n\nexport function normalizeExecutionResultErrors(result: unknown, options: ErrorNormalizationOptions = {}): void {\n if (Array.isArray(result)) {\n result.forEach((entry) => normalizeExecutionResultErrors(entry, options));\n return;\n }\n\n if (!isRecord(result)) return;\n const errors = result['errors'];\n if (!Array.isArray(errors) || errors.length === 0) return;\n\n result['errors'] = errors.map((error) => toUserFacingGraphQLError(error, options));\n}\n\nexport function normalizeGraphQLResponsePayload(payload: unknown, options: ErrorNormalizationOptions = {}): unknown {\n normalizeExecutionResultErrors(payload, options);\n return payload;\n}\n\n// Yoga consumes extensions.http when serializing. Preserve the actual transport\n// status for custom domain codes before the final JSON normalization; otherwise\n// an accurate 4xx/5xx response acquires a contradictory default 500 in its body.\n// Known codes retain their established mapping, and uncategorized internal errors\n// never inherit a client-error status merely because they share a response.\nfunction restoreSerializedHttpStatuses(payload: unknown, responseStatus: number): void {\n if (Array.isArray(payload)) {\n payload.forEach((entry) => restoreSerializedHttpStatuses(entry, responseStatus));\n return;\n }\n if (!isRecord(payload) || !Array.isArray(payload['errors'])) return;\n\n for (const error of payload['errors']) {\n if (!isRecord(error)) continue;\n const extensions = readExtensions(error);\n const http = extensions['http'];\n if (isRecord(http) && isValidHttpStatus(http['status'])) continue;\n const code = inferCode(error, extensions, undefined);\n const status =\n DEFAULT_STATUS_BY_CODE[code] ??\n (code !== DEFAULT_ERROR_CODE && responseStatus >= 400 ? responseStatus : DEFAULT_HTTP_STATUS);\n error['extensions'] = { ...extensions, http: { ...(isRecord(http) ? http : {}), status } };\n }\n}\n\nexport async function normalizeGraphQLResponse(\n response: Response,\n options: ErrorNormalizationOptions = {}\n): Promise<Response> {\n const contentType = response.headers.get('content-type') ?? '';\n if (!contentType.toLowerCase().includes('json')) {\n return response;\n }\n\n const text = await response.text();\n if (!text) {\n return new Response(text, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n }\n\n let payload: unknown;\n try {\n payload = JSON.parse(text) as unknown;\n } catch {\n return new Response(text, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n }\n\n restoreSerializedHttpStatuses(payload, response.status);\n normalizeGraphQLResponsePayload(payload, options);\n\n return new Response(JSON.stringify(payload), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n}\n\nexport function createHumanReadableErrorPlugin(options: ErrorNormalizationOptions = {}): YogaPlugin {\n return {\n onExecute() {\n return {\n onExecuteDone({ result }: { result: unknown }) {\n normalizeExecutionResultErrors(result, options);\n },\n };\n },\n };\n}\n\nexport function formatHttpError(error: unknown, options: ErrorNormalizationOptions = {}): HttpErrorResult {\n const normalized = normalizeError(error, options);\n return {\n status: normalized.status,\n body: {\n error: normalized.userMessage,\n message: normalized.userMessage,\n userMessage: normalized.userMessage,\n technicalMessage: normalized.technicalMessage,\n code: normalized.code,\n extensions: normalized.extensions,\n },\n };\n}\n\nexport function createHttpErrorResponse(error: unknown, options: ErrorNormalizationOptions = {}): Response {\n const formatted = formatHttpError(error, options);\n return new Response(JSON.stringify(formatted.body), {\n status: formatted.status,\n headers: { 'Content-Type': 'application/json' },\n });\n}\n","/**\n * Server Module\n *\n * Main server bootstrapping with Elysia, GraphQL Yoga, and middleware.\n * Uses Bun runtime for high-performance GraphQL services.\n *\n * Provides a simple API for microservices to start a fully configured server.\n */\n\nimport { logger } from '../logger/index.js';\nimport { configureAuth, configureDefaultAuth, type FetchWorkspaceSecretFn } from './auth.js';\nimport { configureContext, buildContext } from './context.js';\nimport { createWorkspaceExecutionContextPlugin, runWithServerWorkspaceContext } from './workspace-execution-context.js';\nimport type {\n ServerDefinition,\n ServerInstance,\n ServerInfo,\n ElysiaApp,\n BunServerHandle,\n YogaPlugin,\n GraphQLContext,\n} from './types.js';\nimport { I18n } from '../i18n/index.js';\nimport { canAccessGraphExport, normalizeCorsOrigins, resolveAllowedCorsOrigin } from './security.js';\nimport { getMetricsRegistry } from '../instrumentation/metrics-collector.js';\nimport { getWorkspaceQuotaRegistry } from '../metrics/index.js';\nimport { createQuotaGaugeRefresher } from './quotaGaugeRefresh.js';\nimport { collectPromDefaultMetrics, type PromDefaultMetricsClient } from '../telemetry/bun-runtime-metrics.js';\nimport {\n DEFAULT_RAW_BODY_MAX_BYTES,\n PayloadTooLargeError,\n createRawBodyRouter,\n readBoundedRawBody,\n rememberRequestServer,\n resolveBodyLimitBytes,\n resolveMaxRequestBodySize,\n} from './raw-body-routes.js';\nimport {\n createReadinessProbe,\n livenessBody,\n readinessBody,\n readinessStatusCode,\n type ReadinessCache,\n type ReadinessDeps,\n} from './readiness.js';\nimport { getPubSubHealth } from '../graphql/pubsub-health.js';\nimport { withIncomingRequestSpan } from '../telemetry/incoming-request-span.js';\nimport { getConsumerHealth } from '../event-queue/consumer-health.js';\nimport { createServerWatchdog, watchdogLivenessResponse } from './dependency-watchdog.js';\nimport {\n createHttpErrorResponse,\n createHumanReadableErrorPlugin,\n formatHttpError,\n normalizeGraphQLResponse,\n} from './errors.js';\n\n// Store startup time for uptime calculation\nlet serverStartTime: Date | null = null;\n\n// Workspace quota gauges cost Prisma groupBy queries, so /metrics refreshes\n// them on a TTL rather than on every scrape. See ./quotaGaugeRefresh.ts.\nconst quotaGaugeRefresher = createQuotaGaugeRefresher({\n collect: () => getWorkspaceQuotaRegistry().collectAll(),\n});\n\n/**\n * Create and configure a server instance using Elysia + GraphQL Yoga\n */\nexport async function createServer(definition: ServerDefinition): Promise<ServerInstance> {\n const {\n config,\n prismaClient,\n schema,\n moduleGraph,\n restEndpoints,\n yogaPlugins,\n buildContext: customBuildContext,\n workspaceExtensionConfig,\n disableWorkspaceExtension,\n onShutdown,\n } = definition;\n\n // Dynamic imports to avoid requiring these as hard dependencies\n const { Elysia } = await import('elysia');\n const { BunAdapter } = await import('elysia/adapter/bun');\n const { cors } = await import('@elysiajs/cors');\n const { createYoga } = await import('graphql-yoga');\n const { initializeDatabase, getDb, getDatabaseManager } = await import('../prisma/index.js');\n const { createSecurityPlugin } = await import('../middleware/index.js');\n const { createMetricsPlugin } = await import('../observability/index.js');\n const { createWorkspaceGuardPlugin } = await import('./workspace-guard.js');\n\n logger.info(`[Server] Initializing ${config.serviceName}...`);\n\n // Detect boundary from config or service name — needed before database and guard setup\n const boundary =\n config.boundary ??\n (config.serviceName.startsWith('wspace-')\n ? 'wspace'\n : config.serviceName.startsWith('global-')\n ? 'global'\n : 'wspace'); // fail-closed: default to wspace (stricter)\n\n // Initialize database\n // Workspace extension is auto-disabled for global boundary services unless explicitly enabled\n const shouldEnableWorkspaceExtension =\n disableWorkspaceExtension === true ? false : disableWorkspaceExtension === false ? true : boundary === 'wspace'; // auto-detect: enabled for wspace, disabled for global\n\n logger.info('[Server] Initializing database...', {\n boundary,\n workspaceExtension: shouldEnableWorkspaceExtension,\n });\n\n const { connect } = initializeDatabase(prismaClient, config.serviceName, {\n registerShutdownHandlers: false, // Server manages shutdown handlers itself\n enableWorkspaceExtension: shouldEnableWorkspaceExtension,\n ...(workspaceExtensionConfig ? { workspaceExtensionConfig } : {}),\n });\n await connect();\n\n // Initialize i18n if configured\n let i18nInstance: I18n | undefined;\n if (config.i18n?.enabled && config.i18n.localesPath) {\n logger.info('[Server] Initializing i18n...');\n i18nInstance = new I18n({\n defaultLocale: config.i18n.defaultLocale || 'en-US',\n fallbackLocale: config.i18n.fallbackLocale || 'en-US',\n localesPath: config.i18n.localesPath,\n supportedLocales: config.i18n.supportedLocales,\n namespace: config.i18n.namespace || config.serviceName,\n lazyLoad: config.i18n.lazyLoad,\n logMissing: config.i18n.logMissing ?? true,\n enableCache: true,\n returnKeyOnMissing: true,\n });\n await i18nInstance.initialize();\n logger.info(`[Server] i18n initialized with locales: ${i18nInstance.getSupportedLocales().join(', ')}`);\n }\n\n // Configure context builder\n configureContext({\n getDb: () => getDb(),\n i18n: i18nInstance,\n });\n\n // Auto-configure auth with default workspace secret fetcher if not already configured\n configureDefaultAuth();\n\n // Initialize module graph if provided\n if (moduleGraph) {\n logger.info('[Server] Initializing module graph...');\n await moduleGraph.initialize();\n }\n\n // Determine if playground/introspection should be enabled\n const isDev = config.environment !== 'production';\n const enablePlayground = config.enablePlayground ?? isDev;\n\n // Enable GraphQL-over-HTTP batching by default so subgraphs accept the batched\n // array POSTs the federation gateway forwards from Apollo Client BatchHttpLink.\n // The default limit (10) matches the workspace gateway's batching limit.\n const batching = config.batching ?? true;\n\n // Build workspace guard plugin — auto-enabled for wspace boundary only\n const workspaceGuardEnabled = config.workspaceGuard?.enabled ?? boundary === 'wspace';\n logger.info(`[Server] Boundary: ${boundary}, workspace guard: ${workspaceGuardEnabled ? 'enabled' : 'disabled'}`);\n\n const workspaceGuardPlugins = workspaceGuardEnabled\n ? [\n createWorkspaceGuardPlugin({\n enabled: true,\n whitelistedOperations: config.workspaceGuard?.whitelistedOperations,\n whitelistedFields: config.workspaceGuard?.whitelistedFields,\n validateWorkspaceMembership: config.workspaceGuard?.validateWorkspaceMembership,\n }),\n ]\n : [];\n\n // Create GraphQL Yoga instance\n const graphqlEndpoint = config.graphqlEndpoint || '/graphql';\n logger.info('[Server] Setting up GraphQL Yoga with provided schema...', {\n batching,\n });\n\n const responseHeadersPlugin: YogaPlugin = {\n onResponse: ({ response, serverContext }: { response: Response; serverContext: unknown }) => {\n const yogaContext = serverContext as GraphQLContext;\n if (yogaContext?.responseHeaders) {\n yogaContext.responseHeaders.forEach((value: string, key: string) => {\n response.headers.append(key, value);\n });\n }\n },\n };\n\n const yoga = createYoga<{ request: Request }>({\n graphqlEndpoint,\n schema, // Use the schema provided by microservice\n graphiql: enablePlayground,\n batching,\n logging: {\n debug: (...args) => logger.debug('[GraphQL]', ...args),\n info: (...args) => logger.info('[GraphQL]', ...args),\n warn: (...args) => logger.warn('[GraphQL]', ...args),\n error: (...args) => logger.error('[GraphQL]', ...args),\n },\n plugins: [\n createHumanReadableErrorPlugin({ serviceName: config.serviceName, environment: config.environment }),\n ...workspaceGuardPlugins,\n responseHeadersPlugin,\n ...(yogaPlugins || []),\n // Consumers such as GraphQL Modules replace execute/subscribe; bind their final functions.\n createWorkspaceExecutionContextPlugin(),\n ],\n context: async ({ request }) => {\n // Build default context\n const defaultContext = await buildContext(request);\n\n // Apply custom context builder if provided\n if (customBuildContext) {\n return customBuildContext(defaultContext);\n }\n\n return defaultContext;\n },\n });\n\n // Create Elysia instance with Bun adapter\n const app = new Elysia({ adapter: BunAdapter });\n\n // Register CORS middleware\n const corsOrigins = normalizeCorsOrigins(config.corsOrigins, config.environment);\n\n app.use(\n cors({\n origin: corsOrigins,\n credentials: corsOrigins.length > 0,\n allowedHeaders: [\n 'Content-Type',\n 'Authorization',\n 'X-Tenant-ID',\n 'X-Workspace-ID',\n 'X-Org-ID',\n 'X-Project-ID',\n 'X-Product-ID',\n 'X-CSRF-Token',\n 'X-Service-Name',\n 'Accept-Language',\n 'X-Locale',\n 'X-Language',\n 'X-Geo-Country',\n 'X-Geo-Currency',\n 'X-Geo-Timezone',\n // Actor headers (gateway-injected or dev mode)\n 'X-Actor-ID',\n 'X-Actor-Type',\n 'X-Internal-Service-Token',\n 'X-Gateway-Auth-Token',\n ],\n methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],\n })\n );\n\n // Raw-body endpoints (webhooks) are served in onRequest, before Elysia parses the body, so they\n // get their own router — keyed on path AND method (BOFF-7766).\n const rawBodyRouter = createRawBodyRouter(restEndpoints || [], () => app.routes);\n const defaultRawBodyMaxBytes = resolveBodyLimitBytes(config.maxBodyBytes, DEFAULT_RAW_BODY_MAX_BYTES);\n const maxRequestBodySize = resolveMaxRequestBodySize(config, restEndpoints || []);\n\n // Handle GraphQL, metrics, and raw body requests BEFORE any middleware that consumes the body\n // This is critical because Yoga needs the raw request body stream\n // and webhook endpoints need raw body for signature verification\n // onRequest runs before onParse (body parsing) and onBeforeHandle\n app.onRequest(async ({ request, server }) => {\n const url = new URL(request.url);\n const pathname = url.pathname;\n logger.debug(`[Server] onRequest: ${request.method} ${pathname}`);\n const isHealthRoute = pathname === '/health' || pathname.startsWith('/health/');\n\n // Build CORS headers helper\n const buildCorsHeaders = (): Record<string, string> => {\n const origin = request.headers.get('origin') || '*';\n const allowedOrigin = resolveAllowedCorsOrigin(origin === '*' ? null : origin, corsOrigins);\n const headers: Record<string, string> = {\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers':\n 'Content-Type, Authorization, X-Tenant-ID, X-Workspace-ID, X-Org-ID, X-Project-ID, X-Product-ID, X-CSRF-Token, X-Service-Name, Accept-Language, X-Locale, X-Language, X-Geo-Country, X-Geo-Currency, X-Geo-Timezone, X-Actor-ID, X-Actor-Type, X-Internal-Service-Token, X-Gateway-Auth-Token',\n };\n\n if (allowedOrigin) {\n headers['Access-Control-Allow-Origin'] = allowedOrigin;\n headers['Access-Control-Allow-Credentials'] = 'true';\n }\n\n return headers;\n };\n\n // Raw-body endpoints (webhooks). One path may serve several verbs, each its own handler.\n if (!isHealthRoute && rawBodyRouter.size > 0 && rawBodyRouter.hasPath(pathname)) {\n const corsHeaders = buildCorsHeaders();\n\n // Handle CORS preflight for raw body endpoints\n if (request.method === 'OPTIONS') {\n return new Response(null, {\n status: 204,\n headers: corsHeaders,\n });\n }\n\n const resolution = rawBodyRouter.resolve(pathname, request.method);\n // An ordinary route serves this method on the same path: let Elysia handle it.\n if (!resolution) return undefined;\n\n if (resolution.kind === 'method-not-allowed') {\n return new Response(\n JSON.stringify({ error: `Method ${request.method} is not allowed`, allowed: resolution.allowed }),\n {\n status: 405,\n headers: { 'Content-Type': 'application/json', Allow: resolution.allowed.join(', '), ...corsHeaders },\n }\n );\n }\n\n const rawBodyEndpoint = resolution.endpoint;\n logger.debug(`[Server] Matched raw body endpoint: ${request.method} ${pathname} -> ${rawBodyEndpoint.path}`);\n // Lets the handler extend this request's idle timeout (extendRequestIdleTimeout).\n rememberRequestServer(request, server);\n const isHead = request.method === 'HEAD';\n\n try {\n // Read raw body BEFORE any parsing, bounded to prevent pre-auth memory exhaustion (BOFF-16046)\n const endpointMaxBodyBytes = resolveBodyLimitBytes(rawBodyEndpoint.maxBodyBytes, defaultRawBodyMaxBytes);\n const rawBody = await readBoundedRawBody(request, endpointMaxBodyBytes);\n\n // Build context without consuming body (body already read)\n const context = await buildContext(request);\n\n // Call the handler with raw body\n const result = await runWithServerWorkspaceContext(context, async () =>\n rawBodyEndpoint.handler(request, context, rawBody)\n );\n\n // If handler returns a Response, use it directly\n if (result instanceof Response) {\n // Add CORS headers\n const headers = new Headers(result.headers);\n for (const [key, value] of Object.entries(corsHeaders)) {\n headers.set(key, value);\n }\n // A HEAD served by the GET handler carries its headers, never its body.\n return new Response(isHead ? null : result.body, {\n status: result.status,\n statusText: result.statusText,\n headers,\n });\n }\n\n // Otherwise, serialize as JSON\n const headers = new Headers({\n 'Content-Type': 'application/json',\n ...corsHeaders,\n });\n\n return new Response(isHead ? null : JSON.stringify(result), {\n status: 200,\n headers,\n });\n } catch (error) {\n if (error instanceof PayloadTooLargeError) {\n logger.warn(`[Server] Raw body endpoint payload too large (${pathname})`, {\n maxBodyBytes: error.maxBodyBytes,\n });\n return new Response(\n isHead\n ? null\n : JSON.stringify({\n error: 'Payload too large',\n code: error.code,\n maxBodyBytes: error.maxBodyBytes,\n }),\n {\n status: 413,\n headers: {\n 'Content-Type': 'application/json',\n ...corsHeaders,\n },\n }\n );\n }\n logger.error(`[Server] Raw body endpoint error (${pathname}):`, error);\n const formatted = formatHttpError(error, {\n serviceName: config.serviceName,\n environment: config.environment,\n });\n return new Response(isHead ? null : JSON.stringify(formatted.body), {\n status: formatted.status,\n headers: {\n 'Content-Type': 'application/json',\n ...corsHeaders,\n },\n });\n }\n }\n\n // Serve Prometheus metrics via prom-client at /metrics.\n // The graphql-yoga prometheus plugin populates the same default registry,\n // so GraphQL-level metrics (operation durations, error counts, etc.) are\n // included automatically without needing Yoga to handle this route.\n //\n // Also includes SDK MetricsRegistry metrics (business counters/histograms\n // created via @burdenoff/be-sdk/instrumentation factories) so that custom\n // service metrics are available without a separate /api/metrics endpoint.\n if (pathname === '/metrics' && request.method === 'GET') {\n try {\n const promClientMod = 'prom-client';\n const prom = (await import(promClientMod)) as unknown as PromDefaultMetricsClient & {\n register: { metrics: () => Promise<string> | string; contentType?: string };\n };\n // Under Bun this leaves out the heap-space gauges, whose collect walks the heap (BOFF-12287).\n collectPromDefaultMetrics(prom);\n const promBody = await prom.register.metrics();\n\n // Append SDK MetricsRegistry metrics (business counters, histograms,\n // gauges) that are created via @burdenoff/be-sdk/instrumentation\n // factories. The toPrometheusFormat() method is deliberately not cached\n // — each scrape gets a fresh snapshot including dynamic label values.\n //\n // Workspace quota gauges are different: collectAll() issues Prisma\n // groupBy queries, so running it inline on every scrape made /metrics\n // as slow as the database. Services registering quota collectors\n // routinely blew a 30s Prometheus scrape_timeout and reported as down.\n // Refresh on a TTL and bound each refresh, so a slow or unavailable\n // database degrades gauge freshness instead of failing the scrape.\n let sdkBody = '';\n await quotaGaugeRefresher.refresh();\n try {\n sdkBody = getMetricsRegistry().toPrometheusFormat();\n } catch {\n /* MetricsRegistry not initialised; serve prom-client output alone */\n }\n\n const combined = sdkBody ? `${promBody}\\n${sdkBody}` : promBody;\n return new Response(combined, {\n status: 200,\n headers: {\n 'Content-Type': prom.register.contentType ?? 'text/plain; version=0.0.4; charset=utf-8',\n },\n });\n } catch {\n // fall through — prom-client not installed; let Yoga handle as fallback\n }\n }\n\n // Routes that should be handled by Yoga (GraphQL endpoint only)\n const yogaRoutes = [graphqlEndpoint, `${graphqlEndpoint}/`, '/metrics'];\n const shouldHandleByYoga = yogaRoutes.includes(pathname);\n\n if (shouldHandleByYoga) {\n const corsHeaders = buildCorsHeaders();\n\n // Handle CORS preflight\n if (request.method === 'OPTIONS') {\n return new Response(null, {\n status: 204,\n headers: corsHeaders,\n });\n }\n\n // Get response from Yoga inside a SERVER span that continues the\n // gateway's trace (BOFF-17552): Bun.serve requests are not seen by\n // OpenTelemetry's http instrumentation, so without this no span was\n // created and `traceparent` was never extracted.\n const yogaResponse = await withIncomingRequestSpan(request, graphqlEndpoint, async () =>\n normalizeGraphQLResponse(await yoga.fetch(request), {\n serviceName: config.serviceName,\n environment: config.environment,\n })\n );\n\n // Add CORS headers to Yoga response\n const headers = new Headers(yogaResponse.headers);\n for (const [key, value] of Object.entries(corsHeaders)) {\n headers.set(key, value);\n }\n\n // Return response with CORS headers\n return new Response(yogaResponse.body, {\n status: yogaResponse.status,\n statusText: yogaResponse.statusText,\n headers,\n });\n }\n // Return undefined to continue to next handlers for non-GraphQL requests\n return undefined;\n });\n\n // Register metrics middleware (after GraphQL interception)\n app.use(createMetricsPlugin());\n\n // Register security middleware (after GraphQL interception)\n app.use(\n createSecurityPlugin({\n csrfSkipRoutes: config.csrfSkipRoutes || ['/graphql', '/health', '/api/graph/'],\n loginEndpoints: config.loginEndpoints || [],\n enableCSRF: config.enableCSRF ?? false, // Disabled by default for GraphQL services\n enableSessionSecurity: config.enableSessionSecurity ?? false,\n })\n );\n\n // Health check endpoints. Rationale for the required/optional split and for\n // keeping liveness shallow lives in ./readiness.ts — read it before changing\n // which dependency is required.\n //\n // /health aggregate: 200 healthy / 200 degraded / 503 unavailable\n // /health/live Kubernetes liveness — process only, never a dependency\n // /health/ready Kubernetes readiness — 503 when a REQUIRED dep is down\n // /health/startup Kubernetes startup — process only, same as liveness\n const serviceVersion = config.serviceVersion || '1.0.0';\n const valkeySource = async (): Promise<ReadinessCache | undefined> => {\n // Optional: services that never configured Valkey must not be marked\n // degraded for not having one, so an unconfigured client is not an error.\n try {\n const { getValkeyClient } = await import('../cache/index.js');\n return await getValkeyClient();\n } catch {\n return undefined;\n }\n };\n const getReadiness = createReadinessProbe({\n prisma: () => getDb(),\n valkey: valkeySource,\n // Reported only when the service created a Redis Streams pubsub.\n pubsub: () => getPubSubHealth(),\n // Reported only when the service started a supervised consumer (BOFF-17231).\n consumers: () => getConsumerHealth(),\n ...(config.health?.requiredDependencies ? { requiredDependencies: config.health.requiredDependencies } : {}),\n } satisfies ReadinessDeps);\n\n // Opt-in liveness watchdog (BOFF-17231): restarts a pod whose listed\n // dependency stayed unhealthy past a bounded window. The handler reads the\n // watchdog's in-memory state only, so liveness never waits on a datastore.\n const watchdog = createServerWatchdog(config.health?.watchdog, {\n prisma: () => getDb(),\n valkey: valkeySource,\n pubsub: () => getPubSubHealth(),\n consumers: () => getConsumerHealth(),\n });\n\n const shallow = (): unknown => livenessBody(config.serviceName, serviceVersion, new Date().toISOString());\n\n const live = (ctx: unknown): unknown => {\n const { status, body } = watchdogLivenessResponse(\n livenessBody(config.serviceName, serviceVersion, new Date().toISOString()),\n watchdog\n );\n const ctxWithSet = ctx as { set?: { status?: number } };\n if (ctxWithSet.set) ctxWithSet.set.status = status;\n return body;\n };\n\n const deep = async (ctx: unknown): Promise<unknown> => {\n const snapshot = await getReadiness();\n const ctxWithSet = ctx as { set?: { status?: number } };\n const code = readinessStatusCode(snapshot);\n if (ctxWithSet.set) ctxWithSet.set.status = code;\n return readinessBody(\n snapshot,\n config.serviceName,\n serviceVersion,\n new Date().toISOString(),\n Math.round(process.uptime())\n );\n };\n\n app.get('/health', deep);\n app.get('/health/live', live);\n app.get('/health/ready', deep);\n app.get('/health/startup', shallow);\n\n // Graph API endpoints (if moduleGraph provided)\n if (moduleGraph) {\n // Get graph configuration schema\n app.get('/api/graph/schema', async ({ request, set }) => {\n const context = await buildContext(request);\n if (!canAccessGraphExport(context.actor)) {\n set.status = 403;\n return { error: 'Forbidden' };\n }\n\n return moduleGraph.getSchema();\n });\n\n // Export all graph data\n app.get('/api/graph/export', async ({ query, request, set }) => {\n const context = await buildContext(request);\n if (!canAccessGraphExport(context.actor)) {\n set.status = 403;\n return { error: 'Forbidden' };\n }\n\n const { organizationId, workspaceId } = query as { organizationId?: string; workspaceId?: string };\n return runWithServerWorkspaceContext(context, () => moduleGraph.exportAll(organizationId, workspaceId));\n });\n\n // Export entities only\n app.get('/api/graph/entities', async ({ query, request, set }) => {\n const context = await buildContext(request);\n if (!canAccessGraphExport(context.actor)) {\n set.status = 403;\n return { error: 'Forbidden' };\n }\n\n const { organizationId, workspaceId, types } = query as {\n organizationId?: string;\n workspaceId?: string;\n types?: string;\n };\n const entityTypes = types?.split(',').map((t) => t.trim());\n return runWithServerWorkspaceContext(context, () =>\n moduleGraph.exportEntities(organizationId, workspaceId, entityTypes)\n );\n });\n\n // Export relationships only\n app.get('/api/graph/relationships', async ({ query, request, set }) => {\n const context = await buildContext(request);\n if (!canAccessGraphExport(context.actor)) {\n set.status = 403;\n return { error: 'Forbidden' };\n }\n\n const { organizationId, workspaceId } = query as { organizationId?: string; workspaceId?: string };\n return runWithServerWorkspaceContext(context, () => moduleGraph.exportRelationships(organizationId, workspaceId));\n });\n }\n\n // Register custom REST endpoints (skip rawBody endpoints - they're handled in onRequest)\n if (restEndpoints && restEndpoints.length > 0) {\n for (const endpoint of restEndpoints) {\n // Skip rawBody endpoints - they're intercepted in onRequest before body parsing\n if (endpoint.rawBody) {\n logger.info(`[Server] Raw body endpoint registered: ${endpoint.method} ${endpoint.path}`);\n continue;\n }\n\n const handler = async ({ request }: { request: Request }): Promise<unknown> => {\n try {\n const context = await buildContext(request);\n return await runWithServerWorkspaceContext(context, async () => endpoint.handler(request, context));\n } catch (error) {\n logger.error(`[Server] REST endpoint error (${endpoint.path}):`, error);\n return createHttpErrorResponse(error, {\n serviceName: config.serviceName,\n environment: config.environment,\n });\n }\n };\n\n switch (endpoint.method) {\n case 'GET':\n app.get(endpoint.path, handler);\n break;\n case 'POST':\n app.post(endpoint.path, handler);\n break;\n case 'PUT':\n app.put(endpoint.path, handler);\n break;\n case 'PATCH':\n app.patch(endpoint.path, handler);\n break;\n case 'DELETE':\n app.delete(endpoint.path, handler);\n break;\n }\n }\n }\n\n const host = config.host || '0.0.0.0';\n const port = config.port;\n\n // Create server instance\n const serverInstance: ServerInstance = {\n app: app as unknown as ElysiaApp,\n server: null,\n start: async () => {\n serverStartTime = new Date();\n watchdog?.start();\n\n // Call listen() which starts the server and makes app.server available\n app.listen({\n port,\n hostname: host,\n maxRequestBodySize,\n });\n\n // Access the Bun server instance from the app\n // Cast through unknown to satisfy TypeScript since Elysia's types are complex\n const elysiaApp = app as unknown as { server: BunServerHandle | null };\n serverInstance.server = elysiaApp.server;\n\n logger.info(`🚀 ${config.serviceName} is running at http://${host}:${port}${graphqlEndpoint}`);\n },\n stop: async () => {\n logger.info(`[Server] Stopping ${config.serviceName}...`);\n watchdog?.stop();\n\n if (onShutdown) {\n await onShutdown();\n }\n\n if (moduleGraph) {\n await moduleGraph.shutdown();\n }\n\n await getDatabaseManager().disconnect();\n\n if (serverInstance.server) {\n serverInstance.server.stop();\n }\n\n logger.info(`[Server] ${config.serviceName} stopped`);\n },\n getInfo: (): ServerInfo => {\n const uptime = serverStartTime ? Math.floor((Date.now() - serverStartTime.getTime()) / 1000) : 0;\n\n return {\n serviceName: config.serviceName,\n serviceVersion: config.serviceVersion || '1.0.0',\n environment: config.environment || 'development',\n port,\n host,\n graphqlEndpoint,\n startedAt: serverStartTime?.toISOString() || '',\n uptime,\n };\n },\n };\n\n // Setup graceful shutdown handlers\n const gracefulShutdown = async (signal: string): Promise<never> => {\n logger.info(`[Server] ${signal} received, shutting down gracefully...`);\n await serverInstance.stop();\n process.exit(0);\n };\n\n process.on('SIGTERM', () => {\n void gracefulShutdown('SIGTERM');\n });\n process.on('SIGINT', () => {\n void gracefulShutdown('SIGINT');\n });\n\n return serverInstance;\n}\n\n/**\n * Configure auth with workspace secret fetcher\n *\n * This should be called before creating the server if using workspace-scoped JWT\n */\nexport function configureServerAuth(fetchWorkspaceSecret: FetchWorkspaceSecretFn): void {\n configureAuth({ fetchWorkspaceSecret });\n}\n","/**\n * Workspace Guard Plugin for GraphQL Yoga\n *\n * Blocks GraphQL operations that lack a valid workspace context (x-workspace-id header).\n * This provides defense-in-depth at the GraphQL layer — even if the gateway allows a request\n * through, the service itself will reject it if workspace context is missing.\n *\n * **Whitelisted operations** (e.g., workspace creation) can bypass the guard.\n *\n * **Public schema fields** marked with `@public` or `@rbac(public: true)` are auto-bypassed\n * when `allowPublicDirective` is enabled (default true). This lets anonymous public-link\n * resolvers (e.g. `accessShare`) be reached through the federation gateway without an\n * `x-workspace-id` header.\n *\n * @module server/workspace-guard\n * @category Security\n */\n\nimport { logger } from '../logger/index.js';\nimport { UserFacingGraphQLError } from './errors.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Configuration for the workspace guard plugin\n */\nexport interface WorkspaceGuardConfig {\n /**\n * Enable the workspace guard.\n * @default true\n */\n enabled?: boolean;\n\n /**\n * GraphQL operation names that can run without workspace context.\n * These are typically operations like `createWorkspace` that execute\n * before a workspace exists.\n *\n * Matching is case-sensitive against the operation name in the GraphQL document.\n *\n * @deprecated Prefer `whitelistedFields`: operation names are client-supplied\n * strings, so any client that names its operation differently (or sends an\n * anonymous operation) is rejected even when every root field it requests is\n * genuinely context-free. `whitelistedFields` matches on the root field names\n * resolved from the parsed document, which is a property of the schema, not\n * of the client's request.\n *\n * @default []\n *\n * @example\n * ```typescript\n * whitelistedOperations: ['createWorkspace', 'validateTokens']\n * ```\n */\n whitelistedOperations?: string[];\n\n /**\n * Root field names (Query/Mutation/Subscription fields) that can run without\n * workspace context — e.g. `myWorkspaces`, which bootstraps workspace\n * discovery before any workspace has been chosen.\n *\n * Matching is done against the root field names resolved from the parsed\n * GraphQL document for the executed operation, completely independent of the\n * client-supplied `operationName`: anonymous operations, persisted queries\n * and arbitrarily named operations all behave identically.\n *\n * An operation is exempt only when EVERY root field it selects is listed\n * here (or is public per the schema directives). A document that mixes an\n * exempt field with a guarded field is NOT exempt. Fragment spreads at the\n * root fail closed (not exempt).\n *\n * @default []\n *\n * @example\n * ```typescript\n * whitelistedFields: ['myWorkspaces', 'createWorkspace']\n * ```\n */\n whitelistedFields?: string[];\n\n /**\n * Optional membership validation for requests that DO carry a workspace\n * context (`x-workspace-id`). Without this, the guard only checks that a\n * workspace id is present — any well-formed UUID passes, which looks like\n * authorization but performs none.\n *\n * When provided, the callback is invoked with the resolved actor and\n * workspace id for every guarded request; returning `false` rejects the\n * request with `NOT_FOUND` (per the platform RBAC guide: never leak resource\n * existence to non-members). Returning `true` (or omitting this callback)\n * preserves the legacy accept-any-present-workspace-id behaviour.\n *\n * The callback is NOT invoked for operations exempted via\n * `whitelistedOperations`, `whitelistedFields` or the public-directive\n * bypass — context-free bootstrap fields stay reachable regardless.\n *\n * The service that owns the `Workspace`/`WorkspaceMember` entities wires\n * this; the SDK never derives membership itself.\n *\n * @default undefined\n */\n validateWorkspaceMembership?: (validation: WorkspaceMembershipValidation) => boolean | Promise<boolean>;\n\n /**\n * Custom error message when workspace context is missing.\n * @default 'Workspace context required. Provide a valid X-Workspace-Authorization header.'\n */\n errorMessage?: string;\n\n /**\n * If true, fields whose schema definition carries the `@public` directive or\n * `@rbac(public: true)` are bypassed by the guard automatically — no need to\n * list them in `whitelistedOperations`. The check uses the GraphQL schema\n * passed to the executor at request time.\n *\n * Set to false to fall back to the legacy operation-name allowlist only.\n *\n * @default true\n */\n allowPublicDirective?: boolean;\n}\n\n/**\n * Input for the `validateWorkspaceMembership` callback.\n */\nexport interface WorkspaceMembershipValidation {\n /** Actor id from the gateway-injected identity (`x-actor-id`). */\n actorId: string | null;\n /** Actor type from the gateway-injected identity (`x-actor-type`). */\n actorType: string | null;\n /** The workspace id claimed by `x-workspace-id` (or the actor's workspace). */\n workspaceId: string;\n /** The full GraphQL context value for the request. */\n contextValue: unknown;\n}\n\n// ============================================================================\n// GraphQL Error\n// ============================================================================\n\n/**\n * Workspace required error with proper GraphQL error extensions\n */\nclass WorkspaceRequiredError extends UserFacingGraphQLError {\n constructor(message: string) {\n super({\n code: 'WORKSPACE_REQUIRED',\n userMessage: 'Please choose a workspace and try again.',\n technicalMessage: message,\n httpStatus: 403,\n });\n this.name = 'WorkspaceRequiredError';\n }\n}\n\n/**\n * Rejection for a workspace id the calling actor is not a member of.\n * Per the platform RBAC guide (Type B convention), non-members get\n * NOT_FOUND so resource existence is never leaked.\n */\nclass WorkspaceMembershipError extends UserFacingGraphQLError {\n constructor(workspaceId: string) {\n super({\n code: 'NOT_FOUND',\n userMessage: 'We could not find the requested item.',\n technicalMessage: `Workspace ${workspaceId} was not found for the current actor.`,\n httpStatus: 404,\n });\n this.name = 'WorkspaceMembershipError';\n }\n}\n\n// ============================================================================\n// Schema directive helpers\n// ============================================================================\n\n/**\n * Minimal structural typings for the bits of the GraphQL schema we look at.\n * We avoid importing the GraphQL types directly so the SDK keeps `graphql`\n * as a peer dep without a runtime hard dependency.\n */\ninterface FieldLikeDef {\n astNode?: {\n directives?: ReadonlyArray<{\n name: { value: string };\n arguments?: ReadonlyArray<{\n name: { value: string };\n value: { kind: string; value?: unknown };\n }>;\n }>;\n };\n}\n\ninterface SchemaLike {\n getQueryType?: () => { getFields: () => Record<string, FieldLikeDef> } | null | undefined;\n getMutationType?: () => { getFields: () => Record<string, FieldLikeDef> } | null | undefined;\n getSubscriptionType?: () => { getFields: () => Record<string, FieldLikeDef> } | null | undefined;\n}\n\n/**\n * Returns true iff the field carries either:\n * - `@public` directive, OR\n * - `@rbac(public: true)` directive (any arg-order)\n */\nfunction isFieldPublic(field: FieldLikeDef | undefined): boolean {\n const directives = field?.astNode?.directives;\n if (!directives || directives.length === 0) return false;\n\n for (const dir of directives) {\n const name = dir.name?.value;\n if (name === 'public') return true;\n if (name === 'rbac') {\n const args = dir.arguments ?? [];\n for (const arg of args) {\n if (arg.name?.value === 'public' && arg.value?.kind === 'BooleanValue' && arg.value.value === true) {\n return true;\n }\n }\n }\n }\n return false;\n}\n\ninterface DocumentLike {\n definitions?: ReadonlyArray<{\n kind?: string;\n operation?: string;\n name?: { value?: string };\n selectionSet?: {\n selections?: ReadonlyArray<{\n kind?: string;\n name?: { value?: string };\n }>;\n };\n }>;\n}\n\n/**\n * Resolve the operation type ('query' | 'mutation' | 'subscription') for the\n * primary operation in the document. Falls back to 'query'.\n */\nfunction resolveOperationType(\n document: DocumentLike | undefined,\n operationName: string | null | undefined\n): 'query' | 'mutation' | 'subscription' {\n const defs = document?.definitions ?? [];\n for (const def of defs) {\n if (def.kind !== 'OperationDefinition') {\n // Older parsers may not set kind; fall through to the operation property check below.\n }\n if (def.operation && (!operationName || def.name?.value === operationName)) {\n return def.operation as 'query' | 'mutation' | 'subscription';\n }\n }\n return 'query';\n}\n\n/**\n * Resolve the root field names selected by the operation that will execute\n * (`operationName` identifies it when the document carries multiple\n * operations). Returns null when no operation definition matches, the\n * selection set is empty, or a non-Field selection appears at the root\n * (fragment spreads / inline fragments fail closed — see the public-bypass\n * rationale above). Introspection fields (`__schema`, `__type`) are omitted;\n * an introspection-only operation yields an EMPTY array (not null) so callers\n * can distinguish \"only introspection selected\" from \"fail closed\".\n */\nfunction resolveRootFieldNames(\n document: DocumentLike | undefined,\n operationName: string | null | undefined\n): string[] | null {\n const defs = document?.definitions ?? [];\n const opDef = defs.find((d) => d.operation && (!operationName || d.name?.value === operationName));\n const selections = opDef?.selectionSet?.selections ?? [];\n if (selections.length === 0) return null;\n\n const fieldNames: string[] = [];\n for (const sel of selections) {\n if (sel.kind && sel.kind !== 'Field') return null;\n const fieldName = sel.name?.value;\n if (!fieldName) return null;\n if (fieldName.startsWith('__')) continue;\n fieldNames.push(fieldName);\n }\n return fieldNames;\n}\n\n/**\n * Returns true iff every root field selected by the operation is present in\n * the whitelist set. An empty list (introspection-only operation) is NOT\n * exempt — the whitelist covers named schema fields only. A document mixing\n * an exempt field with a guarded field is NOT exempt either, so an exempt\n * bootstrap field cannot smuggle a guarded one.\n */\nfunction allRootFieldsWhitelisted(rootFieldNames: string[], whitelistedFields: Set<string>): boolean {\n return rootFieldNames.length > 0 && rootFieldNames.every((name) => whitelistedFields.has(name));\n}\n\n/**\n * Returns true iff every root field in the document selection set is marked\n * public on the schema. An empty field list (introspection-only operation) is\n * public — schema discovery never requires workspace context. Null (fail\n * closed: no matching operation, empty selection set, or fragment at the\n * root) is not public.\n */\nfunction allRootFieldsPublic(\n schema: SchemaLike | undefined,\n document: DocumentLike | undefined,\n operationName: string | null | undefined,\n rootFieldNames: string[] | null\n): boolean {\n if (!document) return false;\n if (rootFieldNames === null) return false;\n // Introspection-only operations are always public — schema discovery never\n // requires workspace context, and no schema lookup is needed for it.\n if (rootFieldNames.length === 0) return true;\n if (!schema) return false;\n\n const opType = resolveOperationType(document, operationName);\n let rootType: ReturnType<NonNullable<SchemaLike['getQueryType']>> | undefined;\n if (opType === 'mutation') {\n rootType = schema.getMutationType?.();\n } else if (opType === 'subscription') {\n rootType = schema.getSubscriptionType?.();\n } else {\n rootType = schema.getQueryType?.();\n }\n\n if (!rootType) return false;\n\n const fields = rootType.getFields();\n for (const fieldName of rootFieldNames) {\n const fieldDef = fields[fieldName];\n if (!isFieldPublic(fieldDef)) return false;\n }\n return true;\n}\n\n// ============================================================================\n// Plugin\n// ============================================================================\n\n/**\n * Create a GraphQL Yoga plugin that guards operations requiring workspace context.\n *\n * The plugin inspects the GraphQL context for workspace information (set by the SDK's\n * buildContext from the x-workspace-id header). If missing and the operation is not\n * whitelisted (and not all-public per directive), it throws a WORKSPACE_REQUIRED error.\n *\n * @param config - Guard configuration\n * @returns A Yoga-compatible plugin\n *\n * @example\n * ```typescript\n * import { createWorkspaceGuardPlugin } from '@burdenoff/be-sdk/server';\n *\n * const guardPlugin = createWorkspaceGuardPlugin({\n * whitelistedOperations: ['createWorkspace'],\n * allowPublicDirective: true, // default\n * });\n * ```\n */\nexport function createWorkspaceGuardPlugin(config?: WorkspaceGuardConfig) {\n const enabled = config?.enabled ?? true;\n const whitelistedOperations = new Set(config?.whitelistedOperations ?? []);\n const whitelistedFields = new Set(config?.whitelistedFields ?? []);\n const validateWorkspaceMembership = config?.validateWorkspaceMembership;\n const allowPublicDirective = config?.allowPublicDirective ?? true;\n const errorMessage =\n config?.errorMessage ??\n 'Workspace context required. Ensure the request includes a valid workspace context (x-workspace-id header).';\n\n if (!enabled) {\n logger.info('[WorkspaceGuard] Workspace guard disabled');\n return {};\n }\n\n logger.info('[WorkspaceGuard] Workspace guard enabled', {\n whitelistedOperations: [...whitelistedOperations],\n whitelistedFields: [...whitelistedFields],\n membershipValidation: validateWorkspaceMembership ? 'enabled' : 'disabled',\n allowPublicDirective,\n });\n\n return {\n async onExecute({\n args,\n }: {\n args: {\n schema?: SchemaLike;\n document?: DocumentLike;\n operationName?: string | null;\n contextValue?: {\n actor?: { id?: string; type?: string } | null;\n workspace?: { id?: string };\n request?: Request;\n };\n };\n }) {\n // Extract operation name from args or document\n let operationName = args.operationName;\n\n if (!operationName && args.document?.definitions) {\n for (const def of args.document.definitions) {\n if (def.operation && def.name?.value) {\n operationName = def.name.value;\n break;\n }\n }\n }\n\n // Check if operation is whitelisted by name (legacy, client-supplied name)\n if (operationName && whitelistedOperations.has(operationName)) {\n return undefined;\n }\n\n // Resolve the executed operation's root fields once. Null means fail\n // closed (no matching operation, empty selection set, or fragment at\n // the root); an empty array means an introspection-only operation.\n const rootFieldNames = resolveRootFieldNames(args.document, operationName);\n\n // Check if every root field of the executed operation is whitelisted by\n // FIELD name, resolved from the parsed document — independent of the\n // client-supplied operation name.\n if (whitelistedFields.size > 0 && rootFieldNames && allRootFieldsWhitelisted(rootFieldNames, whitelistedFields)) {\n return undefined;\n }\n\n // Check schema-directive-based public bypass (Option C)\n if (allowPublicDirective && allRootFieldsPublic(args.schema, args.document, operationName, rootFieldNames)) {\n return undefined;\n }\n\n // Check for workspace context\n const context = args.contextValue;\n const workspaceId = context?.workspace?.id;\n\n // Also check the raw header as a fallback\n const headerWorkspaceId = context?.request?.headers?.get?.('x-workspace-id');\n\n if (!workspaceId && !headerWorkspaceId) {\n logger.warn('[WorkspaceGuard] Blocked operation without workspace context', {\n operationName: operationName ?? '<anonymous>',\n });\n throw new WorkspaceRequiredError(errorMessage);\n }\n\n // A workspace id is present. When the service wired a membership\n // validator, the id must denote a workspace the actor actually belongs\n // to — a well-formed but unrelated UUID is rejected with NOT_FOUND so\n // workspace existence is never leaked to non-members. The context id\n // wins only when non-empty; an empty context id falls back to the\n // header (matching the truthiness gate above).\n if (validateWorkspaceMembership) {\n const resolvedWorkspaceId = workspaceId ? workspaceId : (headerWorkspaceId ?? '');\n const actor = context?.actor ?? null;\n let isMember = false;\n try {\n isMember = await validateWorkspaceMembership({\n actorId: actor?.id ?? null,\n actorType: actor?.type ?? null,\n workspaceId: resolvedWorkspaceId,\n contextValue: context,\n });\n } catch (error) {\n // Fail closed: a membership-lookup failure must not admit the request.\n logger.error('[WorkspaceGuard] Workspace membership validation failed', {\n operationName: operationName ?? '<anonymous>',\n workspaceId: resolvedWorkspaceId,\n error,\n });\n throw new WorkspaceMembershipError(resolvedWorkspaceId);\n }\n if (!isMember) {\n logger.warn('[WorkspaceGuard] Rejected non-member workspace context', {\n operationName: operationName ?? '<anonymous>',\n workspaceId: resolvedWorkspaceId,\n actorId: actor?.id ?? null,\n });\n throw new WorkspaceMembershipError(resolvedWorkspaceId);\n }\n }\n\n return undefined;\n },\n };\n}\n","/**\n * Mutation-audit backstop plugin\n *\n * A GraphQL Yoga plugin that writes one generic activity row\n * (`activityType: 'graphql.mutation'`, `resourceType: 'graphql_mutation'`,\n * `resourceId: <comma-joined top-level field names>`) for every mutation that\n * did NOT already record its own activity through an explicit SDK call.\n *\n * It replaces the `src/plugins/mutation-audit-plugin.ts` copy that lived in ~34\n * services. Differences from that copy:\n *\n * - Dedupe. The operation runs inside an explicit-activity scope\n * (`../activity/explicit-activity-scope.ts`). `trackOperation`,\n * `trackerStub.track` and `ActivityModule.log` mark the scope, and so does every\n * service `logAudit` wrapper built on them. A marked operation gets no backstop\n * row, so mounting this plugin never doubles a row a resolver already wrote.\n * Resolvers whose audit goes through a path the SDK cannot see call\n * `suppressMutationAudit()`.\n * - `excludeFields` opts individual mutation fields out entirely.\n * - Top-level fields reached through inline fragments and fragment spreads are\n * counted, and `__typename` is ignored.\n *\n * Dedupe works per operation: a multi-field mutation document where one field\n * records explicitly and another does not gets no backstop row. Clients send one\n * top-level mutation field per operation in practice, so this is the safe side\n * (never a duplicate) of the trade-off.\n *\n * Sensitive keys (password, token, secret, …) are redacted and every preview is\n * bounded in depth, array length, key count and string length.\n *\n * @example\n * ```ts\n * import { createMutationAuditPlugin } from '@burdenoff/be-sdk/server';\n *\n * yogaPlugins: [createMutationAuditPlugin({ serviceName: 'wspace-vibecontrols-svc' })]\n * ```\n */\n\nimport type {\n DocumentNode,\n ExecutionResult,\n FragmentDefinitionNode,\n OperationDefinitionNode,\n SelectionSetNode,\n} from 'graphql';\nimport { Kind, OperationTypeNode } from 'graphql';\nimport type { Plugin } from 'graphql-yoga';\n\nimport {\n createExplicitActivityScope,\n runInExplicitActivityScope,\n type ExplicitActivityScope,\n} from '../activity/explicit-activity-scope.js';\nimport { logger } from '../logger/index.js';\nimport { trackOperation } from '../tracker/stub.js';\n\nexport const MUTATION_AUDIT_ACTIVITY_TYPE = 'graphql.mutation';\nexport const MUTATION_AUDIT_RESOURCE_TYPE = 'graphql_mutation';\n\nexport interface MutationAuditPluginOptions {\n /** Service name recorded in each row's metadata, e.g. `wspace-vibecontrols-svc`. */\n serviceName: string;\n /** Mutation field names that never get a backstop row. */\n excludeFields?: Iterable<string>;\n /**\n * Skip the backstop row when the operation already recorded activity through an\n * explicit SDK call. Default `true`; `false` restores the old always-write behaviour.\n */\n dedupeExplicitActivity?: boolean;\n}\n\nconst SENSITIVE_KEY_MARKERS = [\n 'password',\n 'passcode',\n 'pass',\n 'token',\n 'secret',\n 'apikey',\n 'accesskey',\n 'authorization',\n 'cookie',\n 'credential',\n 'clientsecret',\n 'privatekey',\n];\n\nconst MAX_DEPTH = 2;\nconst MAX_ARRAY_ITEMS = 5;\nconst MAX_OBJECT_KEYS = 20;\nconst MAX_STRING_LENGTH = 200;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isSensitiveKey(key: string): boolean {\n const normalizedKey = key.toLowerCase().replaceAll(/[-_]/g, '');\n return SENSITIVE_KEY_MARKERS.some((marker) => normalizedKey.includes(marker));\n}\n\nfunction truncate(value: string): string {\n return value.length > MAX_STRING_LENGTH ? `${value.slice(0, MAX_STRING_LENGTH)}...` : value;\n}\n\n/** Redact sensitive keys and bound the size of a value before it is stored as metadata. */\nexport function sanitizeAuditValue(value: unknown, depth = 0): unknown {\n if (value == null || typeof value === 'boolean' || typeof value === 'number') {\n return value;\n }\n if (typeof value === 'string') {\n return truncate(value);\n }\n if (depth >= MAX_DEPTH) {\n return '[Truncated]';\n }\n if (Array.isArray(value)) {\n return value.slice(0, MAX_ARRAY_ITEMS).map((entry) => sanitizeAuditValue(entry, depth + 1));\n }\n if (!isRecord(value)) {\n return `[${typeof value}]`;\n }\n\n const sanitized: Record<string, unknown> = {};\n let count = 0;\n for (const [key, entry] of Object.entries(value)) {\n if (count >= MAX_OBJECT_KEYS) {\n sanitized['__truncated__'] = true;\n break;\n }\n sanitized[key] = isSensitiveKey(key) ? '[REDACTED]' : sanitizeAuditValue(entry, depth + 1);\n count += 1;\n }\n return sanitized;\n}\n\nfunction findMutation(document: DocumentNode, operationName?: string | null): OperationDefinitionNode | undefined {\n const operations = document.definitions.filter(\n (definition): definition is OperationDefinitionNode => definition.kind === Kind.OPERATION_DEFINITION\n );\n // graphql-js executes the named operation, or the only one when no name is given.\n let operation: OperationDefinitionNode | undefined;\n if (operationName) {\n operation = operations.find((definition) => definition.name?.value === operationName);\n } else if (operations.length === 1) {\n operation = operations[0];\n }\n return operation?.operation === OperationTypeNode.MUTATION ? operation : undefined;\n}\n\nfunction collectTopLevelFields(\n selectionSet: SelectionSetNode,\n fragments: ReadonlyMap<string, FragmentDefinitionNode>,\n fields: string[],\n visitedFragments: Set<string>\n): void {\n for (const selection of selectionSet.selections) {\n if (selection.kind === Kind.FIELD) {\n const name = selection.name.value;\n if (!name.startsWith('__') && !fields.includes(name)) fields.push(name);\n } else if (selection.kind === Kind.INLINE_FRAGMENT) {\n collectTopLevelFields(selection.selectionSet, fragments, fields, visitedFragments);\n } else {\n const fragmentName = selection.name.value;\n const fragment = fragments.get(fragmentName);\n if (fragment && !visitedFragments.has(fragmentName)) {\n visitedFragments.add(fragmentName);\n collectTopLevelFields(fragment.selectionSet, fragments, fields, visitedFragments);\n }\n }\n }\n}\n\n/** Top-level mutation field names the executed operation selects (empty for a query or subscription). */\nexport function getMutationFieldNames(document: DocumentNode, operationName?: string | null): string[] {\n const operation = findMutation(document, operationName);\n if (!operation) return [];\n\n const fragments = new Map<string, FragmentDefinitionNode>();\n for (const definition of document.definitions) {\n if (definition.kind === Kind.FRAGMENT_DEFINITION) fragments.set(definition.name.value, definition);\n }\n const fields: string[] = [];\n collectTopLevelFields(operation.selectionSet, fragments, fields, new Set());\n return fields;\n}\n\nfunction idOf(value: unknown): string | undefined {\n if (!isRecord(value)) return undefined;\n const id = value['id'];\n return typeof id === 'string' && id.length > 0 ? id : undefined;\n}\n\nfunction stringOf(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction findWorkspaceId(value: unknown, depth = 0): string | undefined {\n if (depth > MAX_DEPTH || !isRecord(value)) return undefined;\n const direct = stringOf(value['workspaceId']);\n if (direct) return direct;\n for (const entry of Object.values(value)) {\n const nested = findWorkspaceId(entry, depth + 1);\n if (nested) return nested;\n }\n return undefined;\n}\n\nfunction isExecutionResult(value: unknown): value is ExecutionResult {\n return isRecord(value) && ('data' in value || 'errors' in value);\n}\n\ninterface AuditRecordInput {\n serviceName: string;\n fieldNames: string[];\n contextValue: unknown;\n variableValues: unknown;\n result: unknown;\n}\n\nfunction recordMutationAudit(input: AuditRecordInput): void {\n const context = isRecord(input.contextValue) ? input.contextValue : {};\n const actor = isRecord(context['actor']) ? context['actor'] : undefined;\n const actorId = idOf(actor) ?? stringOf(context['actorId']) ?? 'anonymous';\n const actorType = stringOf(actor?.['type']) ?? stringOf(context['actorType']) ?? 'unknown';\n const workspaceId =\n idOf(context['workspace']) ?? stringOf(context['workspaceId']) ?? findWorkspaceId(input.variableValues);\n const tenantId = idOf(context['tenant']) ?? stringOf(context['tenantId']);\n const executionResult = isExecutionResult(input.result) ? input.result : undefined;\n const errors = executionResult?.errors ?? [];\n const success = errors.length === 0;\n const errorMessage = success ? undefined : truncate(errors.map((error) => error.message).join('; '));\n const joinedFields = input.fieldNames.join(',');\n\n void trackOperation({\n operationName: joinedFields,\n userId: actorId,\n // The request context drives the row's actorType/onBehalfOf (BOFF-9684): an `app` actor\n // here is an AI agent or integration. An unknown kind is left unset, never guessed.\n context,\n workspaceId,\n success,\n errorMessage,\n activityOptions: {\n enabled: true,\n activityType: MUTATION_AUDIT_ACTIVITY_TYPE,\n description: `GraphQL mutation executed: ${input.fieldNames.join(', ')}`,\n workspaceId,\n resourceType: MUTATION_AUDIT_RESOURCE_TYPE,\n resourceId: joinedFields,\n metadata: {\n serviceName: input.serviceName,\n source: 'mutation-audit-backstop',\n actorType,\n fieldNames: input.fieldNames,\n tenantId,\n tracking: sanitizeAuditValue(context['tracking']),\n variablePreview: sanitizeAuditValue(input.variableValues),\n resultPreview: sanitizeAuditValue(\n executionResult\n ? {\n data: executionResult.data,\n errors: errors.map((error) => ({ message: error.message, path: error.path?.join('.') })),\n }\n : undefined\n ),\n },\n },\n }).catch((error: unknown) => {\n logger.warn('[MutationAuditPlugin] Failed to record mutation audit', {\n serviceName: input.serviceName,\n fieldNames: input.fieldNames,\n error: error instanceof Error ? error.message : String(error),\n });\n });\n}\n\nfunction shouldWrite(scope: ExplicitActivityScope, dedupe: boolean): boolean {\n if (scope.suppressed) return false;\n return !(dedupe && scope.explicitCount > 0);\n}\n\n/**\n * Create the mutation-audit backstop plugin.\n *\n * Accepts the bare service name for drop-in compatibility with the per-service copies.\n */\nexport function createMutationAuditPlugin(options: MutationAuditPluginOptions | string): Plugin {\n const resolved: MutationAuditPluginOptions = typeof options === 'string' ? { serviceName: options } : options;\n const excluded = new Set(resolved.excludeFields ?? []);\n const dedupe = resolved.dedupeExplicitActivity !== false;\n\n return {\n onExecute({ args, executeFn, setExecuteFn }) {\n const fieldNames = getMutationFieldNames(args.document, args.operationName).filter((name) => !excluded.has(name));\n if (fieldNames.length === 0) return;\n\n setExecuteFn(async (executeArgs) => {\n const scope = createExplicitActivityScope();\n const result = await runInExplicitActivityScope(scope, () => executeFn(executeArgs));\n try {\n if (shouldWrite(scope, dedupe)) {\n recordMutationAudit({\n serviceName: resolved.serviceName,\n fieldNames,\n contextValue: executeArgs.contextValue,\n variableValues: executeArgs.variableValues,\n result,\n });\n }\n } catch (error) {\n // The backstop must never fail the mutation it observes.\n logger.warn('[MutationAuditPlugin] Failed to prepare mutation audit', {\n serviceName: resolved.serviceName,\n fieldNames,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n return result;\n });\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,kBACd,OACA,oBACoB;CACpB,IAAI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a,UAAU,WAAW,CAAC;GACnF,IAAI;IACF,IAAI,YAAY,OAAO,MAAM,GAC3B,oBAAoB;KAClB,aAAa,SAAS;KACtB;KACA,cAAc,YAAY;KAC1B,gBAAgB,YAAY;KAC5B;IACF,CAAC;GAEL,SAAS,OAAO;IAEd,OAAO,KAAK,0DAA0D;KACpE,aAAa,SAAS;KACtB;KACA,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;IAC9D,CAAC;GACH;GACA,OAAO;EACT,CAAC;CACH,EACF;AACF"}
1
+ {"version":3,"file":"index.js","names":["isRecord","elysiaApp"],"sources":["../../src/server/delegated-identity.ts","../../src/server/auth.ts","../../src/server/verified-delegation.ts","../../src/server/context.ts","../../src/server/workspace-execution-context.ts","../../src/server/security.ts","../../src/server/quotaGaugeRefresh.ts","../../src/server/raw-body-routes.ts","../../src/server/readiness.ts","../../src/server/dependency-watchdog.ts","../../src/server/errors.ts","../../src/server/server.ts","../../src/server/workspace-guard.ts","../../src/server/mutation-audit.ts"],"sourcesContent":["/**\n * Delegated identity helpers (BOFF-9962).\n *\n * The only trustworthy source of \"an app or agent acting for a user\" is the\n * signed `app_as_user` token issued by global-auth (App + AppUserDelegation).\n * A gateway verifies that token and forwards the decoded facts as\n * `x-verified-delegation`, which `buildContext` turns into\n * `ctx.verifiedDelegation`. The legacy `x-consent-*` headers are plain caller\n * input: every gateway strips them, and this SDK no longer reads them, so they\n * can never decide audit attribution.\n *\n * @module server/delegated-identity\n */\n\nimport type { IActor, VerifiedDelegationContext } from './types.js';\n\n/**\n * The principal recorded as `onBehalfOf` for an operation.\n *\n * With a verified delegation the gateway has already authenticated the\n * represented user as the actor, so the represented user is the principal.\n * Without one the actor acts for itself. Caller-supplied consent headers are\n * never consulted.\n */\nexport function resolveOnBehalfOf(\n actor: IActor | null,\n verifiedDelegation: VerifiedDelegationContext | undefined\n): string | undefined {\n if (verifiedDelegation && actor && verifiedDelegation.representedUserId === actor.id) {\n return verifiedDelegation.representedUserId;\n }\n return actor?.id;\n}\n\n/**\n * The verified \"agent for user\" pair behind a request, in the shape the audit\n * helpers need (for example `trackAgentActivity({ agentId, onBehalfOf })`).\n */\nexport interface DelegatedPrincipal {\n /** The global-auth App (agent) that acts. */\n agentAppId: string;\n /** The user the agent acts for; also the authenticated actor. */\n onBehalfOfUserId: string;\n /** The AppUserDelegation grant the token was issued from. */\n delegationId: string;\n /** Scopes the signed token carries. */\n scopes: readonly string[];\n /** Workspaces the grant is bound to; empty means unrestricted. */\n allowedWorkspaceIds: readonly string[];\n /** Who granted the delegation, when the token carries signed consent facts. */\n grantedBy: string | null;\n /** When the grant itself expires; null for an unbounded grant or unknown consent. */\n grantExpiresAt: Date | null;\n /** When the presented token stops being valid. */\n tokenExpiresAt: Date;\n}\n\n/**\n * Returns the verified delegated principal for a request context, or null when\n * the request was not made under a verified `app_as_user` delegation.\n */\nexport function getDelegatedPrincipal(context: {\n actor: IActor | null;\n verifiedDelegation?: VerifiedDelegationContext;\n}): DelegatedPrincipal | null {\n const delegation = context.verifiedDelegation;\n if (!delegation || !context.actor || delegation.representedUserId !== context.actor.id) {\n return null;\n }\n return {\n agentAppId: delegation.originatingAppId,\n onBehalfOfUserId: delegation.representedUserId,\n delegationId: delegation.delegationId,\n scopes: delegation.scopes,\n allowedWorkspaceIds: delegation.allowedWorkspaceIds,\n grantedBy: delegation.consent?.grantedBy ?? null,\n grantExpiresAt: delegation.consent?.expiresAt ?? null,\n tokenExpiresAt: delegation.tokenExpiresAt,\n };\n}\n","/**\n * Server Auth Module\n *\n * JWT verification with workspace secret fetching for microservices.\n * Handles HS256 tokens with secrets stored in workspace database.\n */\n\nimport { logger } from '../logger/index.js';\nimport type { IActor, JWTPayload, VerifiedDelegationContext, WorkspaceSecret } from './types.js';\nimport { resolveOnBehalfOf } from './delegated-identity.js';\n\n// Type imports from packages\nimport type * as jose from 'jose';\nimport type { VerifyOptions, Jwt, JwtPayload } from 'jsonwebtoken';\n\n/**\n * Workspace model interface for fetching JWT secrets\n */\ninterface WorkspaceModel {\n findUnique: (args: { where: { id: string } }) => Promise<{ jwtSecret?: unknown } | null>;\n}\n\ninterface DbClient {\n client: {\n workspace: WorkspaceModel;\n };\n}\n\n// Import getDb dynamically to avoid circular dependencies\nlet getDbFn: (() => DbClient) | null = null;\n\nasync function getDb(): Promise<DbClient> {\n if (!getDbFn) {\n const prismaModule = await import('../prisma/index.js');\n // Use unknown first then cast to avoid type inference issues\n getDbFn = prismaModule.getDb as unknown as () => DbClient;\n }\n return getDbFn();\n}\n\n// Interface for the subset of jsonwebtoken we use\ninterface JwtModule {\n decode(token: string, options?: { complete?: boolean }): string | Jwt | JwtPayload | null;\n verify(token: string, secretOrPublicKey: string, options?: VerifyOptions): string | JwtPayload;\n}\n\n// Module cache for dynamic imports\nlet joseModule: typeof jose | null = null;\nlet jwtModule: JwtModule | null = null;\n\nasync function getJose(): Promise<typeof jose> {\n if (!joseModule) {\n joseModule = await import('jose');\n }\n return joseModule;\n}\n\nasync function getJwt(): Promise<JwtModule> {\n if (!jwtModule) {\n const jwt = await import('jsonwebtoken');\n // Handle both ESM and CJS module formats\n jwtModule = (jwt as { default?: JwtModule }).default ?? jwt;\n }\n return jwtModule;\n}\n\n/**\n * Fetch workspace secret callback type\n */\nexport type FetchWorkspaceSecretFn = (workspaceId: string) => Promise<WorkspaceSecret | null>;\n\n/**\n * Auth configuration\n */\nexport interface AuthConfig {\n /** Function to fetch workspace JWT secret from database */\n fetchWorkspaceSecret: FetchWorkspaceSecretFn;\n}\n\nlet authConfig: AuthConfig | null = null;\n\n/**\n * Configure auth module with workspace secret fetching\n */\nexport function configureAuth(config: AuthConfig): void {\n authConfig = config;\n logger.debug('[ServerAuth] Auth configured');\n}\n\n/**\n * Default workspace secret fetcher\n *\n * Fetches JWT secret from workspace database. This is the standard implementation\n * that works with any microservice that has access to the workspace model.\n *\n * @param workspaceId - Workspace ID from JWT\n * @returns WorkspaceSecret or null if not found\n */\nexport async function fetchWorkspaceSecret(workspaceId: string): Promise<WorkspaceSecret | null> {\n try {\n const db = await getDb();\n const workspace = await db.client.workspace.findUnique({\n where: { id: workspaceId },\n });\n\n if (!workspace?.jwtSecret) {\n logger.debug('[ServerAuth] No JWT secret found for workspace', { workspaceId });\n return null;\n }\n\n return JSON.parse(JSON.stringify(workspace.jwtSecret)) as WorkspaceSecret;\n } catch (error) {\n logger.warn('[ServerAuth] Error fetching workspace secret', { workspaceId, error });\n return null;\n }\n}\n\n/**\n * Configure auth with default workspace secret fetcher\n *\n * This is automatically called by createServer if no custom auth is configured.\n */\nexport function configureDefaultAuth(): void {\n if (!authConfig) {\n configureAuth({ fetchWorkspaceSecret });\n logger.debug('[ServerAuth] Default auth configured with built-in workspace secret fetcher');\n }\n}\n\n/**\n * Generate a symmetric secret key for JWT signing\n * @returns JWK object with the generated key\n */\nexport async function generateSymmetricSecret(): Promise<jose.JWK> {\n const joseLib = await getJose();\n const secret = await joseLib.generateSecret('HS256', { extractable: true });\n const jwk = await joseLib.exportJWK(secret);\n return jwk;\n}\n\n/**\n * Verify JWT token for workspace-scoped authentication\n *\n * @param token - JWT token to verify\n * @param secret - Optional secret for verification (if not provided, fetches from workspace)\n * @param options - JWT verification options\n * @returns Verified actor information or null if invalid\n */\nexport async function verifyJWT(token: string, secret?: string, options: VerifyOptions = {}): Promise<IActor | null> {\n try {\n const jwt = await getJwt();\n const joseLib = await getJose();\n\n // Decode to check algorithm and extract workspace_id\n const decoded = jwt.decode(token, { complete: true });\n\n if (!decoded || typeof decoded === 'string' || !decoded.payload || typeof decoded.payload !== 'object') {\n logger.warn('[ServerAuth] Invalid token format');\n return null;\n }\n\n // For workspace-scoped HS256 tokens\n if (secret) {\n // Use provided secret\n const verifiedJwt = jwt.verify(token, secret, options) as JWTPayload;\n return mapPayloadToActor(verifiedJwt);\n }\n\n // Fetch secret from workspace database\n const decodedJwt = joseLib.decodeJwt(token) as JWTPayload;\n if (!decodedJwt.workspace_id) {\n logger.warn('[ServerAuth] No workspace_id found in token');\n return null;\n }\n\n if (!authConfig?.fetchWorkspaceSecret) {\n logger.error('[ServerAuth] Auth not configured - call configureAuth() first');\n return null;\n }\n\n const workspaceSecret = await authConfig.fetchWorkspaceSecret(decodedJwt.workspace_id);\n if (!workspaceSecret) {\n logger.warn('[ServerAuth] Workspace secret not found');\n return null;\n }\n\n const keyLikeSecret = await joseLib.importJWK(workspaceSecret, 'HS256');\n const verifiedJwt = await joseLib.jwtVerify(token, keyLikeSecret, options as jose.JWTVerifyOptions);\n return mapPayloadToActor(verifiedJwt.payload as unknown as JWTPayload);\n } catch (err) {\n logger.warn('[ServerAuth] Error verifying JWT:', err);\n return null;\n }\n}\n\n/**\n * Decode JWT without verification (for extracting claims)\n */\nexport async function decodeJWT(token: string): Promise<JWTPayload | null> {\n try {\n const joseLib = await getJose();\n return joseLib.decodeJwt<JWTPayload>(token);\n } catch {\n return null;\n }\n}\n\n/**\n * Map JWT payload to IActor interface\n */\nfunction mapPayloadToActor(payload: JWTPayload): IActor {\n return {\n id: payload.sub,\n type: payload.actor_type ?? 'user',\n workspace_id: payload.workspace_id,\n tenant_id: payload.tenant_id,\n org_id: payload.org_id,\n isAdmin: payload['isAdmin'] as boolean | undefined,\n };\n}\n\n/**\n * Check if actor is authenticated\n */\nexport function authCheck(actor: IActor | null): IActor {\n if (!actor) {\n throw new Error('Please sign in');\n }\n return actor;\n}\n\n/**\n * Check workspace context and return actor ID and workspace ID\n */\nexport function workspaceCheck(context: { actor: IActor | null; workspace: { id: string } | null }): {\n actorId: string;\n workspaceId: string;\n} {\n const actor = authCheck(context.actor);\n\n if (!context.workspace?.id) {\n throw new Error('Please switch to a workspace');\n }\n\n return {\n actorId: actor.id,\n workspaceId: context.workspace.id,\n };\n}\n\n/**\n * Require workspace context - type narrowing guard for wspace layer services\n *\n * Validates that both actor and workspace are present in the context,\n * and returns a type-narrowed context where workspace and actor are guaranteed non-null.\n * Use this at the start of resolvers in wspace services to get typed access\n * to workspace context without optional chaining.\n *\n * @throws Error if actor is not authenticated\n * @throws Error if workspace context is missing\n *\n * @example\n * ```typescript\n * // In a resolver:\n * const ctx = requireWorkspace(context);\n * const workspaceId = ctx.workspace.id; // no optional chaining needed\n * const actorId = ctx.actor.id; // no optional chaining needed\n * ```\n */\nexport function requireWorkspace<T extends { actor: IActor | null; workspace: { id: string } | null }>(\n context: T\n): T & { actor: IActor; workspace: { id: string } } {\n // Validate actor is authenticated (throws if null)\n authCheck(context.actor);\n\n if (!context.workspace?.id) {\n throw new Error('Please switch to a workspace');\n }\n\n // Return the same context object with narrowed types\n return context as T & { actor: IActor; workspace: { id: string } };\n}\n\n/**\n * Check organization context and return actor ID and org ID\n */\nexport function orgCheck(context: { actor: IActor | null; organization: { id: string } | null }): {\n actorId: string;\n orgId: string;\n} {\n const actor = authCheck(context.actor);\n\n if (!context.organization?.id) {\n throw new Error('Please switch to an organization');\n }\n\n return {\n actorId: actor.id,\n orgId: context.organization.id,\n };\n}\n\n/**\n * Check tenant context and return tenant ID\n */\nexport function tenantCheck(context: { tenant: { id: string } | null }): string {\n if (!context.tenant?.id) {\n throw new Error('Tenant context is required');\n }\n return context.tenant.id;\n}\n\n/**\n * Get effective actor ID for \"on behalf of\" tracking\n *\n * Returns the principal an operation is performed for. With a verified\n * delegation (a signed `app_as_user` token checked by a gateway) that is the\n * represented user; otherwise it is the actor itself.\n *\n * Caller-supplied consent (`x-consent-*` headers or a hand-built\n * `consentContext`) is never consulted (BOFF-9962): it is unverified input\n * and would let any caller forge attribution.\n *\n * @param context - GraphQL context with actor and optional verified delegation\n * @returns Effective actor ID (the responsible principal)\n *\n * @example\n * ```typescript\n * // User acting directly\n * getEffectiveActorId({ actor: { id: \"user-123\", type: \"user\" } }) // → \"user-123\"\n *\n * // App acting for a user under a verified delegation: the gateway\n * // authenticates the represented user as the actor.\n * getEffectiveActorId({\n * actor: { id: \"user-789\", type: \"user\", provenance: \"delegated\" },\n * verifiedDelegation, // representedUserId \"user-789\", originatingAppId \"app-abc\"\n * }) // → \"user-789\"\n * ```\n */\nexport function getEffectiveActorId(context: {\n actor: IActor | null;\n verifiedDelegation?: VerifiedDelegationContext;\n}): string | null {\n return resolveOnBehalfOf(context.actor, context.verifiedDelegation) ?? null;\n}\n","import type { IActor, VerifiedDelegationContext } from './types.js';\n\n// Structural narrowing permits inspecting unknown properties without trusting their values.\nfunction object(value: unknown): Record<string, unknown> | null {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null;\n}\n\nfunction identifier(value: unknown): value is string {\n return (\n typeof value === 'string' &&\n value['length'] > 0 &&\n value['length'] <= 200 &&\n value['trim']() === value &&\n Array.from(value).every((character) => character.charCodeAt(0) >= 32 && character.charCodeAt(0) !== 127)\n );\n}\n\nfunction list(value: unknown): value is string[] {\n return Array.isArray(value) && value['length'] <= 1000 && value['every'](identifier);\n}\n\nfunction instant(value: unknown): Date | null {\n if (typeof value !== 'string') return null;\n const time = Date.parse(value);\n return Number.isFinite(time) && new Date(time).toISOString() === value ? new Date(time) : null;\n}\n\n/** Decodes transport only; JWT verification remains the gateway's responsibility. */\nexport function decodeVerifiedDelegation(\n header: string | undefined,\n actor: IActor | null,\n workspaceId: string | undefined,\n trustedGateway: boolean,\n now = Date.now()\n): VerifiedDelegationContext | undefined {\n if (\n !trustedGateway ||\n !actor ||\n actor.provenance !== 'delegated' ||\n !['user', 'super_admin'].includes(actor.type) ||\n header === undefined\n )\n return undefined;\n const invalid = () => new Error('Invalid verified delegation context');\n let raw: unknown;\n try {\n raw = JSON.parse(header);\n } catch {\n throw invalid();\n }\n const value = object(raw);\n const tokenExpiresAt = instant(value?.['tokenExpiresAt']);\n if (\n !value ||\n !identifier(value['representedUserId']) ||\n value['representedUserId'] !== actor.id ||\n !identifier(value['originatingAppId']) ||\n !identifier(value['delegationId']) ||\n !list(value['scopes']) ||\n !list(value['allowedWorkspaceIds']) ||\n !tokenExpiresAt ||\n tokenExpiresAt.getTime() <= now ||\n (workspaceId && value['allowedWorkspaceIds'].length > 0 && !value['allowedWorkspaceIds'].includes(workspaceId))\n )\n throw invalid();\n let consent: VerifiedDelegationContext['consent'] = null;\n if (value['consent'] !== null) {\n const facts = object(value['consent']);\n const grantedAt = instant(facts?.['grantedAt']);\n const expiresAt = facts?.['expiresAt'] === null ? null : instant(facts?.['expiresAt']);\n if (\n !facts ||\n !identifier(facts['grantedBy']) ||\n !grantedAt ||\n grantedAt.getTime() > now ||\n (facts['expiresAt'] !== null &&\n (!expiresAt || expiresAt.getTime() <= grantedAt.getTime() || tokenExpiresAt.getTime() > expiresAt.getTime()))\n )\n throw invalid();\n consent = { grantedBy: facts['grantedBy'], grantedAt, expiresAt };\n }\n return {\n representedUserId: value['representedUserId'],\n originatingAppId: value['originatingAppId'],\n delegationId: value['delegationId'],\n scopes: [...value['scopes']],\n allowedWorkspaceIds: [...value['allowedWorkspaceIds']],\n tokenExpiresAt,\n consent,\n };\n}\n","/**\n * Server Context Module\n *\n * Builds GraphQL context from request headers, JWT, and configuration.\n * Automatically populates actor, tenant, workspace, and tracking information.\n *\n * **Actor-Based Authentication:**\n * - Production: Gateway verifies JWT → populates x-actor-* headers → services trust headers\n * - Development: Services verify JWT directly and build actor from payload\n *\n * Uses standard Web API Request (compatible with Bun/Elysia).\n */\n\nimport { logger } from '../logger/index.js';\nimport crypto from 'node:crypto';\nimport { verifyJWT } from './auth.js';\nimport { decodeVerifiedDelegation } from './verified-delegation.js';\nimport { resolveOnBehalfOf } from './delegated-identity.js';\nimport { parseAssistantSessionHeaders } from '../activity/assistant-session.js';\nimport type {\n GraphQLContext,\n ActorProvenance,\n IActor,\n ITenant,\n IOrganization,\n IWorkspace,\n IProject,\n IProduct,\n ITracking,\n} from './types.js';\nimport type { I18n, I18nContext } from '../i18n/index.js';\nimport { setWorkspaceContext } from '../prisma/workspace-extension.js';\n\n/**\n * Context builder options\n */\nexport interface ContextBuilderOptions {\n /** Database getter function */\n getDb: () => unknown;\n /** Default tenant info (optional) */\n defaultTenant?: ITenant;\n /** I18n instance (optional) */\n i18n?: I18n;\n}\n\nlet contextOptions: ContextBuilderOptions | null = null;\n\n/**\n * Configure context builder\n */\nexport function configureContext(options: ContextBuilderOptions): void {\n contextOptions = options;\n logger.debug('[ServerContext] Context builder configured');\n}\n\n/**\n * Extract header value from standard Web API Request\n */\nfunction getHeader(request: Request, key: string): string | undefined {\n return request.headers.get(key.toLowerCase()) ?? undefined;\n}\n\nfunction compareSecret(provided: string, expected: string): boolean {\n const providedBuffer = Buffer.from(provided);\n const expectedBuffer = Buffer.from(expected);\n\n if (providedBuffer.length !== expectedBuffer.length) {\n return false;\n }\n\n return crypto.timingSafeEqual(providedBuffer, expectedBuffer);\n}\n\nexport function shouldTrustActorHeaders(\n request: Request,\n nodeEnv: string | undefined = process.env['NODE_ENV'],\n expectedGatewayToken: string | undefined = process.env['TRUSTED_GATEWAY_TOKEN'] ??\n process.env['INTERNAL_SERVICE_TOKEN']\n): boolean {\n if (!getHeader(request, 'x-actor-id')) {\n return false;\n }\n\n if (nodeEnv === 'production') {\n return true;\n }\n\n const providedGatewayToken =\n getHeader(request, 'x-internal-service-token') || getHeader(request, 'x-gateway-auth-token');\n if (!expectedGatewayToken || !providedGatewayToken) {\n return false;\n }\n\n return compareSecret(providedGatewayToken, expectedGatewayToken);\n}\n\n/**\n * Extract tracking information from request\n */\nfunction extractTracking(request: Request): ITracking {\n // Get IP from various possible headers\n const forwardedFor = getHeader(request, 'x-forwarded-for');\n const realIp = getHeader(request, 'x-real-ip');\n const ip = forwardedFor?.split(',')[0]?.trim() || realIp || undefined;\n\n return {\n ip,\n userAgent: getHeader(request, 'user-agent'),\n };\n}\n\n/**\n * Extract actor from gateway-injected headers or authorization header\n *\n * **Actor-Based Authentication:**\n * - If x-actor-id header exists, trust it (gateway-authenticated)\n * - Otherwise fall back to JWT verification (direct access in dev)\n *\n * This allows:\n * - Production: Gateway verifies JWT → populates x-actor-* headers → services trust headers\n * - Development: Direct service access with JWT → service verifies JWT itself\n * - Development testing: Direct headers → service trusts headers\n */\nfunction actorProvenance(request: Request): ActorProvenance {\n const value = getHeader(request, 'x-verified-actor-provenance');\n return value === 'direct_human' || value === 'delegated' || value === 'non_human' ? value : 'unknown';\n}\n\nasync function extractActor(request: Request): Promise<IActor | null> {\n // Check for gateway-injected actor headers first\n const actorId = getHeader(request, 'x-actor-id');\n\n if (actorId && shouldTrustActorHeaders(request)) {\n // Gateway has already verified JWT and populated context headers\n // Trust the headers (gateway is the security perimeter)\n logger.debug('[ServerContext] Using gateway-authenticated actor from headers');\n\n const actorType = getHeader(request, 'x-actor-type') || 'user';\n const userRole = getHeader(request, 'x-user-role');\n const verifiedServiceIdentity = getHeader(request, 'x-verified-service-identity')?.trim() || undefined;\n\n return {\n id: actorId,\n type: actorType,\n provenance: actorProvenance(request),\n ...(verifiedServiceIdentity ? { verifiedServiceIdentity } : {}),\n workspace_id: getHeader(request, 'x-workspace-id'),\n tenant_id: getHeader(request, 'x-tenant-id'),\n org_id: getHeader(request, 'x-org-id') || getHeader(request, 'x-organization-id'),\n isAdmin:\n actorType === 'super_admin' ||\n userRole === 'TENANT_ADMIN' ||\n userRole === 'SUPER_ADMIN' ||\n userRole === 'PLATFORM_ADMIN',\n };\n }\n\n if (actorId) {\n logger.warn('[ServerContext] Ignoring untrusted actor headers and falling back to JWT verification');\n }\n\n // FALLBACK: No gateway headers, verify JWT directly (dev/testing mode)\n const authHeader = getHeader(request, 'authorization');\n\n if (!authHeader?.startsWith('Bearer ')) {\n return null;\n }\n\n const token = authHeader.substring(7);\n\n try {\n logger.debug('[ServerContext] No gateway headers, verifying JWT directly for actor (dev mode)');\n const payload = await verifyJWT(token);\n\n if (!payload) {\n return null;\n }\n\n // Build actor from JWT payload\n return {\n id: payload.id,\n type: 'user', // Default to 'user' if not specified\n provenance: 'unknown', // Development fallback does not attest gateway provenance.\n workspace_id: payload.workspace_id,\n };\n } catch (error) {\n logger.warn('[ServerContext] Invalid JWT token:', error);\n return null;\n }\n}\n\n/**\n * Extract tenant from headers\n */\nfunction extractTenant(request: Request): ITenant | null {\n // Check headers\n const tenantId = getHeader(request, 'x-tenant-id');\n const tenantEndpoint = getHeader(request, 'x-tenant-endpoint');\n\n if (tenantId) {\n return {\n id: tenantId,\n endpoint: tenantEndpoint || '',\n };\n }\n\n // Fall back to default tenant if configured\n return contextOptions?.defaultTenant || null;\n}\n\n/**\n * Extract organization from headers\n */\nfunction extractOrganization(request: Request): IOrganization | null {\n const orgId = getHeader(request, 'x-org-id') || getHeader(request, 'x-organization-id');\n\n if (orgId) {\n return { id: orgId };\n }\n\n return null;\n}\n\n/**\n * Extract workspace from headers or actor\n */\nfunction extractWorkspace(request: Request, actor: IActor | null): IWorkspace | null {\n // Check headers first\n const workspaceId = getHeader(request, 'x-workspace-id');\n\n if (workspaceId) {\n return { id: workspaceId };\n }\n\n // Fall back to workspace_id from actor\n if (actor?.workspace_id) {\n return { id: actor.workspace_id };\n }\n\n return null;\n}\n\n/**\n * Extract project from headers\n */\nfunction extractProject(request: Request): IProject | null {\n const projectId = getHeader(request, 'x-project-id');\n\n if (projectId) {\n return { id: projectId };\n }\n\n return null;\n}\n\n/**\n * Extract product from headers\n */\nfunction extractProduct(request: Request): IProduct | null {\n const productId = getHeader(request, 'x-product-id');\n\n if (productId) {\n return { id: productId };\n }\n\n return null;\n}\n\n/**\n * Extract geography context from headers\n *\n * Geography headers carry the user's selected location context,\n * used for currency defaults, tax calculations, payment routing,\n * data residency, and regional support.\n *\n * Headers:\n * - x-geo-country: ISO 3166-1 alpha-2 country code (e.g., 'IN', 'US', 'DE')\n * - x-geo-currency: ISO 4217 currency code (e.g., 'INR', 'USD', 'EUR')\n * - x-geo-timezone: IANA timezone (e.g., 'Asia/Kolkata', 'America/New_York')\n */\nfunction extractGeography(request: Request): { country?: string; currency?: string; timezone?: string } {\n const country = getHeader(request, 'x-geo-country');\n const currency = getHeader(request, 'x-geo-currency');\n const timezone = getHeader(request, 'x-geo-timezone');\n\n return {\n country: country?.toUpperCase() || undefined,\n currency: currency?.toUpperCase() || undefined,\n timezone: timezone || undefined,\n };\n}\n\n/**\n * Build GraphQL context from standard Web Request\n *\n * Also sets the workspace context in AsyncLocalStorage for automatic\n * Prisma workspaceId injection via the workspace extension.\n */\nexport async function buildContext(request: Request): Promise<GraphQLContext> {\n if (!contextOptions) {\n throw new Error('[ServerContext] Context not configured - call configureContext() first');\n }\n\n // Extract actor from headers/JWT\n const actor = await extractActor(request);\n\n // Extract all context parts\n const tenant = extractTenant(request);\n const organization = extractOrganization(request);\n const workspace = extractWorkspace(request, actor);\n const project = extractProject(request);\n const product = extractProduct(request);\n const tracking = extractTracking(request);\n const trustedGatewayHeaders = shouldTrustActorHeaders(request);\n const verifiedDelegation = decodeVerifiedDelegation(\n getHeader(request, 'x-verified-delegation'),\n actor,\n workspace?.id,\n trustedGatewayHeaders\n );\n // BOFF-9649: the AI assistant session behind this request, as the public gateway verified it\n // from the session relay's signed marker. Read only with an actor whose gateway headers this\n // service already trusts; the public gateways strip any client-supplied copy.\n const assistantSession =\n actor && trustedGatewayHeaders ? parseAssistantSessionHeaders((name) => getHeader(request, name)) : undefined;\n const verifiedServiceIdentity =\n actor && trustedGatewayHeaders ? getHeader(request, 'x-verified-service-identity')?.trim() || undefined : undefined;\n\n // Build i18n context if configured\n let i18n: I18nContext | undefined;\n if (contextOptions.i18n) {\n i18n = contextOptions.i18n.createContextFromRequest(request);\n }\n\n // Merge geography context from x-geo-* headers into i18n\n const geo = extractGeography(request);\n if (geo.country || geo.currency || geo.timezone) {\n if (i18n) {\n // Merge geography fields into existing i18n context\n if (geo.country) i18n.country = geo.country;\n if (geo.currency) i18n.currency = geo.currency;\n if (geo.timezone) i18n.timezone = geo.timezone;\n } else {\n // Create minimal i18n context with geography only (when i18n module not configured)\n i18n = {\n locale: 'en-US',\n language: 'en',\n country: geo.country,\n currency: geo.currency,\n timezone: geo.timezone,\n t: (key: string) => key,\n tp: (key: string) => key,\n formatNumber: (value: number) => String(value),\n formatCurrency: (value: number, currency: string) => `${currency} ${value}`,\n formatDate: (date: Date | string) => String(date),\n formatRelativeTime: (value: number, unit: Intl.RelativeTimeFormatUnit) => `${value} ${unit}`,\n };\n }\n }\n\n // Determine onBehalfOf for audit trails (BOFF-9962). Only a verified\n // delegation (signed app_as_user token checked by a gateway) may name a\n // principal other than the actor. Raw x-consent-* headers are caller input\n // and are deliberately not read: they could otherwise forge attribution.\n const onBehalfOf = resolveOnBehalfOf(actor, verifiedDelegation);\n\n // Set workspace context in AsyncLocalStorage for Prisma workspace extension\n // This enables automatic workspaceId injection on create/update operations\n const wsCtxPayload = {\n workspaceId: workspace?.id,\n tenantId: tenant?.id,\n actorId: actor?.id,\n actorType: actor?.type,\n organizationId: organization?.id,\n projectId: project?.id,\n onBehalfOf,\n ...(assistantSession ? { assistantSession } : {}),\n };\n\n logger.debug('[ServerContext] Setting workspace context', {\n workspaceId: wsCtxPayload.workspaceId ?? 'NONE',\n actorId: wsCtxPayload.actorId ?? 'NONE',\n rawHeader: getHeader(request, 'x-workspace-id') ?? 'MISSING',\n });\n\n setWorkspaceContext(wsCtxPayload);\n\n // The Cloudflare Access credentials this request presented are not stored here. The\n // execution plugin and the REST/raw-body/graph-export handlers bind them from this context's\n // `request` together with the rest of the request scope (workspaceContextFromServerContext),\n // so ContextManager.getCfAccessHeaders() sees them only inside this request's own scope.\n\n return {\n request,\n actor,\n tenant,\n organization,\n workspace,\n project,\n product,\n tracking,\n verifiedDelegation,\n ...(verifiedServiceIdentity ? { verifiedServiceIdentity } : {}),\n ...(assistantSession ? { assistantSession } : {}),\n onBehalfOf: onBehalfOf || actor?.id || '',\n db: contextOptions.getDb(),\n i18n,\n responseHeaders: new Headers(),\n };\n}\n\n/**\n * Get context options\n */\nexport function getContextOptions(): ContextBuilderOptions | null {\n return contextOptions;\n}\n","import type { Plugin } from 'graphql-yoga';\n\nimport { readAssistantSessionAttribution } from '../activity/assistant-session.js';\nimport { withWorkspaceContext, type WorkspaceContext } from '../prisma/workspace-extension.js';\nimport type { CfAccessCredentials } from '../types/index.js';\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction string(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction id(value: unknown): string | undefined {\n return record(value) ? string(value['id']) : undefined;\n}\n\nfunction header(request: unknown, name: string): string | undefined {\n if (!record(request)) return undefined;\n const headers = request['headers'];\n if (!record(headers) || typeof headers['get'] !== 'function') return undefined;\n // Duck-typed so any Fetch-API `Headers` implementation (Bun, undici, Yoga's) is accepted.\n return string((headers as unknown as Headers).get(name));\n}\n\n/**\n * The Cloudflare Access credentials the request itself presented, read from its own headers.\n * The public gateway forwards them only for requests that transited Cloudflare. A lone\n * service-token half is dropped, since it can never pass Access on its own.\n */\nexport function cfAccessFromRequest(request: unknown): CfAccessCredentials | undefined {\n const clientId = header(request, 'cf-access-client-id');\n const clientSecret = header(request, 'cf-access-client-secret');\n const authorization = header(request, 'x-cf-authorization');\n const pair = clientId && clientSecret ? { clientId, clientSecret } : undefined;\n if (!pair && !authorization) return undefined;\n return { ...pair, ...(authorization ? { authorization } : {}) };\n}\n\n/**\n * The workspace context for a request, read from the verified server context\n * (`buildContext`'s result or a Yoga `contextValue`). Unknown shapes yield an\n * empty context: no workspace, so the extension's strict mode applies. The\n * Cloudflare Access credentials come from the context's own `request`, so the\n * bound scope carries exactly the credentials that request presented.\n */\nexport function workspaceContextFromServerContext(value: unknown): WorkspaceContext {\n if (!record(value)) return {};\n const assistantSession = readAssistantSessionAttribution(value['assistantSession']);\n const cfAccess = cfAccessFromRequest(value['request']);\n return {\n ...(assistantSession ? { assistantSession } : {}),\n ...(cfAccess ? { cfAccess } : {}),\n workspaceId: id(value['workspace']),\n tenantId: id(value['tenant']),\n organizationId: id(value['organization']),\n projectId: id(value['project']),\n actorId: id(value['actor']),\n actorType: record(value['actor']) ? string(value['actor']['type']) : undefined,\n onBehalfOf: string(value['onBehalfOf']),\n };\n}\n\nfunction scopedIterable<T>(source: AsyncIterable<T>, scope: WorkspaceContext): AsyncIterable<T> {\n return {\n [Symbol.asyncIterator]() {\n const iterator = source[Symbol.asyncIterator]();\n const finish = iterator.return?.bind(iterator);\n const fail = iterator.throw?.bind(iterator);\n return {\n next: (...args: [] | [unknown]) => withWorkspaceContext(scope, async () => iterator.next(...args)),\n return: finish ? (value?: unknown) => withWorkspaceContext(scope, async () => finish(value)) : undefined,\n throw: fail ? (error?: unknown) => withWorkspaceContext(scope, async () => fail(error)) : undefined,\n };\n },\n };\n}\n\n/** Context creation and GraphQL execution may run in different async chains.\n * Bind execution to its own verified context instead of the most recent request's fallback.\n */\nexport function createWorkspaceExecutionContextPlugin(): Plugin {\n return {\n onExecute({ executeFn, setExecuteFn }) {\n setExecuteFn((args) => {\n const scope = workspaceContextFromServerContext(args.contextValue);\n return withWorkspaceContext(scope, async () => {\n const result = await executeFn(args);\n return Symbol.asyncIterator in result ? scopedIterable(result, scope) : result;\n });\n });\n },\n onSubscribe({ subscribeFn, setSubscribeFn }) {\n setSubscribeFn((args) => {\n const scope = workspaceContextFromServerContext(args.contextValue);\n return withWorkspaceContext(scope, async () => {\n const result = await subscribeFn(args);\n return Symbol.asyncIterator in result ? scopedIterable(result, scope) : result;\n });\n });\n },\n };\n}\n\n/**\n * Run a REST or raw-body endpoint handler inside its own request's verified\n * workspace context. `buildContext` binds the context with `enterWith`, which\n * does not reach the caller that awaited it, so without this the handler would\n * run with no bound context.\n */\nexport function runWithServerWorkspaceContext<T>(serverContext: unknown, fn: () => Promise<T>): Promise<T> {\n return withWorkspaceContext(workspaceContextFromServerContext(serverContext), fn);\n}\n","import type { IActor } from './types.js';\n\nconst LOCALHOST_ORIGINS = [\n 'http://localhost:3000',\n 'http://localhost:4000',\n 'http://localhost:5173',\n 'http://127.0.0.1:3000',\n 'http://127.0.0.1:4000',\n 'http://127.0.0.1:5173',\n];\n\nexport function normalizeCorsOrigins(\n origins: string | string[] | undefined,\n environment: 'development' | 'staging' | 'production' | undefined\n): string[] {\n const normalized = (Array.isArray(origins) ? origins : origins?.split(',') || [])\n .map((origin) => origin.trim())\n .filter(Boolean);\n\n if (normalized.length === 0) {\n return environment === 'production' ? [] : LOCALHOST_ORIGINS;\n }\n\n if (normalized.includes('*')) {\n return environment === 'production' ? [] : LOCALHOST_ORIGINS;\n }\n\n return normalized;\n}\n\nexport function resolveAllowedCorsOrigin(requestOrigin: string | null, allowedOrigins: string[]): string | null {\n if (!requestOrigin) {\n return allowedOrigins[0] ?? null;\n }\n\n return allowedOrigins.includes(requestOrigin) ? requestOrigin : null;\n}\n\nexport function canAccessGraphExport(actor: IActor | null): boolean {\n if (!actor) {\n return false;\n }\n\n return actor.isAdmin === true || ['service', 'super_admin'].includes(actor.type);\n}\n","/**\n * Workspace quota gauge refresh throttling for the `/metrics` route.\n *\n * `WorkspaceQuotaRegistry.collectAll()` issues Prisma groupBy queries. Running\n * it inline on every Prometheus scrape made `/metrics` exactly as slow as the\n * database: services that registered quota collectors routinely exceeded a 30s\n * `scrape_timeout` and were recorded as down, even though the endpoint itself\n * was healthy.\n *\n * Scrapes are far more frequent than these values meaningfully change, so\n * refresh on a TTL, bound each refresh, and let concurrent scrapes share one\n * in-flight attempt. A slow or unavailable database then degrades gauge\n * freshness instead of failing the scrape.\n *\n * @module server/quotaGaugeRefresh\n */\n\n/**\n * Read a positive-integer millisecond setting from the environment.\n *\n * Anything unset, non-numeric, or <= 0 falls back to the default: an operator\n * typo must not silently disable the throttle that keeps `/metrics` fast.\n */\nexport function envMs(name: string, fallback: number): number {\n const raw = process.env[name];\n if (!raw) return fallback;\n const parsed = Number.parseInt(raw, 10);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;\n}\n\n/**\n * How long a gauge snapshot is considered fresh.\n *\n * Override with `BOFF_QUOTA_GAUGE_TTL_MS` — raise it when the database is under\n * load and quota freshness matters less than scrape latency.\n */\nexport const QUOTA_GAUGE_TTL_MS = envMs('BOFF_QUOTA_GAUGE_TTL_MS', 60_000);\n\n/**\n * Upper bound on a single refresh, so a slow database cannot stall a scrape.\n *\n * Override with `BOFF_QUOTA_GAUGE_TIMEOUT_MS`. Keep it comfortably below the\n * Prometheus `scrape_timeout`, or a slow refresh still fails the scrape.\n */\nexport const QUOTA_GAUGE_REFRESH_TIMEOUT_MS = envMs('BOFF_QUOTA_GAUGE_TIMEOUT_MS', 5_000);\n\nexport interface QuotaGaugeRefresherOptions {\n /** Performs the actual (expensive) collection. */\n collect: () => Promise<unknown>;\n ttlMs?: number;\n timeoutMs?: number;\n /** Injectable clock, for tests. */\n now?: () => number;\n}\n\nexport interface QuotaGaugeRefresher {\n /** Refresh if stale. Never rejects. */\n refresh: () => Promise<void>;\n /** Epoch ms of the last completed attempt (0 when never run). */\n lastRefreshedAt: () => number;\n}\n\n/**\n * Build a TTL-throttled, timeout-bounded, single-flight refresher.\n *\n * `refresh()` never rejects — `/metrics` must keep serving prom-client and SDK\n * registry output even when the quota registry is unconfigured or erroring.\n * A failed attempt does not advance the TTL, so the next scrape retries.\n */\nexport function createQuotaGaugeRefresher(opts: QuotaGaugeRefresherOptions): QuotaGaugeRefresher {\n const ttlMs = opts.ttlMs ?? QUOTA_GAUGE_TTL_MS;\n const timeoutMs = opts.timeoutMs ?? QUOTA_GAUGE_REFRESH_TIMEOUT_MS;\n const now = opts.now ?? ((): number => Date.now());\n\n let refreshedAt = 0;\n let inFlight: Promise<void> | null = null;\n\n const refresh = async (): Promise<void> => {\n if (refreshedAt !== 0 && now() - refreshedAt < ttlMs) return;\n\n if (!inFlight) {\n inFlight = (async (): Promise<void> => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n Promise.resolve(opts.collect()).then(() => undefined),\n new Promise<void>((resolve) => {\n timer = setTimeout(resolve, timeoutMs);\n }),\n ]);\n // Stamp only on a completed attempt; a throw leaves the TTL expired\n // so the next scrape retries rather than serving a stale snapshot\n // forever.\n refreshedAt = now();\n } catch {\n /* unconfigured registry or failed query — keep the previous snapshot */\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n inFlight = null;\n }\n })();\n }\n\n await inFlight;\n };\n\n return { refresh, lastRefreshedAt: (): number => refreshedAt };\n}\n","/**\n * Raw-body REST route resolution (BOFF-7766).\n *\n * Raw-body endpoints (webhooks: `rawBody: true`) are intercepted in `onRequest`, before Elysia\n * parses the body, so they cannot use Elysia's own router. They used to be resolved by PATH alone\n * — a Map keyed by path, then the first matching pattern — and only then compared to the request\n * method. Registering one path for several verbs therefore served exactly one of them; every other\n * verb fell through and 404'd. The method check could only reject, never select.\n *\n * Resolution is now keyed on path AND method:\n * - a registration for the request's method wins (HEAD falls back to GET, as HTTP allows);\n * - a path that is registered, but not for this method, answers 405 with an `Allow` header —\n * unless an ordinary route serves that method on the same path, in which case the request\n * falls through to Elysia exactly as before (e.g. a GET page next to a raw POST);\n * - an unknown path is not ours, and falls through.\n */\nimport type { RESTEndpoint } from './types.js';\n\nexport type RawBodyResolution =\n { kind: 'endpoint'; endpoint: RESTEndpoint } | { kind: 'method-not-allowed'; allowed: string[] };\n\n/** An ordinary (body-parsed) route, as Elysia lists it in `app.routes`. */\nexport interface OrdinaryRoute {\n method: string;\n path: string;\n}\n\ninterface PathMatcher {\n exact: string | null;\n regex: RegExp | null;\n}\n\ninterface CompiledRoute extends PathMatcher {\n byMethod: Map<string, RESTEndpoint>;\n}\n\nconst REGEX_SPECIAL = /[.*+?^${}()|[\\]\\\\]/g;\n\nfunction compile(path: string): PathMatcher {\n if (!path.includes(':') && !path.includes('*')) return { exact: path, regex: null };\n const pattern = path\n .split('/')\n .map((segment) => {\n if (segment === '*') return '.*';\n if (segment.startsWith(':')) return '[^/]+';\n return segment.replace(REGEX_SPECIAL, '\\\\$&');\n })\n .join('/');\n return { exact: null, regex: new RegExp(`^${pattern}$`) };\n}\n\nfunction matches(route: PathMatcher, pathname: string): boolean {\n return route.exact !== null ? route.exact === pathname : (route.regex?.test(pathname) ?? false);\n}\n\nfunction keyOf(route: PathMatcher): string {\n return route.exact ?? route.regex?.source ?? '';\n}\n\n/** Order the methods an `Allow` header lists: the usual verbs first, then anything else. */\nconst METHOD_ORDER = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];\nconst rank = (method: string): number => {\n const index = METHOD_ORDER.indexOf(method);\n return index === -1 ? METHOD_ORDER.length : index;\n};\n\nexport interface RawBodyRouter {\n /** How many distinct raw-body paths are registered (0 lets a service without any skip the work). */\n readonly size: number;\n /** Whether a raw-body route is registered on this path, for any method (CORS preflight). */\n hasPath(pathname: string): boolean;\n resolve(pathname: string, method: string): RawBodyResolution | null;\n}\n\n/**\n * Build the resolver for a service's raw-body endpoints. `ordinaryRoutes` lists the routes Elysia\n * itself serves; it is read lazily, only when a method misses, so routes a service registers after\n * `createServer` still count.\n */\nexport function createRawBodyRouter(\n endpoints: readonly RESTEndpoint[],\n ordinaryRoutes: () => readonly OrdinaryRoute[] = () => []\n): RawBodyRouter {\n const routes: CompiledRoute[] = [];\n for (const endpoint of endpoints.filter((ep) => ep.rawBody)) {\n const method = endpoint.method.toUpperCase();\n const compiled = compile(endpoint.path);\n let route = routes.find((candidate) => keyOf(candidate) === keyOf(compiled));\n if (!route) {\n route = { ...compiled, byMethod: new Map() };\n routes.push(route);\n }\n // First registration of a path + method wins, as Elysia's own router does.\n if (!route.byMethod.has(method)) route.byMethod.set(method, endpoint);\n }\n\n // Ordinary routes are listed lazily (a service may add some after createServer), so their\n // matchers are compiled on first sight and cached by path.\n const ordinaryMatchers = new Map<string, PathMatcher>();\n const ordinaryVerbsOn = (pathname: string): Set<string> => {\n const verbs = new Set<string>();\n for (const route of ordinaryRoutes()) {\n let matcher = ordinaryMatchers.get(route.path);\n if (!matcher) {\n matcher = compile(route.path);\n ordinaryMatchers.set(route.path, matcher);\n }\n if (matches(matcher, pathname)) verbs.add(route.method.toUpperCase());\n }\n return verbs;\n };\n\n return {\n size: routes.length,\n hasPath(pathname: string): boolean {\n return routes.some((route) => matches(route, pathname));\n },\n resolve(pathname: string, rawMethod: string): RawBodyResolution | null {\n const method = rawMethod.toUpperCase();\n // Exact paths before patterns, so `/webhooks/health` beats `/webhooks/:id`.\n const candidates = [\n ...routes.filter((route) => route.exact !== null && matches(route, pathname)),\n ...routes.filter((route) => route.exact === null && matches(route, pathname)),\n ];\n if (candidates.length === 0) return null;\n\n for (const route of candidates) {\n const endpoint = route.byMethod.get(method) ?? (method === 'HEAD' ? route.byMethod.get('GET') : undefined);\n if (endpoint) return { kind: 'endpoint', endpoint };\n }\n\n // Registered for other verbs only. An ordinary route may still serve this one.\n const ordinaryVerbs = ordinaryVerbsOn(pathname);\n const servedElsewhere =\n ordinaryVerbs.has(method) || ordinaryVerbs.has('ALL') || (method === 'HEAD' && ordinaryVerbs.has('GET'));\n if (servedElsewhere) return null;\n\n // `Allow` lists every verb the resource serves — raw-body and ordinary alike.\n const allowed = new Set<string>(ordinaryVerbs);\n for (const route of candidates) for (const verb of route.byMethod.keys()) allowed.add(verb);\n if (allowed.has('GET')) allowed.add('HEAD');\n allowed.add('OPTIONS');\n return { kind: 'method-not-allowed', allowed: [...allowed].sort((a, b) => rank(a) - rank(b)) };\n },\n };\n}\n\ninterface TimeoutCapableServer {\n timeout(request: Request, seconds: number): void;\n}\n\n/**\n * The Bun server that accepted each in-flight raw-body request, so a handler can extend its idle\n * timeout (see `extendRequestIdleTimeout`). A WeakMap: entries die with the request.\n */\nconst requestServers = new WeakMap<Request, TimeoutCapableServer>();\n\nfunction canTimeout(server: unknown): server is TimeoutCapableServer {\n return typeof (server as { timeout?: unknown } | null | undefined)?.timeout === 'function';\n}\n\nexport function rememberRequestServer(request: Request, server: unknown): void {\n if (canTimeout(server)) requestServers.set(request, server);\n}\n\n/** Bun caps a connection's idle timeout at 255 seconds. */\nexport const MAX_IDLE_TIMEOUT_SECONDS = 255;\n\n/** Default maximum body size buffered for `rawBody: true` REST endpoints (1 MiB). */\nexport const DEFAULT_RAW_BODY_MAX_BYTES = 1024 * 1024;\n\n/** Default server-wide Bun `maxRequestBodySize` ceiling (10 MiB, down from Bun's 128 MiB default). */\nexport const DEFAULT_MAX_REQUEST_BODY_SIZE = 10 * 1024 * 1024;\n\n/**\n * Thrown by {@link readBoundedRawBody} when a `rawBody: true` request declares\n * or streams more bytes than its configured limit.\n */\nexport class PayloadTooLargeError extends Error {\n public readonly status = 413;\n public readonly code = 'PAYLOAD_TOO_LARGE';\n public readonly maxBodyBytes: number;\n\n constructor(maxBodyBytes: number) {\n super(`Request body exceeds maximum allowed size of ${maxBodyBytes} bytes`);\n this.name = 'PayloadTooLargeError';\n this.maxBodyBytes = maxBodyBytes;\n }\n}\n\n/**\n * Validate and normalize a configured byte cap. Rejects negative, NaN, or\n * non-finite values by falling back to `fallback`.\n */\nexport function resolveBodyLimitBytes(configured: number | undefined, fallback: number): number {\n if (typeof configured === 'number' && Number.isFinite(configured) && configured >= 0) {\n return Math.floor(configured);\n }\n return fallback;\n}\n\n/**\n * Compute the explicit `maxRequestBodySize` to pass to `app.listen()` /\n * `Bun.serve()`, honoring an explicit server override or automatically sizing\n * to fit any opted-in large `rawBody` endpoint while staying well below Bun's\n * 128 MiB default.\n */\nexport function resolveMaxRequestBodySize(\n config: { maxBodyBytes?: number; maxRequestBodySize?: number },\n endpoints: readonly RESTEndpoint[] = []\n): number {\n if (\n typeof config.maxRequestBodySize === 'number' &&\n Number.isFinite(config.maxRequestBodySize) &&\n config.maxRequestBodySize > 0\n ) {\n return Math.floor(config.maxRequestBodySize);\n }\n const defaultRawLimit = resolveBodyLimitBytes(config.maxBodyBytes, DEFAULT_RAW_BODY_MAX_BYTES);\n let highestRawLimit = defaultRawLimit;\n for (const endpoint of endpoints) {\n if (!endpoint.rawBody) continue;\n const limit = resolveBodyLimitBytes(endpoint.maxBodyBytes, defaultRawLimit);\n if (limit > highestRawLimit) highestRawLimit = limit;\n }\n return Math.max(DEFAULT_MAX_REQUEST_BODY_SIZE, highestRawLimit);\n}\n\n/**\n * Read a request's raw body as UTF-8 while strictly enforcing `maxBodyBytes`.\n *\n * 1. Pre-rejects immediately on an oversized `Content-Length` header without\n * buffering any chunks.\n * 2. Streams `request.body` chunk-by-chunk, counting raw UTF-8 bytes and\n * cancelling the stream immediately on overflow (handles chunked transfer\n * encoding and spoofed/missing `Content-Length`).\n */\nexport async function readBoundedRawBody(\n request: Request,\n maxBodyBytes: number = DEFAULT_RAW_BODY_MAX_BYTES\n): Promise<string> {\n const limit = resolveBodyLimitBytes(maxBodyBytes, DEFAULT_RAW_BODY_MAX_BYTES);\n\n const contentLengthHeader = request.headers.get('content-length')?.trim();\n if (contentLengthHeader && /^\\d+$/.test(contentLengthHeader)) {\n const declaredBytes = Number.parseInt(contentLengthHeader, 10);\n if (declaredBytes > limit) {\n if (request.body) {\n await request.body.cancel().catch(() => undefined);\n }\n throw new PayloadTooLargeError(limit);\n }\n }\n\n if (!request.body) {\n return '';\n }\n\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let totalBytes = 0;\n\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (!value || value.byteLength === 0) continue;\n\n totalBytes += value.byteLength;\n if (totalBytes > limit) {\n await reader.cancel().catch(() => undefined);\n throw new PayloadTooLargeError(limit);\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n if (totalBytes === 0) {\n return '';\n }\n\n const combined = new Uint8Array(totalBytes);\n let offset = 0;\n for (const chunk of chunks) {\n combined.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return new TextDecoder('utf-8').decode(combined);\n}\n\n/**\n * Let one raw-body request stay idle for longer than the server default (Elysia's Bun adapter sets\n * 30 s). For handlers that legitimately hold a request open — a webhook answering with its\n * workflow's result. `seconds` is clamped to Bun's 255 s cap; 0 disables the timeout for the\n * request. Returns false when the request was not served by a Bun server that supports it.\n */\nexport function extendRequestIdleTimeout(request: Request, seconds: number): boolean {\n const server = requestServers.get(request);\n if (!server || !Number.isFinite(seconds) || seconds < 0) return false;\n server.timeout(request, Math.min(Math.floor(seconds), MAX_IDLE_TIMEOUT_SECONDS));\n return true;\n}\n","/**\n * Dependency-aware readiness for `createServer`.\n *\n * WHY THIS EXISTS\n * `createServer` used to answer `/health`, `/health/live`, `/health/ready` and\n * `/health/startup` with a hardcoded `{ status: 'healthy' }`. Nothing was ever\n * checked. Combined with gitops pointing BOTH Kubernetes probes at `/health`,\n * that meant a pod whose database or cache had gone away stayed in the Service\n * endpoints and kept answering requests with errors, and a rolling deploy could\n * report success while every replica was broken.\n *\n * gitops now splits the probes — liveness on `/health/live`, readiness on\n * `/health/ready` — and this module is what makes readiness mean something.\n *\n * THE REQUIRED / OPTIONAL SPLIT IS THE WHOLE DESIGN\n * Postgres is REQUIRED: a subgraph that cannot reach its database can serve\n * nothing, so it should leave rotation and let its siblings take the traffic.\n * Valkey and the event queue are OPTIONAL by default: they are a cache and an\n * async publisher, the service degrades rather than fails without them, and\n * making them required would take the entire fleet out of rotation\n * simultaneously the moment one shared ElastiCache cluster blinked — turning a\n * cache incident into a total outage. A service that genuinely cannot function\n * without one can promote it via `requiredDependencies`.\n *\n * Liveness deliberately checks NOTHING. If liveness were deep, a shared\n * dependency blip would restart every pod in the fleet at once, which is\n * strictly worse than serving degraded.\n */\n\n/** Minimal Prisma surface used for the readiness query — keeps this testable. */\nexport interface ReadinessPrisma {\n $queryRaw: (strings: TemplateStringsArray, ...values: unknown[]) => Promise<unknown>;\n}\n\n/** Minimal Valkey/Redis surface. */\nexport interface ReadinessCache {\n ping: () => Promise<unknown>;\n}\n\n/** Minimal event-queue surface (be-sdk `IEventPublisher` implementations). */\nexport interface ReadinessEventQueue {\n isConnected?: () => boolean | Promise<boolean>;\n healthCheck?: () => Promise<{ ok: boolean }>;\n}\n\n/**\n * Minimal GraphQL subscription pubsub surface (see `graphql/pubsub-health`).\n * `undefined` means the process has no Redis-backed pubsub to report on.\n */\nexport interface ReadinessPubSub {\n ok: boolean;\n unhealthy: string[];\n}\n\n/**\n * Supervised event consumers (see `event-queue/consumer-health`).\n * `undefined` means the process has no supervised consumer to report on.\n */\nexport interface ReadinessConsumers {\n ok: boolean;\n unhealthy: string[];\n}\n\nexport type DependencyName = 'postgres' | 'valkey' | 'eventQueue' | 'pubsub' | 'consumers';\n\nexport interface ReadinessDeps {\n prisma?: () => ReadinessPrisma | undefined;\n valkey?: () => Promise<ReadinessCache | undefined> | ReadinessCache | undefined;\n eventQueue?: () => ReadinessEventQueue | undefined;\n /**\n * GraphQL subscription pubsub. Optional by default like Valkey: while it is\n * degraded the pod still serves queries and mutations, and subscribers\n * recover once the transport reconnects (BOFF-17232).\n */\n pubsub?: () => ReadinessPubSub | undefined;\n /**\n * Supervised Redis Streams consumers. Optional by default: a consumer whose\n * start is being retried does not stop the pod serving queries, and the\n * supervisor brings it back once Valkey is reachable (BOFF-17231). A\n * service whose API is useless without its consumer can promote it.\n */\n consumers?: () => ReadinessConsumers | undefined;\n /**\n * Dependencies whose failure makes the pod NOT ready. Defaults to\n * `['postgres']`. Anything checked but not listed here is reported and\n * degrades `status`, but still answers 200 so the pod stays in rotation.\n */\n requiredDependencies?: DependencyName[];\n}\n\nexport interface DependencyResult {\n ok: boolean;\n required: boolean;\n error?: string;\n /** Milliseconds the check took — surfaces a slow dependency before it fails. */\n latencyMs: number;\n}\n\nexport interface ReadinessSnapshot {\n /** True when every REQUIRED dependency is healthy. Drives the HTTP status. */\n ready: boolean;\n /** True when every checked dependency is healthy, required or not. */\n healthy: boolean;\n checks: Partial<Record<DependencyName, DependencyResult>>;\n}\n\n/**\n * Result cache TTL. Kubernetes probes every 10s across N replicas, Gatus every\n * 300s, plus any load balancer — without this each of them becomes a `SELECT 1`\n * on a connection from the same bounded pool the application needs.\n */\nexport const READINESS_CACHE_MS = 1000;\n\n/** Hard ceiling on a single dependency check, so readiness cannot hang. */\nexport const READINESS_PROBE_TIMEOUT_MS = 2000;\n\nconst DEFAULT_REQUIRED: DependencyName[] = ['postgres'];\n\nasync function withTimeout<T>(work: Promise<T>, ms: number, label: string): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n work,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(`${label} check timed out after ${ms}ms`)), ms);\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nasync function runCheck(\n name: DependencyName,\n required: boolean,\n work: () => Promise<unknown>,\n now: () => number\n): Promise<DependencyResult> {\n const started = now();\n try {\n await withTimeout(Promise.resolve(work()), READINESS_PROBE_TIMEOUT_MS, name);\n return { ok: true, required, latencyMs: now() - started };\n } catch (err) {\n return {\n ok: false,\n required,\n error: err instanceof Error ? err.message : String(err),\n latencyMs: now() - started,\n };\n }\n}\n\n/**\n * Build a cached readiness prober. Each call site gets its own cache so tests\n * never share state with a running server.\n */\nexport function createReadinessProbe(\n deps: ReadinessDeps,\n now: () => number = Date.now\n): () => Promise<ReadinessSnapshot> {\n const required = new Set<DependencyName>(deps.requiredDependencies ?? DEFAULT_REQUIRED);\n let cache: { snapshot: ReadinessSnapshot; at: number } | null = null;\n let inFlight: Promise<ReadinessSnapshot> | null = null;\n\n async function probe(): Promise<ReadinessSnapshot> {\n const checks: Partial<Record<DependencyName, DependencyResult>> = {};\n\n const jobs: Array<Promise<void>> = [];\n\n if (deps.prisma) {\n jobs.push(\n runCheck(\n 'postgres',\n required.has('postgres'),\n async () => {\n const client = deps.prisma?.();\n if (!client) throw new Error('prisma client not initialised');\n await client.$queryRaw`SELECT 1`;\n },\n now\n ).then((r) => {\n checks.postgres = r;\n })\n );\n }\n\n if (deps.valkey) {\n jobs.push(\n runCheck(\n 'valkey',\n required.has('valkey'),\n async () => {\n const client = await deps.valkey?.();\n if (!client) throw new Error('valkey client not initialised');\n await client.ping();\n },\n now\n ).then((r) => {\n checks.valkey = r;\n })\n );\n }\n\n if (deps.eventQueue) {\n jobs.push(\n runCheck(\n 'eventQueue',\n required.has('eventQueue'),\n async () => {\n const q = deps.eventQueue?.();\n if (!q) throw new Error('event queue not initialised');\n if (typeof q.isConnected === 'function') {\n const connected = await Promise.resolve(q.isConnected());\n if (!connected) throw new Error('event queue reports disconnected');\n return;\n }\n if (typeof q.healthCheck === 'function') {\n const res = await q.healthCheck();\n if (!res.ok) throw new Error('event queue health check failed');\n }\n // A queue exposing neither hook is treated as healthy rather than\n // failed — inventing a failure would take pods out of rotation for\n // a dependency we cannot actually interrogate.\n },\n now\n ).then((r) => {\n checks.eventQueue = r;\n })\n );\n }\n\n const pubsub = deps.pubsub?.();\n if (pubsub) {\n jobs.push(\n runCheck(\n 'pubsub',\n required.has('pubsub'),\n async () => {\n if (!pubsub.ok) throw new Error(`pubsub degraded (${pubsub.unhealthy.join('; ')})`);\n },\n now\n ).then((r) => {\n checks.pubsub = r;\n })\n );\n }\n\n const consumers = deps.consumers?.();\n if (consumers) {\n jobs.push(\n runCheck(\n 'consumers',\n required.has('consumers'),\n async () => {\n if (!consumers.ok) throw new Error(`event consumer degraded (${consumers.unhealthy.join('; ')})`);\n },\n now\n ).then((r) => {\n checks.consumers = r;\n })\n );\n }\n\n await Promise.all(jobs);\n\n const results = Object.values(checks);\n return {\n ready: results.every((c) => c.ok || !c.required),\n healthy: results.every((c) => c.ok),\n checks,\n };\n }\n\n return async function getReadiness(): Promise<ReadinessSnapshot> {\n const at = now();\n if (cache && at - cache.at < READINESS_CACHE_MS) return cache.snapshot;\n // Collapse concurrent probes (three probes can land in the same tick).\n if (inFlight) return inFlight;\n inFlight = probe()\n .then((snapshot) => {\n cache = { snapshot, at: now() };\n return snapshot;\n })\n .finally(() => {\n inFlight = null;\n });\n return inFlight;\n };\n}\n\nexport interface HealthBody {\n status: 'healthy' | 'degraded' | 'unavailable';\n service: string;\n version: string;\n timestamp: string;\n checks?: Partial<Record<DependencyName, DependencyResult>>;\n uptimeSeconds?: number;\n}\n\n/** HTTP status for the readiness and aggregate endpoints. */\nexport function readinessStatusCode(snapshot: ReadinessSnapshot): 200 | 503 {\n return snapshot.ready ? 200 : 503;\n}\n\nexport function readinessBody(\n snapshot: ReadinessSnapshot,\n service: string,\n version: string,\n timestamp: string,\n uptimeSeconds?: number\n): HealthBody {\n const status: HealthBody['status'] = !snapshot.ready ? 'unavailable' : snapshot.healthy ? 'healthy' : 'degraded';\n return {\n status,\n service,\n version,\n timestamp,\n checks: snapshot.checks,\n ...(uptimeSeconds === undefined ? {} : { uptimeSeconds }),\n };\n}\n\n/** Liveness body — deliberately free of any dependency information. */\nexport function livenessBody(service: string, version: string, timestamp: string): HealthBody {\n return { status: 'healthy', service, version, timestamp };\n}\n","/**\n * Dependency watchdog for the liveness probe (BOFF-17229, generalised into the\n * SDK by BOFF-17231; `createServer` wires it through `health.watchdog`).\n *\n * Readiness answers \"can this pod serve right now?\" and covers short\n * datastore blips by taking the pod out of the Service. It cannot help a\n * process that got stuck: on 2026-11-28 the alpha pod hit `EAI_AGAIN` at boot,\n * its readiness stayed 503 for hours, and because liveness always passed\n * Kubernetes never restarted it.\n *\n * The watchdog probes each critical dependency in the background and\n * remembers since when it has been unhealthy. Liveness fails only once a\n * dependency has been unhealthy for longer than a bounded window (5 minutes by\n * default, plus up to 1 minute of per-process jitter), so kubelet restarts a\n * stuck process while a short outage never restarts anything. The jitter keeps\n * a fleet that lost the same datastore together from restarting in lockstep.\n *\n * The liveness handler only reads in-memory state, so the probe stays cheap\n * and never waits on the datastore itself.\n */\nimport { logger } from '../logger/index.js';\nimport type { ReadinessCache, ReadinessPrisma } from './readiness.js';\n\nexport interface DependencyProbe {\n /** Stable name reported in liveness output and logs. */\n name: string;\n /** Resolves true when healthy. `false`, a rejection or a timeout is unhealthy. */\n check: () => Promise<boolean> | boolean;\n}\n\nexport interface DependencyWatchdogConfig {\n /** When false, liveness never fails (the watchdog still records state). */\n enabled: boolean;\n /** How long a dependency may stay unhealthy before liveness fails. */\n unhealthyThresholdMs: number;\n /** Upper bound of the random per-process extension of the threshold. */\n jitterMs: number;\n /** Interval between background probe rounds. */\n intervalMs: number;\n /** Bound on a single probe; a slower probe counts as unhealthy. */\n checkTimeoutMs: number;\n}\n\nexport interface DependencyWatchdogOptions extends Partial<DependencyWatchdogConfig> {\n probes: DependencyProbe[];\n /** Clock; injectable for tests. */\n now?: () => number;\n /** Jitter source in [0, 1); injectable for tests. */\n random?: () => number;\n}\n\nexport interface FailingDependency {\n name: string;\n unhealthyForMs: number;\n}\n\nexport interface LivenessReport {\n alive: boolean;\n thresholdMs: number;\n failing: FailingDependency[];\n}\n\ninterface DependencyState {\n /** Start of the current unhealthy streak; null while healthy. */\n unhealthySince: number | null;\n lastError: string | null;\n}\n\nexport const DEFAULT_DEPENDENCY_WATCHDOG_CONFIG: DependencyWatchdogConfig = {\n enabled: true,\n unhealthyThresholdMs: 5 * 60_000,\n jitterMs: 60_000,\n intervalMs: 15_000,\n checkTimeoutMs: 5_000,\n};\n\n/**\n * The shortest threshold the env may configure. A smaller value would let a\n * routine datastore failover restart the whole fleet.\n */\nexport const MIN_UNHEALTHY_THRESHOLD_MS = 60_000;\n\nfunction readPositiveInt(raw: string | undefined, fallback: number): number {\n if (raw === undefined || raw.trim() === '') return fallback;\n const value = Number(raw);\n return Number.isInteger(value) && value > 0 ? value : fallback;\n}\n\n/**\n * Read the watchdog settings from the environment:\n * `DEPENDENCY_WATCHDOG_ENABLED` (default true), `DEPENDENCY_WATCHDOG_THRESHOLD_MS`\n * (default 300000, minimum 60000), `DEPENDENCY_WATCHDOG_JITTER_MS` (default\n * 60000), `DEPENDENCY_WATCHDOG_INTERVAL_MS` (default 15000) and\n * `DEPENDENCY_WATCHDOG_CHECK_TIMEOUT_MS` (default 5000). Invalid values fall\n * back to the defaults. `base` replaces the built-in defaults (a service's\n * `health.watchdog` settings); the env still wins, so operators can tune or\n * disable the watchdog without a release.\n */\nexport function resolveDependencyWatchdogConfig(\n env: Record<string, string | undefined> = process.env,\n base: Partial<DependencyWatchdogConfig> = {}\n): DependencyWatchdogConfig {\n const defaults = { ...DEFAULT_DEPENDENCY_WATCHDOG_CONFIG, ...base };\n return {\n enabled: defaults.enabled && (env['DEPENDENCY_WATCHDOG_ENABLED'] ?? '').trim().toLowerCase() !== 'false',\n unhealthyThresholdMs: Math.max(\n MIN_UNHEALTHY_THRESHOLD_MS,\n readPositiveInt(env['DEPENDENCY_WATCHDOG_THRESHOLD_MS'], defaults.unhealthyThresholdMs)\n ),\n jitterMs: readPositiveInt(env['DEPENDENCY_WATCHDOG_JITTER_MS'], defaults.jitterMs),\n intervalMs: readPositiveInt(env['DEPENDENCY_WATCHDOG_INTERVAL_MS'], defaults.intervalMs),\n checkTimeoutMs: readPositiveInt(env['DEPENDENCY_WATCHDOG_CHECK_TIMEOUT_MS'], defaults.checkTimeoutMs),\n };\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport class DependencyWatchdog {\n /** Effective threshold for this process: configured value plus jitter. */\n readonly thresholdMs: number;\n\n private readonly config: DependencyWatchdogConfig;\n private readonly probes: DependencyProbe[];\n private readonly now: () => number;\n private readonly states = new Map<string, DependencyState>();\n private timer?: ReturnType<typeof setInterval>;\n private round: Promise<void> | null = null;\n private expiredLogged = false;\n\n constructor(options: DependencyWatchdogOptions) {\n const { probes, now, random, ...overrides } = options;\n this.config = { ...DEFAULT_DEPENDENCY_WATCHDOG_CONFIG, ...overrides };\n this.probes = probes;\n this.now = now ?? Date.now;\n const jitter = Math.floor((random ?? Math.random)() * this.config.jitterMs);\n this.thresholdMs = this.config.unhealthyThresholdMs + jitter;\n\n // A dependency counts as unhealthy until its first successful probe, so a\n // process that never reaches its datastore after boot is caught too.\n const startedAt = this.now();\n for (const probe of probes) {\n this.states.set(probe.name, { unhealthySince: startedAt, lastError: 'not checked yet' });\n }\n }\n\n /** Start background probing (an immediate round, then every `intervalMs`). */\n start(): void {\n if (this.timer) return;\n void this.checkNow();\n const timer = setInterval(() => {\n void this.checkNow();\n }, this.config.intervalMs);\n timer.unref?.();\n this.timer = timer;\n }\n\n stop(): void {\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = undefined;\n }\n }\n\n /** Run one probe round; concurrent callers share the round in flight. */\n checkNow(): Promise<void> {\n if (!this.round) {\n this.round = this.runRound().finally(() => {\n this.round = null;\n });\n }\n return this.round;\n }\n\n /** Record a probe outcome observed elsewhere (for example by readiness). */\n record(name: string, healthy: boolean, error?: unknown): void {\n const state = this.states.get(name);\n if (!state) return;\n if (healthy) {\n if (state.unhealthySince !== null) {\n logger.info('[DependencyWatchdog] Dependency recovered', {\n dependency: name,\n unhealthyForMs: this.now() - state.unhealthySince,\n });\n }\n state.unhealthySince = null;\n state.lastError = null;\n return;\n }\n state.unhealthySince ??= this.now();\n state.lastError = error === undefined ? 'reported unhealthy' : errorMessage(error);\n }\n\n /** Liveness verdict from in-memory state only; never touches a dependency. */\n liveness(): LivenessReport {\n const now = this.now();\n const failing: FailingDependency[] = [];\n for (const [name, state] of this.states) {\n if (state.unhealthySince === null) continue;\n const unhealthyForMs = now - state.unhealthySince;\n if (unhealthyForMs > this.thresholdMs) failing.push({ name, unhealthyForMs });\n }\n const alive = !this.config.enabled || failing.length === 0;\n\n if (failing.length > 0 && !this.expiredLogged) {\n this.expiredLogged = true;\n logger.error('[DependencyWatchdog] Dependency unhealthy beyond the watchdog window', {\n enforced: this.config.enabled,\n thresholdMs: this.thresholdMs,\n failing: failing.map((f) => ({\n ...f,\n lastError: this.states.get(f.name)?.lastError ?? null,\n })),\n });\n } else if (failing.length === 0) {\n this.expiredLogged = false;\n }\n\n return { alive, thresholdMs: this.thresholdMs, failing };\n }\n\n private async runRound(): Promise<void> {\n await Promise.all(\n this.probes.map(async (probe) => {\n try {\n const healthy = await this.withTimeout(probe);\n this.record(probe.name, healthy === true);\n } catch (error) {\n this.record(probe.name, false, error);\n }\n })\n );\n }\n\n private async withTimeout(probe: DependencyProbe): Promise<boolean> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n reject(new Error(`probe timed out after ${String(this.config.checkTimeoutMs)}ms`));\n }, this.config.checkTimeoutMs);\n timer.unref?.();\n });\n try {\n return await Promise.race([Promise.resolve().then(() => probe.check()), timeout]);\n } finally {\n clearTimeout(timer);\n }\n }\n}\n\n/** Dependencies the liveness watchdog can watch. */\nexport type WatchdogDependencyName = 'postgres' | 'valkey' | 'pubsub' | 'consumers';\n\n/** `health.watchdog` settings. Every field except `dependencies` is optional. */\nexport interface ServerWatchdogConfig {\n /**\n * Dependencies whose prolonged failure restarts the pod. `consumers` and\n * `pubsub` count as healthy when the process has none registered.\n */\n dependencies: WatchdogDependencyName[];\n /** Additional service-specific probes. */\n probes?: DependencyProbe[];\n /** How long a dependency may stay unhealthy before liveness fails, in ms (minimum 60000). */\n unhealthyThresholdMs?: number;\n /** Upper bound of the random per-process extension of the threshold, in ms. */\n jitterMs?: number;\n /** Interval between background probe rounds, in ms. */\n intervalMs?: number;\n /** Bound on a single probe, in ms. */\n checkTimeoutMs?: number;\n}\n\n/** Where `createServer` reads each watched dependency's health from. */\nexport interface WatchdogSources {\n prisma: () => ReadinessPrisma | undefined;\n valkey: () => Promise<ReadinessCache | undefined> | ReadinessCache | undefined;\n /** Aggregate pubsub health; `undefined` when the process has no pubsub. */\n pubsub: () => { ok: boolean } | undefined;\n /** Aggregate consumer health; `undefined` when the process has no supervised consumer. */\n consumers: () => { ok: boolean } | undefined;\n}\n\n/** Probes for the dependencies a service listed in `health.watchdog`. */\nexport function buildWatchdogProbes(config: ServerWatchdogConfig, sources: WatchdogSources): DependencyProbe[] {\n const probes: DependencyProbe[] = [];\n for (const name of new Set(config.dependencies)) {\n switch (name) {\n case 'postgres':\n probes.push({\n name,\n check: async () => {\n const client = sources.prisma();\n if (!client) return false;\n await client.$queryRaw`SELECT 1`;\n return true;\n },\n });\n break;\n case 'valkey':\n probes.push({\n name,\n check: async () => {\n const client = await sources.valkey();\n if (!client) return false;\n await client.ping();\n return true;\n },\n });\n break;\n case 'pubsub':\n probes.push({ name, check: () => sources.pubsub()?.ok ?? true });\n break;\n case 'consumers':\n probes.push({ name, check: () => sources.consumers()?.ok ?? true });\n break;\n }\n }\n return [...probes, ...(config.probes ?? [])];\n}\n\n/**\n * Build the watchdog for `createServer`, or `undefined` when the service did\n * not opt in. The env (`DEPENDENCY_WATCHDOG_*`) overrides the service settings.\n */\nexport function createServerWatchdog(\n config: ServerWatchdogConfig | undefined,\n sources: WatchdogSources,\n env: Record<string, string | undefined> = process.env\n): DependencyWatchdog | undefined {\n if (!config) return undefined;\n const probes = buildWatchdogProbes(config, sources);\n if (probes.length === 0) return undefined;\n const base: Partial<DependencyWatchdogConfig> = {};\n if (config.unhealthyThresholdMs !== undefined) base.unhealthyThresholdMs = config.unhealthyThresholdMs;\n if (config.jitterMs !== undefined) base.jitterMs = config.jitterMs;\n if (config.intervalMs !== undefined) base.intervalMs = config.intervalMs;\n if (config.checkTimeoutMs !== undefined) base.checkTimeoutMs = config.checkTimeoutMs;\n return new DependencyWatchdog({ ...resolveDependencyWatchdogConfig(env, base), probes });\n}\n\n/**\n * `/health/live` answer: the static liveness body while the watchdog (if any)\n * reports alive, else 503 with the failing dependencies. Reads in-memory state\n * only.\n */\nexport function watchdogLivenessResponse<B extends { status: string }>(\n body: B,\n watchdog: Pick<DependencyWatchdog, 'liveness'> | undefined\n): {\n status: 200 | 503;\n body: B | (Omit<B, 'status'> & { status: 'unavailable'; watchdog: Omit<LivenessReport, 'alive'> });\n} {\n if (!watchdog) return { status: 200, body };\n const report = watchdog.liveness();\n if (report.alive) return { status: 200, body };\n return {\n status: 503,\n body: { ...body, status: 'unavailable', watchdog: { thresholdMs: report.thresholdMs, failing: report.failing } },\n };\n}\n","import { GraphQLError } from 'graphql';\n\nimport type { YogaPlugin } from './types.js';\n\nexport interface UserFacingErrorOptions {\n code: string;\n userMessage: string;\n technicalMessage?: string;\n details?: Record<string, unknown>;\n httpStatus?: number;\n cause?: Error;\n}\n\nexport interface ErrorNormalizationOptions {\n serviceName?: string;\n environment?: string;\n}\n\nexport interface NormalizedErrorState {\n code: string;\n userMessage: string;\n technicalMessage: string;\n extensions: Record<string, unknown>;\n status: number;\n}\n\nexport interface HttpErrorPayload {\n error: string;\n message: string;\n userMessage: string;\n technicalMessage: string;\n code: string;\n extensions: Record<string, unknown>;\n}\n\nexport interface HttpErrorResult {\n status: number;\n body: HttpErrorPayload;\n}\n\nconst DEFAULT_ERROR_CODE = 'INTERNAL_SERVER_ERROR';\nconst DEFAULT_HTTP_STATUS = 500;\n\n// Held in a separately-named const so the literal isn't assigned directly to\n// the `INVALID_PASSWORD` key — that pattern trips sonarjs/no-hardcoded-passwords\n// (a false positive: this is a user-facing message, not a credential).\nconst INVALID_CREDENTIALS_USER_MESSAGE = 'The password you entered is incorrect.';\n\nconst DEFAULT_USER_MESSAGES: Record<string, string> = {\n BAD_REQUEST: 'Please check the request and try again.',\n BAD_USER_INPUT: 'Please check the information and try again.',\n CAPTCHA_FAILED: 'The verification failed. Please try again.',\n CAPTCHA_REQUIRED: 'Please complete the verification to continue.',\n COMPLEXITY_TOO_HIGH: 'This request is too large to process. Please simplify it and try again.',\n CONFLICT: 'This change conflicts with existing data. Please refresh and try again.',\n FORBIDDEN: 'You do not have permission to do that.',\n INTERNAL_SERVER_ERROR: 'Something went wrong. Please try again.',\n INVALID_PASSWORD: INVALID_CREDENTIALS_USER_MESSAGE,\n NOT_FOUND: 'We could not find the requested item.',\n PERMISSION_DENIED: 'You do not have permission to do that.',\n QUOTA_EXCEEDED: \"You've reached your usage limit.\",\n QUOTA_EXHAUSTED: \"You've reached your usage limit.\",\n RATE_LIMITED: 'Too many requests. Please wait a moment and try again.',\n RESOURCE_CAP_EXCEEDED: \"You've reached your plan limit. Upgrade your plan to continue.\",\n STORAGE_QUOTA_EXCEEDED: \"You've reached your storage limit. Upgrade your plan to continue.\",\n TIMEOUT: 'The request took too long. Please try again.',\n UNAUTHENTICATED: 'Please sign in to continue.',\n VALIDATION_ERROR: 'Please check the information and try again.',\n WORKSPACE_REQUIRED: 'Please choose a workspace and try again.',\n};\n\nconst DEFAULT_STATUS_BY_CODE: Record<string, number> = {\n BAD_REQUEST: 400,\n BAD_USER_INPUT: 400,\n CAPTCHA_FAILED: 400,\n CAPTCHA_REQUIRED: 400,\n COMPLEXITY_TOO_HIGH: 400,\n CONFLICT: 409,\n FORBIDDEN: 403,\n INVALID_PASSWORD: 400,\n NOT_FOUND: 404,\n PERMISSION_DENIED: 403,\n QUOTA_EXCEEDED: 429,\n QUOTA_EXHAUSTED: 429,\n RATE_LIMITED: 429,\n RESOURCE_CAP_EXCEEDED: 429,\n STORAGE_QUOTA_EXCEEDED: 429,\n TIMEOUT: 504,\n UNAUTHENTICATED: 401,\n VALIDATION_ERROR: 400,\n WORKSPACE_REQUIRED: 403,\n};\n\nconst SENSITIVE_EXTENSION_KEYS = new Set(['exception', 'originalError', 'stack', 'stacktrace']);\n\nconst TECHNICAL_MESSAGE_PATTERNS = [\n /\\bprisma\\b/i,\n /\\bsql\\b/i,\n /\\bconstraint\\b/i,\n /\\bstack\\b/i,\n /\\bundefined\\b/i,\n /\\bnull\\b/i,\n /\\bECONN[A-Z_]*\\b/,\n /\\bETIMEDOUT\\b/,\n /\\bENOTFOUND\\b/,\n /\\bP\\d{4}\\b/,\n /Cannot (read|set|find|access)/i,\n /Build failed \\(exit \\d+\\)/i,\n /JSON\\.stringify/i,\n];\n\nconst GRAPHQL_VALIDATION_MESSAGE_PATTERNS = [\n /^Syntax Error:/i,\n /^Cannot query field\\b/i,\n /^Cannot return null for non-nullable field\\b/i,\n /^Unknown (argument|directive|type)\\b/i,\n /^Variable \"\\$[^\"]+\" got invalid value/i,\n /^Field \"[^\"]+\" of required type/i,\n /^Field \"[^\"]+\" must not have a selection/i,\n /^Field \"[^\"]+\" must have a selection/i,\n /^Fragment \"[^\"]+\" cannot be spread here/i,\n /^There can be only one/i,\n /Did you mean /i,\n];\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction readString(record: Record<string, unknown>, key: string): string | null {\n const value = record[key];\n return typeof value === 'string' && value.trim().length > 0 ? value : null;\n}\n\nfunction readExtensions(error: unknown): Record<string, unknown> {\n if (!isRecord(error)) return {};\n const extensions = error['extensions'];\n return isRecord(extensions) ? extensions : {};\n}\n\nfunction readOriginalError(error: unknown): Error | undefined {\n if (error instanceof GraphQLError && error.originalError instanceof Error) {\n return error.originalError;\n }\n return undefined;\n}\n\nfunction sanitizeExtensions(extensions: Record<string, unknown>): Record<string, unknown> {\n const sanitized: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(extensions)) {\n if (!SENSITIVE_EXTENSION_KEYS.has(key)) {\n sanitized[key] = value;\n }\n }\n return sanitized;\n}\n\nfunction normalizeCode(code: string | null): string {\n if (!code) return DEFAULT_ERROR_CODE;\n return code\n .trim()\n .replace(/[\\s-]+/g, '_')\n .toUpperCase();\n}\n\nfunction inferCodeFromMessage(message: string): string {\n const lower = message.toLowerCase();\n\n if (GRAPHQL_VALIDATION_MESSAGE_PATTERNS.some((pattern) => pattern.test(message))) {\n return 'BAD_USER_INPUT';\n }\n\n if (\n lower.includes('unauthenticated') ||\n lower.includes('not authenticated') ||\n lower.includes('authentication required') ||\n lower.includes('unauthorized') ||\n lower.includes('please sign in') ||\n lower.includes('sign in to')\n ) {\n return 'UNAUTHENTICATED';\n }\n\n if (lower.includes('workspace context') || lower.includes('switch to a workspace')) {\n return 'WORKSPACE_REQUIRED';\n }\n\n if (\n lower.includes('forbidden') ||\n lower.includes('access denied') ||\n lower.includes('permission denied') ||\n lower.includes('not authorized')\n ) {\n return 'FORBIDDEN';\n }\n\n if (lower.includes('not found') || lower.includes('disappeared')) {\n return 'NOT_FOUND';\n }\n\n if (lower.includes('already exists') || lower.includes('already taken') || lower.includes('conflict')) {\n return 'CONFLICT';\n }\n\n if (lower.includes('quota') || lower.includes('cap exceeded') || lower.includes('limit reached')) {\n return 'QUOTA_EXCEEDED';\n }\n\n if (lower.includes('timeout') || lower.includes('timed out')) {\n return 'TIMEOUT';\n }\n\n if (\n lower.includes('required') ||\n lower.includes('invalid') ||\n lower.includes('missing') ||\n lower.includes('unsupported')\n ) {\n return 'BAD_USER_INPUT';\n }\n\n return DEFAULT_ERROR_CODE;\n}\n\nfunction inferCode(error: unknown, extensions: Record<string, unknown>, originalError: Error | undefined): string {\n const extensionCode = typeof extensions['code'] === 'string' ? extensions['code'] : null;\n if (extensionCode) return normalizeCode(extensionCode);\n\n if (isRecord(originalError)) {\n const originalCode = readString(originalError, 'code');\n if (originalCode) return normalizeCode(originalCode);\n }\n\n if (isRecord(error)) {\n const directCode = readString(error, 'code');\n if (directCode) return normalizeCode(directCode);\n }\n\n const message = readErrorMessage(error);\n return inferCodeFromMessage(message);\n}\n\nfunction readErrorMessage(error: unknown): string {\n if (error instanceof Error && error.message.trim().length > 0) {\n return error.message;\n }\n if (isRecord(error)) {\n const message = readString(error, 'message');\n if (message) return message;\n }\n return DEFAULT_USER_MESSAGES[DEFAULT_ERROR_CODE] ?? 'Something went wrong. Please try again.';\n}\n\nfunction isLikelyTechnicalMessage(message: string): boolean {\n if (message.length > 220) return true;\n if (message.includes('\\n')) return true;\n if (message.includes('{') && message.includes('}')) return true;\n if (GRAPHQL_VALIDATION_MESSAGE_PATTERNS.some((pattern) => pattern.test(message))) return true;\n return TECHNICAL_MESSAGE_PATTERNS.some((pattern) => pattern.test(message));\n}\n\nfunction readExplicitUserMessage(extensions: Record<string, unknown>): string | null {\n return (\n readString(extensions, 'userMessage') ??\n readString(extensions, 'humanMessage') ??\n readString(extensions, 'displayMessage')\n );\n}\n\nfunction resolveUserMessage(code: string, message: string, extensions: Record<string, unknown>): string {\n const explicit = readExplicitUserMessage(extensions);\n if (explicit) return explicit;\n\n const fallback =\n DEFAULT_USER_MESSAGES[code] ??\n DEFAULT_USER_MESSAGES[DEFAULT_ERROR_CODE] ??\n 'Something went wrong. Please try again.';\n if (code === DEFAULT_ERROR_CODE) {\n return fallback;\n }\n\n if (!isLikelyTechnicalMessage(message)) {\n return message;\n }\n\n return fallback;\n}\n\nfunction resolveTechnicalMessage(\n code: string,\n message: string,\n extensions: Record<string, unknown>,\n options: ErrorNormalizationOptions\n): string {\n const explicit = readString(extensions, 'technicalMessage');\n if (explicit) return explicit;\n\n if (options.environment === 'production' && code === DEFAULT_ERROR_CODE) {\n return options.serviceName ? `${options.serviceName} returned ${DEFAULT_ERROR_CODE}` : DEFAULT_ERROR_CODE;\n }\n\n return message;\n}\n\nfunction isValidHttpStatus(status: unknown): status is number {\n return typeof status === 'number' && Number.isInteger(status) && status >= 200 && status <= 599;\n}\n\nfunction isValidErrorStatus(status: unknown): status is number {\n return isValidHttpStatus(status) && status >= 400;\n}\n\nfunction readHttpStatus(extensions: Record<string, unknown>, code: string): number {\n const http = extensions['http'];\n if (isRecord(http) && isValidHttpStatus(http['status'])) {\n return http['status'];\n }\n // Known platform codes keep their canonical status so services that attach a\n // default `statusCode` (often 500) to every error cannot downgrade them.\n const byCode = DEFAULT_STATUS_BY_CODE[code];\n if (byCode !== undefined) {\n return byCode;\n }\n // Domain codes (e.g. E_DATASINK_KEY_EXISTS) are not in the table; honour the\n // `extensions.statusCode` the service attached so 400/409 are not reported as 500.\n const statusCode = extensions['statusCode'];\n if (isValidErrorStatus(statusCode)) {\n return statusCode;\n }\n return DEFAULT_HTTP_STATUS;\n}\n\nexport function normalizeError(error: unknown, options: ErrorNormalizationOptions = {}): NormalizedErrorState {\n const originalError = readOriginalError(error);\n const originalExtensions = readExtensions(originalError);\n const directExtensions = readExtensions(error);\n const mergedExtensions = sanitizeExtensions({ ...originalExtensions, ...directExtensions });\n const message = readErrorMessage(error);\n const code = inferCode(error, mergedExtensions, originalError);\n const userMessage = resolveUserMessage(code, message, mergedExtensions);\n const technicalMessage = resolveTechnicalMessage(code, message, mergedExtensions, options);\n const status = readHttpStatus(mergedExtensions, code);\n\n const extensions: Record<string, unknown> = {\n ...mergedExtensions,\n code,\n userMessage,\n technicalMessage,\n };\n\n if (options.serviceName) {\n extensions['serviceName'] = options.serviceName;\n }\n\n const http = extensions['http'];\n extensions['http'] = { ...(isRecord(http) ? http : {}), status };\n\n return {\n code,\n userMessage,\n technicalMessage,\n extensions,\n status,\n };\n}\n\nexport class UserFacingGraphQLError extends GraphQLError {\n constructor(options: UserFacingErrorOptions) {\n const extensions: Record<string, unknown> = {\n code: normalizeCode(options.code),\n userMessage: options.userMessage,\n technicalMessage: options.technicalMessage ?? options.userMessage,\n };\n\n if (options.details) {\n extensions['details'] = options.details;\n }\n\n if (options.httpStatus) {\n extensions['http'] = { status: options.httpStatus };\n }\n\n super(options.userMessage, {\n originalError: options.cause,\n extensions,\n });\n this.name = 'UserFacingGraphQLError';\n }\n}\n\nexport function toUserFacingGraphQLError(error: unknown, options: ErrorNormalizationOptions = {}): GraphQLError {\n const normalized = normalizeError(error, options);\n\n if (error instanceof GraphQLError) {\n return new GraphQLError(normalized.userMessage, {\n nodes: error.nodes,\n source: error.source,\n positions: error.positions,\n path: error.path,\n originalError: error.originalError,\n extensions: normalized.extensions,\n });\n }\n\n return new GraphQLError(normalized.userMessage, {\n originalError: error instanceof Error ? error : undefined,\n extensions: normalized.extensions,\n });\n}\n\nexport function normalizeExecutionResultErrors(result: unknown, options: ErrorNormalizationOptions = {}): void {\n if (Array.isArray(result)) {\n result.forEach((entry) => normalizeExecutionResultErrors(entry, options));\n return;\n }\n\n if (!isRecord(result)) return;\n const errors = result['errors'];\n if (!Array.isArray(errors) || errors.length === 0) return;\n\n result['errors'] = errors.map((error) => toUserFacingGraphQLError(error, options));\n}\n\nexport function normalizeGraphQLResponsePayload(payload: unknown, options: ErrorNormalizationOptions = {}): unknown {\n normalizeExecutionResultErrors(payload, options);\n return payload;\n}\n\n// Yoga consumes extensions.http when serializing. Preserve the actual transport\n// status for custom domain codes before the final JSON normalization; otherwise\n// an accurate 4xx/5xx response acquires a contradictory default 500 in its body.\n// Known codes retain their established mapping, and uncategorized internal errors\n// never inherit a client-error status merely because they share a response.\nfunction restoreSerializedHttpStatuses(payload: unknown, responseStatus: number): void {\n if (Array.isArray(payload)) {\n payload.forEach((entry) => restoreSerializedHttpStatuses(entry, responseStatus));\n return;\n }\n if (!isRecord(payload) || !Array.isArray(payload['errors'])) return;\n\n for (const error of payload['errors']) {\n if (!isRecord(error)) continue;\n const extensions = readExtensions(error);\n const http = extensions['http'];\n if (isRecord(http) && isValidHttpStatus(http['status'])) continue;\n const code = inferCode(error, extensions, undefined);\n const status =\n DEFAULT_STATUS_BY_CODE[code] ??\n (code !== DEFAULT_ERROR_CODE && responseStatus >= 400 ? responseStatus : DEFAULT_HTTP_STATUS);\n error['extensions'] = { ...extensions, http: { ...(isRecord(http) ? http : {}), status } };\n }\n}\n\nexport async function normalizeGraphQLResponse(\n response: Response,\n options: ErrorNormalizationOptions = {}\n): Promise<Response> {\n const contentType = response.headers.get('content-type') ?? '';\n if (!contentType.toLowerCase().includes('json')) {\n return response;\n }\n\n const text = await response.text();\n if (!text) {\n return new Response(text, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n }\n\n let payload: unknown;\n try {\n payload = JSON.parse(text) as unknown;\n } catch {\n return new Response(text, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n }\n\n restoreSerializedHttpStatuses(payload, response.status);\n normalizeGraphQLResponsePayload(payload, options);\n\n return new Response(JSON.stringify(payload), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n}\n\nexport function createHumanReadableErrorPlugin(options: ErrorNormalizationOptions = {}): YogaPlugin {\n return {\n onExecute() {\n return {\n onExecuteDone({ result }: { result: unknown }) {\n normalizeExecutionResultErrors(result, options);\n },\n };\n },\n };\n}\n\nexport function formatHttpError(error: unknown, options: ErrorNormalizationOptions = {}): HttpErrorResult {\n const normalized = normalizeError(error, options);\n return {\n status: normalized.status,\n body: {\n error: normalized.userMessage,\n message: normalized.userMessage,\n userMessage: normalized.userMessage,\n technicalMessage: normalized.technicalMessage,\n code: normalized.code,\n extensions: normalized.extensions,\n },\n };\n}\n\nexport function createHttpErrorResponse(error: unknown, options: ErrorNormalizationOptions = {}): Response {\n const formatted = formatHttpError(error, options);\n return new Response(JSON.stringify(formatted.body), {\n status: formatted.status,\n headers: { 'Content-Type': 'application/json' },\n });\n}\n","/**\n * Server Module\n *\n * Main server bootstrapping with Elysia, GraphQL Yoga, and middleware.\n * Uses Bun runtime for high-performance GraphQL services.\n *\n * Provides a simple API for microservices to start a fully configured server.\n */\n\nimport { logger } from '../logger/index.js';\nimport { configureAuth, configureDefaultAuth, type FetchWorkspaceSecretFn } from './auth.js';\nimport { configureContext, buildContext } from './context.js';\nimport { createWorkspaceExecutionContextPlugin, runWithServerWorkspaceContext } from './workspace-execution-context.js';\nimport type {\n ServerDefinition,\n ServerInstance,\n ServerInfo,\n ElysiaApp,\n BunServerHandle,\n YogaPlugin,\n GraphQLContext,\n} from './types.js';\nimport { I18n } from '../i18n/index.js';\nimport { canAccessGraphExport, normalizeCorsOrigins, resolveAllowedCorsOrigin } from './security.js';\nimport { getMetricsRegistry } from '../instrumentation/metrics-collector.js';\nimport { getWorkspaceQuotaRegistry } from '../metrics/index.js';\nimport { createQuotaGaugeRefresher } from './quotaGaugeRefresh.js';\nimport { collectPromDefaultMetrics, type PromDefaultMetricsClient } from '../telemetry/bun-runtime-metrics.js';\nimport {\n DEFAULT_RAW_BODY_MAX_BYTES,\n PayloadTooLargeError,\n createRawBodyRouter,\n readBoundedRawBody,\n rememberRequestServer,\n resolveBodyLimitBytes,\n resolveMaxRequestBodySize,\n} from './raw-body-routes.js';\nimport {\n createReadinessProbe,\n livenessBody,\n readinessBody,\n readinessStatusCode,\n type ReadinessCache,\n type ReadinessDeps,\n} from './readiness.js';\nimport { getPubSubHealth } from '../graphql/pubsub-health.js';\nimport { withIncomingRequestSpan } from '../telemetry/incoming-request-span.js';\nimport { getConsumerHealth } from '../event-queue/consumer-health.js';\nimport { createServerWatchdog, watchdogLivenessResponse } from './dependency-watchdog.js';\nimport {\n createHttpErrorResponse,\n createHumanReadableErrorPlugin,\n formatHttpError,\n normalizeGraphQLResponse,\n} from './errors.js';\n\n// Store startup time for uptime calculation\nlet serverStartTime: Date | null = null;\n\n// Workspace quota gauges cost Prisma groupBy queries, so /metrics refreshes\n// them on a TTL rather than on every scrape. See ./quotaGaugeRefresh.ts.\nconst quotaGaugeRefresher = createQuotaGaugeRefresher({\n collect: () => getWorkspaceQuotaRegistry().collectAll(),\n});\n\n/**\n * Create and configure a server instance using Elysia + GraphQL Yoga\n */\nexport async function createServer(definition: ServerDefinition): Promise<ServerInstance> {\n const {\n config,\n prismaClient,\n schema,\n moduleGraph,\n restEndpoints,\n yogaPlugins,\n buildContext: customBuildContext,\n workspaceExtensionConfig,\n disableWorkspaceExtension,\n onShutdown,\n } = definition;\n\n // Dynamic imports to avoid requiring these as hard dependencies\n const { Elysia } = await import('elysia');\n const { BunAdapter } = await import('elysia/adapter/bun');\n const { cors } = await import('@elysiajs/cors');\n const { createYoga } = await import('graphql-yoga');\n const { initializeDatabase, getDb, getDatabaseManager } = await import('../prisma/index.js');\n const { createSecurityPlugin } = await import('../middleware/index.js');\n const { createMetricsPlugin } = await import('../observability/index.js');\n const { createWorkspaceGuardPlugin } = await import('./workspace-guard.js');\n\n logger.info(`[Server] Initializing ${config.serviceName}...`);\n\n // Detect boundary from config or service name — needed before database and guard setup\n const boundary =\n config.boundary ??\n (config.serviceName.startsWith('wspace-')\n ? 'wspace'\n : config.serviceName.startsWith('global-')\n ? 'global'\n : 'wspace'); // fail-closed: default to wspace (stricter)\n\n // Initialize database\n // Workspace extension is auto-disabled for global boundary services unless explicitly enabled\n const shouldEnableWorkspaceExtension =\n disableWorkspaceExtension === true ? false : disableWorkspaceExtension === false ? true : boundary === 'wspace'; // auto-detect: enabled for wspace, disabled for global\n\n logger.info('[Server] Initializing database...', {\n boundary,\n workspaceExtension: shouldEnableWorkspaceExtension,\n });\n\n const { connect } = initializeDatabase(prismaClient, config.serviceName, {\n registerShutdownHandlers: false, // Server manages shutdown handlers itself\n enableWorkspaceExtension: shouldEnableWorkspaceExtension,\n ...(workspaceExtensionConfig ? { workspaceExtensionConfig } : {}),\n });\n await connect();\n\n // Initialize i18n if configured\n let i18nInstance: I18n | undefined;\n if (config.i18n?.enabled && config.i18n.localesPath) {\n logger.info('[Server] Initializing i18n...');\n i18nInstance = new I18n({\n defaultLocale: config.i18n.defaultLocale || 'en-US',\n fallbackLocale: config.i18n.fallbackLocale || 'en-US',\n localesPath: config.i18n.localesPath,\n supportedLocales: config.i18n.supportedLocales,\n namespace: config.i18n.namespace || config.serviceName,\n lazyLoad: config.i18n.lazyLoad,\n logMissing: config.i18n.logMissing ?? true,\n enableCache: true,\n returnKeyOnMissing: true,\n });\n await i18nInstance.initialize();\n logger.info(`[Server] i18n initialized with locales: ${i18nInstance.getSupportedLocales().join(', ')}`);\n }\n\n // Configure context builder\n configureContext({\n getDb: () => getDb(),\n i18n: i18nInstance,\n });\n\n // Auto-configure auth with default workspace secret fetcher if not already configured\n configureDefaultAuth();\n\n // Initialize module graph if provided\n if (moduleGraph) {\n logger.info('[Server] Initializing module graph...');\n await moduleGraph.initialize();\n }\n\n // Determine if playground/introspection should be enabled\n const isDev = config.environment !== 'production';\n const enablePlayground = config.enablePlayground ?? isDev;\n\n // Enable GraphQL-over-HTTP batching by default so subgraphs accept the batched\n // array POSTs the federation gateway forwards from Apollo Client BatchHttpLink.\n // The default limit (10) matches the workspace gateway's batching limit.\n const batching = config.batching ?? true;\n\n // Build workspace guard plugin — auto-enabled for wspace boundary only\n const workspaceGuardEnabled = config.workspaceGuard?.enabled ?? boundary === 'wspace';\n logger.info(`[Server] Boundary: ${boundary}, workspace guard: ${workspaceGuardEnabled ? 'enabled' : 'disabled'}`);\n\n const workspaceGuardPlugins = workspaceGuardEnabled\n ? [\n createWorkspaceGuardPlugin({\n enabled: true,\n whitelistedOperations: config.workspaceGuard?.whitelistedOperations,\n whitelistedFields: config.workspaceGuard?.whitelistedFields,\n validateWorkspaceMembership: config.workspaceGuard?.validateWorkspaceMembership,\n }),\n ]\n : [];\n\n // Create GraphQL Yoga instance\n const graphqlEndpoint = config.graphqlEndpoint || '/graphql';\n logger.info('[Server] Setting up GraphQL Yoga with provided schema...', {\n batching,\n });\n\n const responseHeadersPlugin: YogaPlugin = {\n onResponse: ({ response, serverContext }: { response: Response; serverContext: unknown }) => {\n const yogaContext = serverContext as GraphQLContext;\n if (yogaContext?.responseHeaders) {\n yogaContext.responseHeaders.forEach((value: string, key: string) => {\n response.headers.append(key, value);\n });\n }\n },\n };\n\n const yoga = createYoga<{ request: Request }>({\n graphqlEndpoint,\n schema, // Use the schema provided by microservice\n graphiql: enablePlayground,\n batching,\n logging: {\n debug: (...args) => logger.debug('[GraphQL]', ...args),\n info: (...args) => logger.info('[GraphQL]', ...args),\n warn: (...args) => logger.warn('[GraphQL]', ...args),\n error: (...args) => logger.error('[GraphQL]', ...args),\n },\n plugins: [\n createHumanReadableErrorPlugin({ serviceName: config.serviceName, environment: config.environment }),\n ...workspaceGuardPlugins,\n responseHeadersPlugin,\n ...(yogaPlugins || []),\n // Consumers such as GraphQL Modules replace execute/subscribe; bind their final functions.\n createWorkspaceExecutionContextPlugin(),\n ],\n context: async ({ request }) => {\n // Build default context\n const defaultContext = await buildContext(request);\n\n // Apply custom context builder if provided\n if (customBuildContext) {\n return customBuildContext(defaultContext);\n }\n\n return defaultContext;\n },\n });\n\n // Create Elysia instance with Bun adapter\n const app = new Elysia({ adapter: BunAdapter });\n\n // Register CORS middleware\n const corsOrigins = normalizeCorsOrigins(config.corsOrigins, config.environment);\n\n app.use(\n cors({\n origin: corsOrigins,\n credentials: corsOrigins.length > 0,\n allowedHeaders: [\n 'Content-Type',\n 'Authorization',\n 'X-Tenant-ID',\n 'X-Workspace-ID',\n 'X-Org-ID',\n 'X-Project-ID',\n 'X-Product-ID',\n 'X-CSRF-Token',\n 'X-Service-Name',\n 'Accept-Language',\n 'X-Locale',\n 'X-Language',\n 'X-Geo-Country',\n 'X-Geo-Currency',\n 'X-Geo-Timezone',\n // Actor headers (gateway-injected or dev mode)\n 'X-Actor-ID',\n 'X-Actor-Type',\n 'X-Internal-Service-Token',\n 'X-Gateway-Auth-Token',\n ],\n methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],\n })\n );\n\n // Raw-body endpoints (webhooks) are served in onRequest, before Elysia parses the body, so they\n // get their own router — keyed on path AND method (BOFF-7766).\n const rawBodyRouter = createRawBodyRouter(restEndpoints || [], () => app.routes);\n const defaultRawBodyMaxBytes = resolveBodyLimitBytes(config.maxBodyBytes, DEFAULT_RAW_BODY_MAX_BYTES);\n const maxRequestBodySize = resolveMaxRequestBodySize(config, restEndpoints || []);\n\n // Handle GraphQL, metrics, and raw body requests BEFORE any middleware that consumes the body\n // This is critical because Yoga needs the raw request body stream\n // and webhook endpoints need raw body for signature verification\n // onRequest runs before onParse (body parsing) and onBeforeHandle\n app.onRequest(async ({ request, server }) => {\n const url = new URL(request.url);\n const pathname = url.pathname;\n logger.debug(`[Server] onRequest: ${request.method} ${pathname}`);\n const isHealthRoute = pathname === '/health' || pathname.startsWith('/health/');\n\n // Build CORS headers helper\n const buildCorsHeaders = (): Record<string, string> => {\n const origin = request.headers.get('origin') || '*';\n const allowedOrigin = resolveAllowedCorsOrigin(origin === '*' ? null : origin, corsOrigins);\n const headers: Record<string, string> = {\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers':\n 'Content-Type, Authorization, X-Tenant-ID, X-Workspace-ID, X-Org-ID, X-Project-ID, X-Product-ID, X-CSRF-Token, X-Service-Name, Accept-Language, X-Locale, X-Language, X-Geo-Country, X-Geo-Currency, X-Geo-Timezone, X-Actor-ID, X-Actor-Type, X-Internal-Service-Token, X-Gateway-Auth-Token',\n };\n\n if (allowedOrigin) {\n headers['Access-Control-Allow-Origin'] = allowedOrigin;\n headers['Access-Control-Allow-Credentials'] = 'true';\n }\n\n return headers;\n };\n\n // Raw-body endpoints (webhooks). One path may serve several verbs, each its own handler.\n if (!isHealthRoute && rawBodyRouter.size > 0 && rawBodyRouter.hasPath(pathname)) {\n const corsHeaders = buildCorsHeaders();\n\n // Handle CORS preflight for raw body endpoints\n if (request.method === 'OPTIONS') {\n return new Response(null, {\n status: 204,\n headers: corsHeaders,\n });\n }\n\n const resolution = rawBodyRouter.resolve(pathname, request.method);\n // An ordinary route serves this method on the same path: let Elysia handle it.\n if (!resolution) return undefined;\n\n if (resolution.kind === 'method-not-allowed') {\n return new Response(\n JSON.stringify({ error: `Method ${request.method} is not allowed`, allowed: resolution.allowed }),\n {\n status: 405,\n headers: { 'Content-Type': 'application/json', Allow: resolution.allowed.join(', '), ...corsHeaders },\n }\n );\n }\n\n const rawBodyEndpoint = resolution.endpoint;\n logger.debug(`[Server] Matched raw body endpoint: ${request.method} ${pathname} -> ${rawBodyEndpoint.path}`);\n // Lets the handler extend this request's idle timeout (extendRequestIdleTimeout).\n rememberRequestServer(request, server);\n const isHead = request.method === 'HEAD';\n\n try {\n // Read raw body BEFORE any parsing, bounded to prevent pre-auth memory exhaustion (BOFF-16046)\n const endpointMaxBodyBytes = resolveBodyLimitBytes(rawBodyEndpoint.maxBodyBytes, defaultRawBodyMaxBytes);\n const rawBody = await readBoundedRawBody(request, endpointMaxBodyBytes);\n\n // Build context without consuming body (body already read)\n const context = await buildContext(request);\n\n // Call the handler with raw body\n const result = await runWithServerWorkspaceContext(context, async () =>\n rawBodyEndpoint.handler(request, context, rawBody)\n );\n\n // If handler returns a Response, use it directly\n if (result instanceof Response) {\n // Add CORS headers\n const headers = new Headers(result.headers);\n for (const [key, value] of Object.entries(corsHeaders)) {\n headers.set(key, value);\n }\n // A HEAD served by the GET handler carries its headers, never its body.\n return new Response(isHead ? null : result.body, {\n status: result.status,\n statusText: result.statusText,\n headers,\n });\n }\n\n // Otherwise, serialize as JSON\n const headers = new Headers({\n 'Content-Type': 'application/json',\n ...corsHeaders,\n });\n\n return new Response(isHead ? null : JSON.stringify(result), {\n status: 200,\n headers,\n });\n } catch (error) {\n if (error instanceof PayloadTooLargeError) {\n logger.warn(`[Server] Raw body endpoint payload too large (${pathname})`, {\n maxBodyBytes: error.maxBodyBytes,\n });\n return new Response(\n isHead\n ? null\n : JSON.stringify({\n error: 'Payload too large',\n code: error.code,\n maxBodyBytes: error.maxBodyBytes,\n }),\n {\n status: 413,\n headers: {\n 'Content-Type': 'application/json',\n ...corsHeaders,\n },\n }\n );\n }\n logger.error(`[Server] Raw body endpoint error (${pathname}):`, error);\n const formatted = formatHttpError(error, {\n serviceName: config.serviceName,\n environment: config.environment,\n });\n return new Response(isHead ? null : JSON.stringify(formatted.body), {\n status: formatted.status,\n headers: {\n 'Content-Type': 'application/json',\n ...corsHeaders,\n },\n });\n }\n }\n\n // Serve Prometheus metrics via prom-client at /metrics.\n // The graphql-yoga prometheus plugin populates the same default registry,\n // so GraphQL-level metrics (operation durations, error counts, etc.) are\n // included automatically without needing Yoga to handle this route.\n //\n // Also includes SDK MetricsRegistry metrics (business counters/histograms\n // created via @burdenoff/be-sdk/instrumentation factories) so that custom\n // service metrics are available without a separate /api/metrics endpoint.\n if (pathname === '/metrics' && request.method === 'GET') {\n try {\n const promClientMod = 'prom-client';\n const prom = (await import(promClientMod)) as unknown as PromDefaultMetricsClient & {\n register: { metrics: () => Promise<string> | string; contentType?: string };\n };\n // Under Bun this leaves out the heap-space gauges, whose collect walks the heap (BOFF-12287).\n collectPromDefaultMetrics(prom);\n const promBody = await prom.register.metrics();\n\n // Append SDK MetricsRegistry metrics (business counters, histograms,\n // gauges) that are created via @burdenoff/be-sdk/instrumentation\n // factories. The toPrometheusFormat() method is deliberately not cached\n // — each scrape gets a fresh snapshot including dynamic label values.\n //\n // Workspace quota gauges are different: collectAll() issues Prisma\n // groupBy queries, so running it inline on every scrape made /metrics\n // as slow as the database. Services registering quota collectors\n // routinely blew a 30s Prometheus scrape_timeout and reported as down.\n // Refresh on a TTL and bound each refresh, so a slow or unavailable\n // database degrades gauge freshness instead of failing the scrape.\n let sdkBody = '';\n await quotaGaugeRefresher.refresh();\n try {\n sdkBody = getMetricsRegistry().toPrometheusFormat();\n } catch {\n /* MetricsRegistry not initialised; serve prom-client output alone */\n }\n\n const combined = sdkBody ? `${promBody}\\n${sdkBody}` : promBody;\n return new Response(combined, {\n status: 200,\n headers: {\n 'Content-Type': prom.register.contentType ?? 'text/plain; version=0.0.4; charset=utf-8',\n },\n });\n } catch {\n // fall through — prom-client not installed; let Yoga handle as fallback\n }\n }\n\n // Routes that should be handled by Yoga (GraphQL endpoint only)\n const yogaRoutes = [graphqlEndpoint, `${graphqlEndpoint}/`, '/metrics'];\n const shouldHandleByYoga = yogaRoutes.includes(pathname);\n\n if (shouldHandleByYoga) {\n const corsHeaders = buildCorsHeaders();\n\n // Handle CORS preflight\n if (request.method === 'OPTIONS') {\n return new Response(null, {\n status: 204,\n headers: corsHeaders,\n });\n }\n\n // Get response from Yoga inside a SERVER span that continues the\n // gateway's trace (BOFF-17552): Bun.serve requests are not seen by\n // OpenTelemetry's http instrumentation, so without this no span was\n // created and `traceparent` was never extracted.\n const yogaResponse = await withIncomingRequestSpan(request, graphqlEndpoint, async () =>\n normalizeGraphQLResponse(await yoga.fetch(request), {\n serviceName: config.serviceName,\n environment: config.environment,\n })\n );\n\n // Add CORS headers to Yoga response\n const headers = new Headers(yogaResponse.headers);\n for (const [key, value] of Object.entries(corsHeaders)) {\n headers.set(key, value);\n }\n\n // Return response with CORS headers\n return new Response(yogaResponse.body, {\n status: yogaResponse.status,\n statusText: yogaResponse.statusText,\n headers,\n });\n }\n // Return undefined to continue to next handlers for non-GraphQL requests\n return undefined;\n });\n\n // Register metrics middleware (after GraphQL interception)\n app.use(createMetricsPlugin());\n\n // Register security middleware (after GraphQL interception)\n app.use(\n createSecurityPlugin({\n csrfSkipRoutes: config.csrfSkipRoutes || ['/graphql', '/health', '/api/graph/'],\n loginEndpoints: config.loginEndpoints || [],\n enableCSRF: config.enableCSRF ?? false, // Disabled by default for GraphQL services\n enableSessionSecurity: config.enableSessionSecurity ?? false,\n })\n );\n\n // Health check endpoints. Rationale for the required/optional split and for\n // keeping liveness shallow lives in ./readiness.ts — read it before changing\n // which dependency is required.\n //\n // /health aggregate: 200 healthy / 200 degraded / 503 unavailable\n // /health/live Kubernetes liveness — process only, never a dependency\n // /health/ready Kubernetes readiness — 503 when a REQUIRED dep is down\n // /health/startup Kubernetes startup — process only, same as liveness\n const serviceVersion = config.serviceVersion || '1.0.0';\n const valkeySource = async (): Promise<ReadinessCache | undefined> => {\n // Optional: services that never configured Valkey must not be marked\n // degraded for not having one, so an unconfigured client is not an error.\n try {\n const { getValkeyClient } = await import('../cache/index.js');\n return await getValkeyClient();\n } catch {\n return undefined;\n }\n };\n const getReadiness = createReadinessProbe({\n prisma: () => getDb(),\n valkey: valkeySource,\n // Reported only when the service created a Redis Streams pubsub.\n pubsub: () => getPubSubHealth(),\n // Reported only when the service started a supervised consumer (BOFF-17231).\n consumers: () => getConsumerHealth(),\n ...(config.health?.requiredDependencies ? { requiredDependencies: config.health.requiredDependencies } : {}),\n } satisfies ReadinessDeps);\n\n // Opt-in liveness watchdog (BOFF-17231): restarts a pod whose listed\n // dependency stayed unhealthy past a bounded window. The handler reads the\n // watchdog's in-memory state only, so liveness never waits on a datastore.\n const watchdog = createServerWatchdog(config.health?.watchdog, {\n prisma: () => getDb(),\n valkey: valkeySource,\n pubsub: () => getPubSubHealth(),\n consumers: () => getConsumerHealth(),\n });\n\n const shallow = (): unknown => livenessBody(config.serviceName, serviceVersion, new Date().toISOString());\n\n const live = (ctx: unknown): unknown => {\n const { status, body } = watchdogLivenessResponse(\n livenessBody(config.serviceName, serviceVersion, new Date().toISOString()),\n watchdog\n );\n const ctxWithSet = ctx as { set?: { status?: number } };\n if (ctxWithSet.set) ctxWithSet.set.status = status;\n return body;\n };\n\n const deep = async (ctx: unknown): Promise<unknown> => {\n const snapshot = await getReadiness();\n const ctxWithSet = ctx as { set?: { status?: number } };\n const code = readinessStatusCode(snapshot);\n if (ctxWithSet.set) ctxWithSet.set.status = code;\n return readinessBody(\n snapshot,\n config.serviceName,\n serviceVersion,\n new Date().toISOString(),\n Math.round(process.uptime())\n );\n };\n\n app.get('/health', deep);\n app.get('/health/live', live);\n app.get('/health/ready', deep);\n app.get('/health/startup', shallow);\n\n // Graph API endpoints (if moduleGraph provided)\n if (moduleGraph) {\n // Get graph configuration schema\n app.get('/api/graph/schema', async ({ request, set }) => {\n const context = await buildContext(request);\n if (!canAccessGraphExport(context.actor)) {\n set.status = 403;\n return { error: 'Forbidden' };\n }\n\n return moduleGraph.getSchema();\n });\n\n // Export all graph data\n app.get('/api/graph/export', async ({ query, request, set }) => {\n const context = await buildContext(request);\n if (!canAccessGraphExport(context.actor)) {\n set.status = 403;\n return { error: 'Forbidden' };\n }\n\n const { organizationId, workspaceId } = query as { organizationId?: string; workspaceId?: string };\n return runWithServerWorkspaceContext(context, () => moduleGraph.exportAll(organizationId, workspaceId));\n });\n\n // Export entities only\n app.get('/api/graph/entities', async ({ query, request, set }) => {\n const context = await buildContext(request);\n if (!canAccessGraphExport(context.actor)) {\n set.status = 403;\n return { error: 'Forbidden' };\n }\n\n const { organizationId, workspaceId, types } = query as {\n organizationId?: string;\n workspaceId?: string;\n types?: string;\n };\n const entityTypes = types?.split(',').map((t) => t.trim());\n return runWithServerWorkspaceContext(context, () =>\n moduleGraph.exportEntities(organizationId, workspaceId, entityTypes)\n );\n });\n\n // Export relationships only\n app.get('/api/graph/relationships', async ({ query, request, set }) => {\n const context = await buildContext(request);\n if (!canAccessGraphExport(context.actor)) {\n set.status = 403;\n return { error: 'Forbidden' };\n }\n\n const { organizationId, workspaceId } = query as { organizationId?: string; workspaceId?: string };\n return runWithServerWorkspaceContext(context, () => moduleGraph.exportRelationships(organizationId, workspaceId));\n });\n }\n\n // Register custom REST endpoints (skip rawBody endpoints - they're handled in onRequest)\n if (restEndpoints && restEndpoints.length > 0) {\n for (const endpoint of restEndpoints) {\n // Skip rawBody endpoints - they're intercepted in onRequest before body parsing\n if (endpoint.rawBody) {\n logger.info(`[Server] Raw body endpoint registered: ${endpoint.method} ${endpoint.path}`);\n continue;\n }\n\n const handler = async ({ request }: { request: Request }): Promise<unknown> => {\n try {\n const context = await buildContext(request);\n return await runWithServerWorkspaceContext(context, async () => endpoint.handler(request, context));\n } catch (error) {\n logger.error(`[Server] REST endpoint error (${endpoint.path}):`, error);\n return createHttpErrorResponse(error, {\n serviceName: config.serviceName,\n environment: config.environment,\n });\n }\n };\n\n switch (endpoint.method) {\n case 'GET':\n app.get(endpoint.path, handler);\n break;\n case 'POST':\n app.post(endpoint.path, handler);\n break;\n case 'PUT':\n app.put(endpoint.path, handler);\n break;\n case 'PATCH':\n app.patch(endpoint.path, handler);\n break;\n case 'DELETE':\n app.delete(endpoint.path, handler);\n break;\n }\n }\n }\n\n const host = config.host || '0.0.0.0';\n const port = config.port;\n\n // Create server instance\n const serverInstance: ServerInstance = {\n app: app as unknown as ElysiaApp,\n server: null,\n start: async () => {\n serverStartTime = new Date();\n watchdog?.start();\n\n // Call listen() which starts the server and makes app.server available\n app.listen({\n port,\n hostname: host,\n maxRequestBodySize,\n });\n\n // Access the Bun server instance from the app\n // Cast through unknown to satisfy TypeScript since Elysia's types are complex\n const elysiaApp = app as unknown as { server: BunServerHandle | null };\n serverInstance.server = elysiaApp.server;\n\n logger.info(`🚀 ${config.serviceName} is running at http://${host}:${port}${graphqlEndpoint}`);\n },\n stop: async () => {\n logger.info(`[Server] Stopping ${config.serviceName}...`);\n watchdog?.stop();\n\n if (onShutdown) {\n await onShutdown();\n }\n\n if (moduleGraph) {\n await moduleGraph.shutdown();\n }\n\n await getDatabaseManager().disconnect();\n\n if (serverInstance.server) {\n serverInstance.server.stop();\n }\n\n logger.info(`[Server] ${config.serviceName} stopped`);\n },\n getInfo: (): ServerInfo => {\n const uptime = serverStartTime ? Math.floor((Date.now() - serverStartTime.getTime()) / 1000) : 0;\n\n return {\n serviceName: config.serviceName,\n serviceVersion: config.serviceVersion || '1.0.0',\n environment: config.environment || 'development',\n port,\n host,\n graphqlEndpoint,\n startedAt: serverStartTime?.toISOString() || '',\n uptime,\n };\n },\n };\n\n // Setup graceful shutdown handlers\n const gracefulShutdown = async (signal: string): Promise<never> => {\n logger.info(`[Server] ${signal} received, shutting down gracefully...`);\n await serverInstance.stop();\n process.exit(0);\n };\n\n process.on('SIGTERM', () => {\n void gracefulShutdown('SIGTERM');\n });\n process.on('SIGINT', () => {\n void gracefulShutdown('SIGINT');\n });\n\n return serverInstance;\n}\n\n/**\n * Configure auth with workspace secret fetcher\n *\n * This should be called before creating the server if using workspace-scoped JWT\n */\nexport function configureServerAuth(fetchWorkspaceSecret: FetchWorkspaceSecretFn): void {\n configureAuth({ fetchWorkspaceSecret });\n}\n","/**\n * Workspace Guard Plugin for GraphQL Yoga\n *\n * Blocks GraphQL operations that lack a valid workspace context (x-workspace-id header).\n * This provides defense-in-depth at the GraphQL layer — even if the gateway allows a request\n * through, the service itself will reject it if workspace context is missing.\n *\n * **Whitelisted operations** (e.g., workspace creation) can bypass the guard.\n *\n * **Public schema fields** marked with `@public` or `@rbac(public: true)` are auto-bypassed\n * when `allowPublicDirective` is enabled (default true). This lets anonymous public-link\n * resolvers (e.g. `accessShare`) be reached through the federation gateway without an\n * `x-workspace-id` header.\n *\n * @module server/workspace-guard\n * @category Security\n */\n\nimport { logger } from '../logger/index.js';\nimport { UserFacingGraphQLError } from './errors.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Configuration for the workspace guard plugin\n */\nexport interface WorkspaceGuardConfig {\n /**\n * Enable the workspace guard.\n * @default true\n */\n enabled?: boolean;\n\n /**\n * GraphQL operation names that can run without workspace context.\n * These are typically operations like `createWorkspace` that execute\n * before a workspace exists.\n *\n * Matching is case-sensitive against the operation name in the GraphQL document.\n *\n * @deprecated Prefer `whitelistedFields`: operation names are client-supplied\n * strings, so any client that names its operation differently (or sends an\n * anonymous operation) is rejected even when every root field it requests is\n * genuinely context-free. `whitelistedFields` matches on the root field names\n * resolved from the parsed document, which is a property of the schema, not\n * of the client's request.\n *\n * @default []\n *\n * @example\n * ```typescript\n * whitelistedOperations: ['createWorkspace', 'validateTokens']\n * ```\n */\n whitelistedOperations?: string[];\n\n /**\n * Root field names (Query/Mutation/Subscription fields) that can run without\n * workspace context — e.g. `myWorkspaces`, which bootstraps workspace\n * discovery before any workspace has been chosen.\n *\n * Matching is done against the root field names resolved from the parsed\n * GraphQL document for the executed operation, completely independent of the\n * client-supplied `operationName`: anonymous operations, persisted queries\n * and arbitrarily named operations all behave identically.\n *\n * An operation is exempt only when EVERY root field it selects is listed\n * here (or is public per the schema directives). A document that mixes an\n * exempt field with a guarded field is NOT exempt. Fragment spreads at the\n * root fail closed (not exempt).\n *\n * @default []\n *\n * @example\n * ```typescript\n * whitelistedFields: ['myWorkspaces', 'createWorkspace']\n * ```\n */\n whitelistedFields?: string[];\n\n /**\n * Optional membership validation for requests that DO carry a workspace\n * context (`x-workspace-id`). Without this, the guard only checks that a\n * workspace id is present — any well-formed UUID passes, which looks like\n * authorization but performs none.\n *\n * When provided, the callback is invoked with the resolved actor and\n * workspace id for every guarded request; returning `false` rejects the\n * request with `NOT_FOUND` (per the platform RBAC guide: never leak resource\n * existence to non-members). Returning `true` (or omitting this callback)\n * preserves the legacy accept-any-present-workspace-id behaviour.\n *\n * The callback is NOT invoked for operations exempted via\n * `whitelistedOperations`, `whitelistedFields` or the public-directive\n * bypass — context-free bootstrap fields stay reachable regardless.\n *\n * The service that owns the `Workspace`/`WorkspaceMember` entities wires\n * this; the SDK never derives membership itself.\n *\n * @default undefined\n */\n validateWorkspaceMembership?: (validation: WorkspaceMembershipValidation) => boolean | Promise<boolean>;\n\n /**\n * Custom error message when workspace context is missing.\n * @default 'Workspace context required. Provide a valid X-Workspace-Authorization header.'\n */\n errorMessage?: string;\n\n /**\n * If true, fields whose schema definition carries the `@public` directive or\n * `@rbac(public: true)` are bypassed by the guard automatically — no need to\n * list them in `whitelistedOperations`. The check uses the GraphQL schema\n * passed to the executor at request time.\n *\n * Set to false to fall back to the legacy operation-name allowlist only.\n *\n * @default true\n */\n allowPublicDirective?: boolean;\n}\n\n/**\n * Input for the `validateWorkspaceMembership` callback.\n */\nexport interface WorkspaceMembershipValidation {\n /** Actor id from the gateway-injected identity (`x-actor-id`). */\n actorId: string | null;\n /** Actor type from the gateway-injected identity (`x-actor-type`). */\n actorType: string | null;\n /** The workspace id claimed by `x-workspace-id` (or the actor's workspace). */\n workspaceId: string;\n /** The full GraphQL context value for the request. */\n contextValue: unknown;\n}\n\n// ============================================================================\n// GraphQL Error\n// ============================================================================\n\n/**\n * Workspace required error with proper GraphQL error extensions\n */\nclass WorkspaceRequiredError extends UserFacingGraphQLError {\n constructor(message: string) {\n super({\n code: 'WORKSPACE_REQUIRED',\n userMessage: 'Please choose a workspace and try again.',\n technicalMessage: message,\n httpStatus: 403,\n });\n this.name = 'WorkspaceRequiredError';\n }\n}\n\n/**\n * Rejection for a workspace id the calling actor is not a member of.\n * Per the platform RBAC guide (Type B convention), non-members get\n * NOT_FOUND so resource existence is never leaked.\n */\nclass WorkspaceMembershipError extends UserFacingGraphQLError {\n constructor(workspaceId: string) {\n super({\n code: 'NOT_FOUND',\n userMessage: 'We could not find the requested item.',\n technicalMessage: `Workspace ${workspaceId} was not found for the current actor.`,\n httpStatus: 404,\n });\n this.name = 'WorkspaceMembershipError';\n }\n}\n\n// ============================================================================\n// Schema directive helpers\n// ============================================================================\n\n/**\n * Minimal structural typings for the bits of the GraphQL schema we look at.\n * We avoid importing the GraphQL types directly so the SDK keeps `graphql`\n * as a peer dep without a runtime hard dependency.\n */\ninterface FieldLikeDef {\n astNode?: {\n directives?: ReadonlyArray<{\n name: { value: string };\n arguments?: ReadonlyArray<{\n name: { value: string };\n value: { kind: string; value?: unknown };\n }>;\n }>;\n };\n}\n\ninterface SchemaLike {\n getQueryType?: () => { getFields: () => Record<string, FieldLikeDef> } | null | undefined;\n getMutationType?: () => { getFields: () => Record<string, FieldLikeDef> } | null | undefined;\n getSubscriptionType?: () => { getFields: () => Record<string, FieldLikeDef> } | null | undefined;\n}\n\n/**\n * Returns true iff the field carries either:\n * - `@public` directive, OR\n * - `@rbac(public: true)` directive (any arg-order)\n */\nfunction isFieldPublic(field: FieldLikeDef | undefined): boolean {\n const directives = field?.astNode?.directives;\n if (!directives || directives.length === 0) return false;\n\n for (const dir of directives) {\n const name = dir.name?.value;\n if (name === 'public') return true;\n if (name === 'rbac') {\n const args = dir.arguments ?? [];\n for (const arg of args) {\n if (arg.name?.value === 'public' && arg.value?.kind === 'BooleanValue' && arg.value.value === true) {\n return true;\n }\n }\n }\n }\n return false;\n}\n\ninterface DocumentLike {\n definitions?: ReadonlyArray<{\n kind?: string;\n operation?: string;\n name?: { value?: string };\n selectionSet?: {\n selections?: ReadonlyArray<{\n kind?: string;\n name?: { value?: string };\n }>;\n };\n }>;\n}\n\n/**\n * Resolve the operation type ('query' | 'mutation' | 'subscription') for the\n * primary operation in the document. Falls back to 'query'.\n */\nfunction resolveOperationType(\n document: DocumentLike | undefined,\n operationName: string | null | undefined\n): 'query' | 'mutation' | 'subscription' {\n const defs = document?.definitions ?? [];\n for (const def of defs) {\n if (def.kind !== 'OperationDefinition') {\n // Older parsers may not set kind; fall through to the operation property check below.\n }\n if (def.operation && (!operationName || def.name?.value === operationName)) {\n return def.operation as 'query' | 'mutation' | 'subscription';\n }\n }\n return 'query';\n}\n\n/**\n * Resolve the root field names selected by the operation that will execute\n * (`operationName` identifies it when the document carries multiple\n * operations). Returns null when no operation definition matches, the\n * selection set is empty, or a non-Field selection appears at the root\n * (fragment spreads / inline fragments fail closed — see the public-bypass\n * rationale above). Introspection fields (`__schema`, `__type`) are omitted;\n * an introspection-only operation yields an EMPTY array (not null) so callers\n * can distinguish \"only introspection selected\" from \"fail closed\".\n */\nfunction resolveRootFieldNames(\n document: DocumentLike | undefined,\n operationName: string | null | undefined\n): string[] | null {\n const defs = document?.definitions ?? [];\n const opDef = defs.find((d) => d.operation && (!operationName || d.name?.value === operationName));\n const selections = opDef?.selectionSet?.selections ?? [];\n if (selections.length === 0) return null;\n\n const fieldNames: string[] = [];\n for (const sel of selections) {\n if (sel.kind && sel.kind !== 'Field') return null;\n const fieldName = sel.name?.value;\n if (!fieldName) return null;\n if (fieldName.startsWith('__')) continue;\n fieldNames.push(fieldName);\n }\n return fieldNames;\n}\n\n/**\n * Returns true iff every root field selected by the operation is present in\n * the whitelist set. An empty list (introspection-only operation) is NOT\n * exempt — the whitelist covers named schema fields only. A document mixing\n * an exempt field with a guarded field is NOT exempt either, so an exempt\n * bootstrap field cannot smuggle a guarded one.\n */\nfunction allRootFieldsWhitelisted(rootFieldNames: string[], whitelistedFields: Set<string>): boolean {\n return rootFieldNames.length > 0 && rootFieldNames.every((name) => whitelistedFields.has(name));\n}\n\n/**\n * Returns true iff every root field in the document selection set is marked\n * public on the schema. An empty field list (introspection-only operation) is\n * public — schema discovery never requires workspace context. Null (fail\n * closed: no matching operation, empty selection set, or fragment at the\n * root) is not public.\n */\nfunction allRootFieldsPublic(\n schema: SchemaLike | undefined,\n document: DocumentLike | undefined,\n operationName: string | null | undefined,\n rootFieldNames: string[] | null\n): boolean {\n if (!document) return false;\n if (rootFieldNames === null) return false;\n // Introspection-only operations are always public — schema discovery never\n // requires workspace context, and no schema lookup is needed for it.\n if (rootFieldNames.length === 0) return true;\n if (!schema) return false;\n\n const opType = resolveOperationType(document, operationName);\n let rootType: ReturnType<NonNullable<SchemaLike['getQueryType']>> | undefined;\n if (opType === 'mutation') {\n rootType = schema.getMutationType?.();\n } else if (opType === 'subscription') {\n rootType = schema.getSubscriptionType?.();\n } else {\n rootType = schema.getQueryType?.();\n }\n\n if (!rootType) return false;\n\n const fields = rootType.getFields();\n for (const fieldName of rootFieldNames) {\n const fieldDef = fields[fieldName];\n if (!isFieldPublic(fieldDef)) return false;\n }\n return true;\n}\n\n// ============================================================================\n// Plugin\n// ============================================================================\n\n/**\n * Create a GraphQL Yoga plugin that guards operations requiring workspace context.\n *\n * The plugin inspects the GraphQL context for workspace information (set by the SDK's\n * buildContext from the x-workspace-id header). If missing and the operation is not\n * whitelisted (and not all-public per directive), it throws a WORKSPACE_REQUIRED error.\n *\n * @param config - Guard configuration\n * @returns A Yoga-compatible plugin\n *\n * @example\n * ```typescript\n * import { createWorkspaceGuardPlugin } from '@burdenoff/be-sdk/server';\n *\n * const guardPlugin = createWorkspaceGuardPlugin({\n * whitelistedOperations: ['createWorkspace'],\n * allowPublicDirective: true, // default\n * });\n * ```\n */\nexport function createWorkspaceGuardPlugin(config?: WorkspaceGuardConfig) {\n const enabled = config?.enabled ?? true;\n const whitelistedOperations = new Set(config?.whitelistedOperations ?? []);\n const whitelistedFields = new Set(config?.whitelistedFields ?? []);\n const validateWorkspaceMembership = config?.validateWorkspaceMembership;\n const allowPublicDirective = config?.allowPublicDirective ?? true;\n const errorMessage =\n config?.errorMessage ??\n 'Workspace context required. Ensure the request includes a valid workspace context (x-workspace-id header).';\n\n if (!enabled) {\n logger.info('[WorkspaceGuard] Workspace guard disabled');\n return {};\n }\n\n logger.info('[WorkspaceGuard] Workspace guard enabled', {\n whitelistedOperations: [...whitelistedOperations],\n whitelistedFields: [...whitelistedFields],\n membershipValidation: validateWorkspaceMembership ? 'enabled' : 'disabled',\n allowPublicDirective,\n });\n\n return {\n async onExecute({\n args,\n }: {\n args: {\n schema?: SchemaLike;\n document?: DocumentLike;\n operationName?: string | null;\n contextValue?: {\n actor?: { id?: string; type?: string } | null;\n workspace?: { id?: string };\n request?: Request;\n };\n };\n }) {\n // Extract operation name from args or document\n let operationName = args.operationName;\n\n if (!operationName && args.document?.definitions) {\n for (const def of args.document.definitions) {\n if (def.operation && def.name?.value) {\n operationName = def.name.value;\n break;\n }\n }\n }\n\n // Check if operation is whitelisted by name (legacy, client-supplied name)\n if (operationName && whitelistedOperations.has(operationName)) {\n return undefined;\n }\n\n // Resolve the executed operation's root fields once. Null means fail\n // closed (no matching operation, empty selection set, or fragment at\n // the root); an empty array means an introspection-only operation.\n const rootFieldNames = resolveRootFieldNames(args.document, operationName);\n\n // Check if every root field of the executed operation is whitelisted by\n // FIELD name, resolved from the parsed document — independent of the\n // client-supplied operation name.\n if (whitelistedFields.size > 0 && rootFieldNames && allRootFieldsWhitelisted(rootFieldNames, whitelistedFields)) {\n return undefined;\n }\n\n // Check schema-directive-based public bypass (Option C)\n if (allowPublicDirective && allRootFieldsPublic(args.schema, args.document, operationName, rootFieldNames)) {\n return undefined;\n }\n\n // Check for workspace context\n const context = args.contextValue;\n const workspaceId = context?.workspace?.id;\n\n // Also check the raw header as a fallback\n const headerWorkspaceId = context?.request?.headers?.get?.('x-workspace-id');\n\n if (!workspaceId && !headerWorkspaceId) {\n logger.warn('[WorkspaceGuard] Blocked operation without workspace context', {\n operationName: operationName ?? '<anonymous>',\n });\n throw new WorkspaceRequiredError(errorMessage);\n }\n\n // A workspace id is present. When the service wired a membership\n // validator, the id must denote a workspace the actor actually belongs\n // to — a well-formed but unrelated UUID is rejected with NOT_FOUND so\n // workspace existence is never leaked to non-members. The context id\n // wins only when non-empty; an empty context id falls back to the\n // header (matching the truthiness gate above).\n if (validateWorkspaceMembership) {\n const resolvedWorkspaceId = workspaceId ? workspaceId : (headerWorkspaceId ?? '');\n const actor = context?.actor ?? null;\n let isMember = false;\n try {\n isMember = await validateWorkspaceMembership({\n actorId: actor?.id ?? null,\n actorType: actor?.type ?? null,\n workspaceId: resolvedWorkspaceId,\n contextValue: context,\n });\n } catch (error) {\n // Fail closed: a membership-lookup failure must not admit the request.\n logger.error('[WorkspaceGuard] Workspace membership validation failed', {\n operationName: operationName ?? '<anonymous>',\n workspaceId: resolvedWorkspaceId,\n error,\n });\n throw new WorkspaceMembershipError(resolvedWorkspaceId);\n }\n if (!isMember) {\n logger.warn('[WorkspaceGuard] Rejected non-member workspace context', {\n operationName: operationName ?? '<anonymous>',\n workspaceId: resolvedWorkspaceId,\n actorId: actor?.id ?? null,\n });\n throw new WorkspaceMembershipError(resolvedWorkspaceId);\n }\n }\n\n return undefined;\n },\n };\n}\n","/**\n * Mutation-audit backstop plugin\n *\n * A GraphQL Yoga plugin that writes one generic activity row\n * (`activityType: 'graphql.mutation'`, `resourceType: 'graphql_mutation'`,\n * `resourceId: <comma-joined top-level field names>`) for every mutation that\n * did NOT already record its own activity through an explicit SDK call.\n *\n * It replaces the `src/plugins/mutation-audit-plugin.ts` copy that lived in ~34\n * services. Differences from that copy:\n *\n * - Dedupe. The operation runs inside an explicit-activity scope\n * (`../activity/explicit-activity-scope.ts`). `trackOperation`,\n * `trackerStub.track` and `ActivityModule.log` mark the scope, and so does every\n * service `logAudit` wrapper built on them. A marked operation gets no backstop\n * row, so mounting this plugin never doubles a row a resolver already wrote.\n * Resolvers whose audit goes through a path the SDK cannot see call\n * `suppressMutationAudit()`.\n * - `excludeFields` opts individual mutation fields out entirely.\n * - Top-level fields reached through inline fragments and fragment spreads are\n * counted, and `__typename` is ignored.\n *\n * Dedupe works per operation: a multi-field mutation document where one field\n * records explicitly and another does not gets no backstop row. Clients send one\n * top-level mutation field per operation in practice, so this is the safe side\n * (never a duplicate) of the trade-off.\n *\n * Sensitive keys (password, token, secret, …) are redacted and every preview is\n * bounded in depth, array length, key count and string length.\n *\n * @example\n * ```ts\n * import { createMutationAuditPlugin } from '@burdenoff/be-sdk/server';\n *\n * yogaPlugins: [createMutationAuditPlugin({ serviceName: 'wspace-vibecontrols-svc' })]\n * ```\n */\n\nimport type {\n DocumentNode,\n ExecutionResult,\n FragmentDefinitionNode,\n OperationDefinitionNode,\n SelectionSetNode,\n} from 'graphql';\nimport { Kind, OperationTypeNode } from 'graphql';\nimport type { Plugin } from 'graphql-yoga';\n\nimport {\n createExplicitActivityScope,\n runInExplicitActivityScope,\n type ExplicitActivityScope,\n} from '../activity/explicit-activity-scope.js';\nimport { logger } from '../logger/index.js';\nimport { trackOperation } from '../tracker/stub.js';\n\nexport const MUTATION_AUDIT_ACTIVITY_TYPE = 'graphql.mutation';\nexport const MUTATION_AUDIT_RESOURCE_TYPE = 'graphql_mutation';\n\nexport interface MutationAuditPluginOptions {\n /** Service name recorded in each row's metadata, e.g. `wspace-vibecontrols-svc`. */\n serviceName: string;\n /** Mutation field names that never get a backstop row. */\n excludeFields?: Iterable<string>;\n /**\n * Skip the backstop row when the operation already recorded activity through an\n * explicit SDK call. Default `true`; `false` restores the old always-write behaviour.\n */\n dedupeExplicitActivity?: boolean;\n}\n\nconst SENSITIVE_KEY_MARKERS = [\n 'password',\n 'passcode',\n 'pass',\n 'token',\n 'secret',\n 'apikey',\n 'accesskey',\n 'authorization',\n 'cookie',\n 'credential',\n 'clientsecret',\n 'privatekey',\n];\n\nconst MAX_DEPTH = 2;\nconst MAX_ARRAY_ITEMS = 5;\nconst MAX_OBJECT_KEYS = 20;\nconst MAX_STRING_LENGTH = 200;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isSensitiveKey(key: string): boolean {\n const normalizedKey = key.toLowerCase().replaceAll(/[-_]/g, '');\n return SENSITIVE_KEY_MARKERS.some((marker) => normalizedKey.includes(marker));\n}\n\nfunction truncate(value: string): string {\n return value.length > MAX_STRING_LENGTH ? `${value.slice(0, MAX_STRING_LENGTH)}...` : value;\n}\n\n/** Redact sensitive keys and bound the size of a value before it is stored as metadata. */\nexport function sanitizeAuditValue(value: unknown, depth = 0): unknown {\n if (value == null || typeof value === 'boolean' || typeof value === 'number') {\n return value;\n }\n if (typeof value === 'string') {\n return truncate(value);\n }\n if (depth >= MAX_DEPTH) {\n return '[Truncated]';\n }\n if (Array.isArray(value)) {\n return value.slice(0, MAX_ARRAY_ITEMS).map((entry) => sanitizeAuditValue(entry, depth + 1));\n }\n if (!isRecord(value)) {\n return `[${typeof value}]`;\n }\n\n const sanitized: Record<string, unknown> = {};\n let count = 0;\n for (const [key, entry] of Object.entries(value)) {\n if (count >= MAX_OBJECT_KEYS) {\n sanitized['__truncated__'] = true;\n break;\n }\n sanitized[key] = isSensitiveKey(key) ? '[REDACTED]' : sanitizeAuditValue(entry, depth + 1);\n count += 1;\n }\n return sanitized;\n}\n\nfunction findMutation(document: DocumentNode, operationName?: string | null): OperationDefinitionNode | undefined {\n const operations = document.definitions.filter(\n (definition): definition is OperationDefinitionNode => definition.kind === Kind.OPERATION_DEFINITION\n );\n // graphql-js executes the named operation, or the only one when no name is given.\n let operation: OperationDefinitionNode | undefined;\n if (operationName) {\n operation = operations.find((definition) => definition.name?.value === operationName);\n } else if (operations.length === 1) {\n operation = operations[0];\n }\n return operation?.operation === OperationTypeNode.MUTATION ? operation : undefined;\n}\n\nfunction collectTopLevelFields(\n selectionSet: SelectionSetNode,\n fragments: ReadonlyMap<string, FragmentDefinitionNode>,\n fields: string[],\n visitedFragments: Set<string>\n): void {\n for (const selection of selectionSet.selections) {\n if (selection.kind === Kind.FIELD) {\n const name = selection.name.value;\n if (!name.startsWith('__') && !fields.includes(name)) fields.push(name);\n } else if (selection.kind === Kind.INLINE_FRAGMENT) {\n collectTopLevelFields(selection.selectionSet, fragments, fields, visitedFragments);\n } else {\n const fragmentName = selection.name.value;\n const fragment = fragments.get(fragmentName);\n if (fragment && !visitedFragments.has(fragmentName)) {\n visitedFragments.add(fragmentName);\n collectTopLevelFields(fragment.selectionSet, fragments, fields, visitedFragments);\n }\n }\n }\n}\n\n/** Top-level mutation field names the executed operation selects (empty for a query or subscription). */\nexport function getMutationFieldNames(document: DocumentNode, operationName?: string | null): string[] {\n const operation = findMutation(document, operationName);\n if (!operation) return [];\n\n const fragments = new Map<string, FragmentDefinitionNode>();\n for (const definition of document.definitions) {\n if (definition.kind === Kind.FRAGMENT_DEFINITION) fragments.set(definition.name.value, definition);\n }\n const fields: string[] = [];\n collectTopLevelFields(operation.selectionSet, fragments, fields, new Set());\n return fields;\n}\n\nfunction idOf(value: unknown): string | undefined {\n if (!isRecord(value)) return undefined;\n const id = value['id'];\n return typeof id === 'string' && id.length > 0 ? id : undefined;\n}\n\nfunction stringOf(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction findWorkspaceId(value: unknown, depth = 0): string | undefined {\n if (depth > MAX_DEPTH || !isRecord(value)) return undefined;\n const direct = stringOf(value['workspaceId']);\n if (direct) return direct;\n for (const entry of Object.values(value)) {\n const nested = findWorkspaceId(entry, depth + 1);\n if (nested) return nested;\n }\n return undefined;\n}\n\nfunction isExecutionResult(value: unknown): value is ExecutionResult {\n return isRecord(value) && ('data' in value || 'errors' in value);\n}\n\ninterface AuditRecordInput {\n serviceName: string;\n fieldNames: string[];\n contextValue: unknown;\n variableValues: unknown;\n result: unknown;\n}\n\nfunction recordMutationAudit(input: AuditRecordInput): void {\n const context = isRecord(input.contextValue) ? input.contextValue : {};\n const actor = isRecord(context['actor']) ? context['actor'] : undefined;\n const actorId = idOf(actor) ?? stringOf(context['actorId']) ?? 'anonymous';\n const actorType = stringOf(actor?.['type']) ?? stringOf(context['actorType']) ?? 'unknown';\n const workspaceId =\n idOf(context['workspace']) ?? stringOf(context['workspaceId']) ?? findWorkspaceId(input.variableValues);\n const tenantId = idOf(context['tenant']) ?? stringOf(context['tenantId']);\n const executionResult = isExecutionResult(input.result) ? input.result : undefined;\n const errors = executionResult?.errors ?? [];\n const success = errors.length === 0;\n const errorMessage = success ? undefined : truncate(errors.map((error) => error.message).join('; '));\n const joinedFields = input.fieldNames.join(',');\n\n void trackOperation({\n operationName: joinedFields,\n userId: actorId,\n // The request context drives the row's actorType/onBehalfOf (BOFF-9684): an `app` actor\n // here is an AI agent or integration. An unknown kind is left unset, never guessed.\n context,\n workspaceId,\n success,\n errorMessage,\n activityOptions: {\n enabled: true,\n activityType: MUTATION_AUDIT_ACTIVITY_TYPE,\n description: `GraphQL mutation executed: ${input.fieldNames.join(', ')}`,\n workspaceId,\n resourceType: MUTATION_AUDIT_RESOURCE_TYPE,\n resourceId: joinedFields,\n metadata: {\n serviceName: input.serviceName,\n source: 'mutation-audit-backstop',\n actorType,\n fieldNames: input.fieldNames,\n tenantId,\n tracking: sanitizeAuditValue(context['tracking']),\n variablePreview: sanitizeAuditValue(input.variableValues),\n resultPreview: sanitizeAuditValue(\n executionResult\n ? {\n data: executionResult.data,\n errors: errors.map((error) => ({ message: error.message, path: error.path?.join('.') })),\n }\n : undefined\n ),\n },\n },\n }).catch((error: unknown) => {\n logger.warn('[MutationAuditPlugin] Failed to record mutation audit', {\n serviceName: input.serviceName,\n fieldNames: input.fieldNames,\n error: error instanceof Error ? error.message : String(error),\n });\n });\n}\n\nfunction shouldWrite(scope: ExplicitActivityScope, dedupe: boolean): boolean {\n if (scope.suppressed) return false;\n return !(dedupe && scope.explicitCount > 0);\n}\n\n/**\n * Create the mutation-audit backstop plugin.\n *\n * Accepts the bare service name for drop-in compatibility with the per-service copies.\n */\nexport function createMutationAuditPlugin(options: MutationAuditPluginOptions | string): Plugin {\n const resolved: MutationAuditPluginOptions = typeof options === 'string' ? { serviceName: options } : options;\n const excluded = new Set(resolved.excludeFields ?? []);\n const dedupe = resolved.dedupeExplicitActivity !== false;\n\n return {\n onExecute({ args, executeFn, setExecuteFn }) {\n const fieldNames = getMutationFieldNames(args.document, args.operationName).filter((name) => !excluded.has(name));\n if (fieldNames.length === 0) return;\n\n setExecuteFn(async (executeArgs) => {\n const scope = createExplicitActivityScope();\n const result = await runInExplicitActivityScope(scope, () => executeFn(executeArgs));\n try {\n if (shouldWrite(scope, dedupe)) {\n recordMutationAudit({\n serviceName: resolved.serviceName,\n fieldNames,\n contextValue: executeArgs.contextValue,\n variableValues: executeArgs.variableValues,\n result,\n });\n }\n } catch (error) {\n // The backstop must never fail the mutation it observes.\n logger.warn('[MutationAuditPlugin] Failed to prepare mutation audit', {\n serviceName: resolved.serviceName,\n fieldNames,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n return result;\n });\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,kBACd,OACA,oBACoB;CACpB,IAAI,sBAA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