{"version":3,"sources":["../src/index.ts","../src/types.ts","../src/middleware/hono.ts","../src/authz/role.ts","../src/authz/tenant-boundary.ts","../src/jwt/claims.ts","../src/jwt/jwks-cache.ts","../src/jwt/jwks/retry-policy.ts","../src/jwt/jwks/usable-keys.ts","../src/jwt/jwks/fetch.ts","../src/jwt/jwks/options.ts","../src/jwt/validator.ts","../src/user/resolve.ts","../src/middleware/acting-user.ts","../src/oauth/client.ts","../src/oauth/state.ts","../src/oauth/token-store.ts","../src/platform/env.ts","../src/platform/validators.ts","../src/platform/bff-auth.ts","../src/platform/internal-channel.ts","../src/platform/service-token.ts"],"sourcesContent":["// ─── Types ─────────────────────────────────────────────────────────\n\nexport { requireRole } from \"./authz/role.js\";\nexport type { TenantBoundaryOptions } from \"./authz/tenant-boundary.js\";\n// ─── Authorization ─────────────────────────────────────────────────\nexport { requireTenantBoundary } from \"./authz/tenant-boundary.js\";\nexport type {\n  AuthenticatedPrincipal,\n  AuthorizationDecision,\n  Operation,\n  Resource,\n  TokenSet,\n} from \"./authz/types.js\";\n// ─── JWT Validation ────────────────────────────────────────────────\nexport type { TenantClaims } from \"./jwt/claims.js\";\nexport { claimsFromPayload } from \"./jwt/claims.js\";\nexport type { JwksCacheOptions, JwksFetchFailure, JwksStatus } from \"./jwt/jwks-cache.js\";\nexport { fullJitterDelay, JwksCache } from \"./jwt/jwks-cache.js\";\nexport type { JwtValidatorOptions } from \"./jwt/validator.js\";\nexport {\n  type AllowedCaller,\n  type CallerKind,\n  JwtValidator,\n  parseAllowedCallers,\n} from \"./jwt/validator.js\";\nexport type { ActingUser, ActingUserOptions } from \"./middleware/acting-user.js\";\n// The acting user and the identity endpoint, for an app's own server (ADR-057).\nexport {\n  ACTING_USER_KEY,\n  actingUserMiddleware,\n  getActingUser,\n  identityHandler,\n  requireActingUser,\n} from \"./middleware/acting-user.js\";\nexport type { AuthMiddlewareOptions } from \"./middleware/hono.js\";\n// ─── Hono Middleware ───────────────────────────────────────────────\nexport { authMiddleware, getPrincipal, PRINCIPAL_KEY } from \"./middleware/hono.js\";\n// ─── OAuth ─────────────────────────────────────────────────────────\nexport type { OidcClientOptions } from \"./oauth/client.js\";\nexport { OidcClient } from \"./oauth/client.js\";\nexport { generateOAuthState, hashState } from \"./oauth/state.js\";\nexport type { PendingOAuthFlow, RedisTokenStoreOptions, TokenStore } from \"./oauth/token-store.js\";\nexport { RedisTokenStore } from \"./oauth/token-store.js\";\nexport type { BffAuth, BffAuthOptions } from \"./platform/bff-auth.js\";\nexport { bffAuth } from \"./platform/bff-auth.js\";\nexport type { EnvSource } from \"./platform/env.js\";\n\n// ─── Platform surfaces ─────────────────────────────────────────────\n//\n// What an application should reach for FIRST. The exports above are the\n// primitives this platform is built from; these are the shapes it actually has,\n// with the security-relevant switches already decided. An application that\n// configures a JwtValidator by hand has taken on four decisions whose wrong\n// settings fail by accepting a token rather than by erroring.\nexport {\n  PLATFORM_ENV,\n  PLATFORM_LOGIN_SCOPES,\n  PlatformConfigError,\n  platformEnv,\n  requirePlatformEnv,\n} from \"./platform/env.js\";\nexport type { InternalChannelHeaders } from \"./platform/internal-channel.js\";\nexport {\n  forwardedPrincipal,\n  InternalTokenMissingError,\n  internalCallHeaders,\n  internalChannelHeaders,\n  requireInternalCaller,\n} from \"./platform/internal-channel.js\";\nexport type { ServiceTokenOptions, ServiceTokenSource } from \"./platform/service-token.js\";\n// Calling another application as THIS APPLICATION, with no user in the request\n// (ADR-097). The scopes an issuer needs for that are raw vocabulary; naming them\n// here means a product team never writes them.\nexport {\n  backendProjectIdKey,\n  projectAudienceScope,\n  RESOURCE_OWNER_SCOPE,\n  serviceTokenSource,\n} from \"./platform/service-token.js\";\nexport type { SurfaceValidatorOptions } from \"./platform/validators.js\";\nexport { browserSessionValidator, consumerApiValidator } from \"./platform/validators.js\";\nexport {\n  AuthError,\n  CallerNotAllowedError,\n  IdTokenPresentedError,\n  InsufficientScopeError,\n  InvalidAudienceError,\n  InvalidIssuerError,\n  JwksFetchError,\n  KeyNotFoundError,\n  RoleDeniedError,\n  TenantMismatchError,\n  TokenExpiredError,\n  TokenMissingError,\n} from \"./types.js\";\nexport { resolveUser, withUserContext } from \"./user/resolve.js\";\n// Tenant-local user resolution (platform baseline `users` / `identities`).\nexport type {\n  ResolvedUser,\n  ResolveUserOptions,\n  SqlExecutor,\n  SqlTransactor,\n} from \"./user/types.js\";\n","export interface AuthErrorOptions {\n  code: string;\n  message: string;\n  cause?: unknown;\n}\n\nexport class AuthError extends Error {\n  readonly code: string;\n\n  constructor(opts: AuthErrorOptions) {\n    super(opts.message, { cause: opts.cause });\n    this.name = \"AuthError\";\n    this.code = opts.code;\n  }\n}\n\nexport class TokenExpiredError extends AuthError {\n  constructor(message = \"Token has expired\", cause?: unknown) {\n    super({ code: \"TOKEN_EXPIRED\", message, cause });\n    this.name = \"TokenExpiredError\";\n  }\n}\n\nexport class InvalidIssuerError extends AuthError {\n  constructor(expected: string, actual: string) {\n    super({\n      code: \"INVALID_ISSUER\",\n      message: `Invalid issuer: expected \"${expected}\", got \"${actual}\"`,\n    });\n    this.name = \"InvalidIssuerError\";\n  }\n}\n\nexport class InvalidAudienceError extends AuthError {\n  constructor(expected: string, actual: string | string[]) {\n    super({\n      code: \"INVALID_AUDIENCE\",\n      message: `Invalid audience: expected \"${expected}\", got \"${JSON.stringify(actual)}\"`,\n    });\n    this.name = \"InvalidAudienceError\";\n  }\n}\n\nexport class InsufficientScopeError extends AuthError {\n  constructor(required: string[], actual: string[]) {\n    super({\n      code: \"INSUFFICIENT_SCOPE\",\n      message: `Insufficient scope: required [${required.join(\", \")}], got [${actual.join(\", \")}]`,\n    });\n    this.name = \"InsufficientScopeError\";\n  }\n}\n\nexport class TenantMismatchError extends AuthError {\n  constructor(expected: string, actual: string) {\n    super({\n      code: \"TENANT_MISMATCH\",\n      message: `Tenant mismatch: expected \"${expected}\", got \"${actual}\"`,\n    });\n    this.name = \"TenantMismatchError\";\n  }\n}\n\nexport class RoleDeniedError extends AuthError {\n  constructor(required: string[]) {\n    super({\n      code: \"ROLE_DENIED\",\n      message: `Role denied: required one of [${required.join(\", \")}]`,\n    });\n    this.name = \"RoleDeniedError\";\n  }\n}\n\nexport class TokenMissingError extends AuthError {\n  constructor(message = \"No token provided\") {\n    super({ code: \"TOKEN_MISSING\", message });\n    this.name = \"TokenMissingError\";\n  }\n}\n\n/**\n * The receiver could not obtain the issuer's keys. Nothing is known about the\n * token, so this is the RECEIVER's failure, not the caller's: middleware answers\n * it 503, never 401 (a 401 tells a client its credential is bad, and it is not).\n *\n * The message names the URL, the cause and the attempts. It is for the service's\n * own logs; a response body carries only the code.\n */\nexport class JwksFetchError extends AuthError {\n  /** The upstream HTTP status, when there was one. */\n  readonly status?: number;\n\n  constructor(url: string, cause?: unknown, detail?: string, status?: number) {\n    super({\n      code: \"JWKS_FETCH_ERROR\",\n      message: `Failed to fetch JWKS from ${url}${detail ? `: ${detail}` : \"\"}`,\n      cause,\n    });\n    this.name = \"JwksFetchError\";\n    this.status = status;\n  }\n}\n\nexport class KeyNotFoundError extends AuthError {\n  constructor(kid: string) {\n    super({ code: \"KEY_NOT_FOUND\", message: `Key not found in JWKS: ${kid}` });\n    this.name = \"KeyNotFoundError\";\n  }\n}\n\n/**\n * A token that identifies a login was presented where a credential for this API\n * was required.\n *\n * Separate from TOKEN_INVALID deliberately: the token is well-formed, correctly\n * signed by the right issuer, and carries the right audience. It is the wrong\n * KIND of token, and an operator reading TOKEN_INVALID would look for a signing\n * or clock problem that does not exist (ADR-095).\n */\nexport class IdTokenPresentedError extends AuthError {\n  constructor() {\n    super({\n      code: \"ID_TOKEN_PRESENTED\",\n      message:\n        \"An ID token was presented where an access token is required: the token carries at_hash, which only an ID token does. APIs accept access tokens (ADR-095).\",\n    });\n    this.name = \"IdTokenPresentedError\";\n  }\n}\n\n/**\n * The token names a calling application that is not on this receiver's\n * allowlist, or names none at all (ADR-094 invariant 2).\n *\n * Its own code because the remedy differs from every other rejection: the token\n * is valid, the user is real, and what is wrong is WHICH application asked for\n * it. That is a configuration answer -- add the caller to the allowlist, or stop\n * it calling -- not a credential one.\n */\nexport class CallerNotAllowedError extends AuthError {\n  constructor(azp: string | undefined, allowed: string[]) {\n    super({\n      code: \"CALLER_NOT_ALLOWED\",\n      message:\n        azp === undefined\n          ? `Token carries no azp/client_id, so the calling application cannot be established; this receiver admits only [${allowed.join(\", \")}] (ADR-094 invariant 2).`\n          : `Calling application \"${azp}\" is not permitted by this receiver; it admits only [${allowed.join(\", \")}] (ADR-094 invariant 2).`,\n    });\n    this.name = \"CallerNotAllowedError\";\n  }\n}\n","import type { Context, MiddlewareHandler } from \"hono\";\nimport type { AuthenticatedPrincipal } from \"../authz/types.js\";\nimport type { JwtValidator } from \"../jwt/validator.js\";\nimport { AuthError } from \"../types.js\";\n\nconst PRINCIPAL_KEY = \"auth:principal\" as const;\n\nexport interface AuthMiddlewareOptions {\n  /** JwtValidator instance */\n  validator: JwtValidator;\n  /** Required scopes — if provided, token must contain all listed scopes */\n  requiredScopes?: string[];\n  /** Custom header to extract token from (default: \"Authorization\") */\n  headerName?: string;\n  /**\n   * Where a JWKS failure's detail goes (URL, cause, attempts). Defaults to\n   * console.warn. The response carries only the code: that detail describes the\n   * service's own infrastructure and is not the caller's to read.\n   */\n  onDependencyError?: (err: unknown) => void;\n}\n\n/**\n * Hono middleware that extracts a Bearer token, validates it via JwtValidator,\n * and sets the authenticated principal on the context.\n *\n * Usage:\n *   app.use(\"/api/*\", authMiddleware({ validator }));\n *   // c.get(\"principal\") → AuthenticatedPrincipal\n */\nexport function authMiddleware(opts: AuthMiddlewareOptions): MiddlewareHandler {\n  const reportDependency =\n    opts.onDependencyError ??\n    ((err: unknown) => {\n      console.warn(\n        \"[zero-ops-auth] JWKS unavailable:\",\n        err instanceof Error ? err.message : \"unknown error\",\n      );\n    });\n\n  return async (c, next) => {\n    const headerName = opts.headerName ?? \"Authorization\";\n    const auth = c.req.header(headerName);\n\n    if (!auth?.startsWith(\"Bearer \")) {\n      return c.json({ error: \"Unauthorized\", code: \"TOKEN_MISSING\" }, 401);\n    }\n\n    const token = auth.slice(7);\n\n    try {\n      const claims = await opts.validator.validate(token);\n\n      // A token with NO scope claim previously skipped this check entirely and was\n      // admitted. Absence of scope must be treated as \"no scopes granted\", not as\n      // \"check not applicable\".\n      if (opts.requiredScopes?.length) {\n        const tokenScopes = (claims.scope ?? \"\").split(/\\s+/).filter(Boolean);\n        const missing = opts.requiredScopes.filter((s) => !tokenScopes.includes(s));\n        if (missing.length > 0) {\n          return c.json(\n            {\n              error: \"Forbidden\",\n              code: \"INSUFFICIENT_SCOPE\",\n              required: opts.requiredScopes,\n              missing,\n            },\n            403,\n          );\n        }\n      }\n\n      const principal: AuthenticatedPrincipal = {\n        subject: claims.sub,\n        email: claims.email,\n        tenantId: claims.tenant_id,\n        tenantTier: claims.tenant_tier,\n        roles: claims.roles,\n        issuer: claims.iss,\n        audience:\n          typeof claims.aud === \"string\"\n            ? claims.aud\n            : Array.isArray(claims.aud)\n              ? claims.aud[0]\n              : undefined,\n      };\n\n      c.set(PRINCIPAL_KEY, principal);\n      await next();\n    } catch (err) {\n      if (err instanceof AuthError) {\n        // The keys could not be fetched: the token was never examined, so the\n        // caller is not at fault and must not be told its credential is bad.\n        if (err.code === \"JWKS_FETCH_ERROR\") {\n          reportDependency(err);\n          return c.json(\n            {\n              error: \"Service Unavailable\",\n              code: err.code,\n              message: \"Credentials cannot be verified right now\",\n            },\n            503,\n          );\n        }\n        return c.json({ error: \"Unauthorized\", code: err.code, message: err.message }, 401);\n      }\n      return c.json({ error: \"Unauthorized\", code: \"TOKEN_INVALID\" }, 401);\n    }\n  };\n}\n\n/**\n * Extract the authenticated principal from the Hono context.\n * Must be called after authMiddleware has run.\n */\nexport function getPrincipal(c: Context): AuthenticatedPrincipal | undefined {\n  return c.get(PRINCIPAL_KEY) as AuthenticatedPrincipal | undefined;\n}\n\nexport { PRINCIPAL_KEY };\n","import type { MiddlewareHandler } from \"hono\";\nimport { getPrincipal } from \"../middleware/hono.js\";\n\n/**\n * Hono middleware that checks if the authenticated principal has one of the\n * required roles.\n *\n * Returns 403 if the principal's roles do not include any of the listed roles.\n *\n * Usage:\n *   app.delete(\"/api/:id\", requireRole(\"admin\"), deleteHandler);\n *   app.post(\"/api/config\", requireRole(\"platform_admin\", \"tenant_admin\"), handler);\n */\nexport function requireRole(...requiredRoles: string[]): MiddlewareHandler {\n  return async (c, next) => {\n    const principal = getPrincipal(c);\n    if (!principal) {\n      return c.json({ error: \"Unauthorized\", code: \"NOT_AUTHENTICATED\" }, 401);\n    }\n\n    const hasRole = requiredRoles.some((role) => principal.roles.includes(role));\n\n    if (!hasRole) {\n      return c.json(\n        {\n          error: \"Forbidden\",\n          code: \"ROLE_DENIED\",\n          message: `Access denied: requires one of [${requiredRoles.join(\", \")}]`,\n        },\n        403,\n      );\n    }\n\n    await next();\n  };\n}\n","import type { Context, MiddlewareHandler } from \"hono\";\nimport { getPrincipal } from \"../middleware/hono.js\";\n\nexport interface TenantBoundaryOptions {\n  /**\n   * Function to extract the resource tenant ID from the request.\n   * Default: reads from route param \"tenantId\" or query param \"tenant_id\".\n   */\n  getTenantId?: (c: Context) => string | undefined;\n}\n\n/**\n * Hono middleware that enforces tenant boundary:\n * principal.tenantId == resource.tenantId.\n *\n * Returns 403 if the authenticated principal's tenant does not match the\n * resource's tenant.\n *\n * Usage:\n *   app.get(\"/api/v1/spokes/:tenantId\", requireTenantBoundary(), handler);\n */\nexport function requireTenantBoundary(opts?: TenantBoundaryOptions): MiddlewareHandler {\n  return async (c, next) => {\n    const principal = getPrincipal(c);\n    if (!principal) {\n      return c.json({ error: \"Unauthorized\", code: \"NOT_AUTHENTICATED\" }, 401);\n    }\n\n    const getTenantId = opts?.getTenantId ?? defaultGetTenantId;\n    const resourceTenantId = getTenantId(c);\n\n    if (!resourceTenantId) {\n      return c.json(\n        {\n          error: \"Bad Request\",\n          code: \"TENANT_ID_REQUIRED\",\n          message: \"Tenant ID is required for this operation\",\n        },\n        400,\n      );\n    }\n\n    if (principal.tenantId !== resourceTenantId) {\n      return c.json(\n        {\n          error: \"Forbidden\",\n          code: \"TENANT_MISMATCH\",\n          message: `Access denied: your tenant (${principal.tenantId}) does not have access to tenant ${resourceTenantId}`,\n        },\n        403,\n      );\n    }\n\n    await next();\n  };\n}\n\nfunction defaultGetTenantId(c: Context): string | undefined {\n  // Try route params first\n  const routeTenantId = c.req.param(\"tenantId\") ?? c.req.param(\"tenant_id\");\n  if (routeTenantId) return routeTenantId;\n\n  // Try query params\n  const queryTenantId = c.req.query(\"tenant_id\");\n  if (queryTenantId) return queryTenantId;\n\n  return undefined;\n}\n","export interface TenantClaims {\n  /** Subject (user ID) */\n  sub: string;\n  /** User email */\n  email: string;\n  /**\n   * Standard OIDC claim. Optional because not every provider or flow emits it,\n   * and an absent claim must not be read as \"verified\".\n   */\n  email_verified?: boolean;\n  /** Tenant ID — required for tenant-scoped authorization */\n  tenant_id: string;\n  /**\n   * Human-readable tenant name, when the provider supplies one.\n   *\n   * Never load-bearing: tenant_id is the identifier and the only thing an\n   * authorization decision may use. This is for display and logs, where an\n   * issuer-allocated identifier is unreadable — they are commonly opaque\n   * numbers, while the tenant has a name a human recognises.\n   */\n  tenant_name?: string;\n  /** Tenant tier (e.g., \"free\", \"pro\", \"enterprise\") */\n  tenant_tier?: string;\n  /** User roles */\n  roles: string[];\n  /**\n   * `azp` — the client the token was issued to (ADR-094 invariant 2).\n   *\n   * The AUTHORIZED PARTY, not the subject and not the audience. It answers\n   * \"which application asked for this token\", which is the only claim that can:\n   * `aud` names who may accept it, and Zitadel issues any project's audience to\n   * any client that asks, so `aud` cannot say who is calling.\n   *\n   * Optional because it genuinely is: a `client_credentials` token carries no\n   * `azp`. Absence must therefore be a REFUSAL where a caller identity is\n   * required, never a pass — which is what `allowedAzp` on the validator does.\n   *\n   * Zitadel spells it `azp` on ID tokens and `client_id` on access tokens, and\n   * both are read here so a receiver does not have to know which it holds.\n   */\n  azp?: string;\n  /**\n   * The APPLICATION the calling client belongs to, resolved from the receiver's\n   * caller map (ADR-094 invariant 2b).\n   *\n   * Not a claim. No token carries it and none may: `azp` names a client, and\n   * only the platform knows which application the platform registered that\n   * client for. A receiver partitioning records per consuming application uses\n   * this and never a field from the request.\n   *\n   * Undefined when the validator was given no caller map.\n   */\n  consumer_app_id?: string;\n  /**\n   * What the calling client's tokens carry, from the receiver's caller map\n   * (ADR-110): `user` -- the subject is the person the calling application acts\n   * for -- or `service` -- the subject is the calling application's machine\n   * identity, and nothing may read a person out of it (ADR-097 invariant 8).\n   *\n   * Not a claim, for the same reason as `consumer_app_id`: the token cannot say,\n   * because Zitadel spells the client claim the same way for both. Undefined\n   * when the validator was given no caller map.\n   */\n  caller_kind?: \"user\" | \"service\";\n  /**\n   * Platform-assigned groups (ADR-058).\n   *\n   * The auth-proxy injects this claim, and the API server matches it for\n   * Kubernetes RBAC — but this library dropped it, so no consumer could read\n   * the one claim that identifies a platform-scoped identity. That is why a\n   * platform admin, who legitimately has no tenant, could not be told apart\n   * from a token that was simply missing its tenant.\n   */\n  groups: string[];\n  /** JWT issuer */\n  iss?: string;\n  /** JWT audience */\n  aud?: string | string[];\n  /** Expiration time (unix seconds) */\n  exp?: number;\n  /** Issued at (unix seconds) */\n  iat?: number;\n  /** Not before (unix seconds) */\n  nbf?: number;\n  /** JWT ID */\n  jti?: string;\n  /** Token scope (space-delimited) */\n  scope?: string;\n}\n\n/**\n * Claim names the platform's own contract does not define.\n *\n * The platform's contract is `tenant_id` and `roles`. An issuer that does not\n * emit those spells them its own way, and reading it means naming its claims\n * somewhere — there is no abstraction that removes the literal, only one that\n * decides where it lives.\n *\n * They live HERE, in one table, so the rest of this library is written against\n * the contract rather than against an issuer. Supporting another issuer is an\n * entry in this table, not an edit to the logic below (ADR-059). The reasoning\n * for each name, and which product uses it, belongs in that ADR rather than in\n * this file.\n *\n * Order is preference order: the platform's own claim first, so a token that\n * already speaks the contract is never reinterpreted.\n */\nconst TENANT_ID_CLAIMS = [\n  \"tenant_id\",\n  \"urn:zitadel:iam:user:resourceowner:id\",\n  \"urn:zitadel:iam:org:id\",\n] as const;\n\nconst TENANT_NAME_CLAIMS = [\n  \"tenant_name\",\n  \"urn:zitadel:iam:user:resourceowner:name\",\n  \"urn:zitadel:iam:org:name\",\n] as const;\n\n/** Nested as `{ roleKey: { grantingTenantId: domain } }`. */\nconst SCOPED_ROLES_CLAIM = \"urn:zitadel:iam:org:project:roles\";\n\nfunction firstString(payload: Record<string, unknown>, names: readonly string[]): string {\n  for (const n of names) {\n    const v = payload[n];\n    if (typeof v === \"string\" && v) return v;\n  }\n  return \"\";\n}\n\n/**\n * Roles granted to this user WITHIN THE GIVEN TENANT.\n *\n * The claim is nested because one token can carry the same role granted in\n * several tenants. An issuer emits it only when asked for the scope that mints\n * it, so absent means no roles — never \"all roles\".\n *\n * The tenant filter is the security-relevant part, not a detail. Flattening to\n * `Object.keys()` would return a role granted in a DIFFERENT tenant as if it had\n * been granted here — a cross-tenant privilege leak that reads as a correct role\n * list, and one that stays invisible until a user is granted access to a second\n * tenant. Roles are therefore kept only where the nested tenant id equals the\n * tenant this token is scoped to.\n */\nfunction rolesGrantedInTenant(payload: Record<string, unknown>, tenantId: string): string[] {\n  const raw = payload[SCOPED_ROLES_CLAIM];\n  if (!raw || typeof raw !== \"object\" || !tenantId) return [];\n  const out: string[] = [];\n  for (const [roleKey, grantedIn] of Object.entries(raw as Record<string, unknown>)) {\n    if (grantedIn && typeof grantedIn === \"object\" && Object.hasOwn(grantedIn, tenantId)) {\n      out.push(roleKey);\n    }\n  }\n  return out;\n}\n\nexport function claimsFromPayload(payload: Record<string, unknown>): TenantClaims {\n  const tenantId = firstString(payload, TENANT_ID_CLAIMS);\n\n  return {\n    sub: String(payload.sub ?? \"\"),\n    email: String(payload.email ?? \"\"),\n    email_verified: payload.email_verified === true,\n    // Read through the alias table, so one library serves any issuer and a\n    // provider swap is a configuration change rather than a fork.\n    //\n    // An issuer that carries tenancy structurally — where the tenant OWNS the\n    // user rather than being an attribute written onto it — mints these claims\n    // only for the scope that asks for them. Without that scope the claim is\n    // absent and the token is correctly rejected as tenant-less, so the\n    // requirement in the validator must stay a check and never a default.\n    // `client_id` as well as `azp`: Zitadel's NewIDTokenClaims sets azp and its\n    // NewAccessTokenClaims sets client_id, for the same fact. Reading only one\n    // would make the caller identity appear absent on half the tokens this\n    // platform issues, and absent means refused.\n    azp:\n      (typeof payload.azp === \"string\" && payload.azp) ||\n      (typeof payload.client_id === \"string\" && payload.client_id) ||\n      undefined,\n    tenant_id: tenantId,\n    tenant_name: firstString(payload, TENANT_NAME_CLAIMS) || undefined,\n    tenant_tier: payload.tenant_tier ? String(payload.tenant_tier) : undefined,\n    // The platform's auth-proxy injects a SINGULAR `role` claim\n    // (internal/auth-proxy/validate.go). Without this fallback `roles` was always\n    // empty and every requireRole() check denied.\n    // Same singular/plural tolerance as roles: the source of this claim is\n    // metadata_public.groups, which is an array, but a provider emitting a\n    // single string must not silently produce an empty list.\n    groups: Array.isArray(payload.groups)\n      ? (payload.groups as unknown[]).map(String)\n      : typeof payload.groups === \"string\"\n        ? [payload.groups]\n        : [],\n    // The contract's own claim wins when present; the issuer's scoped roles\n    // otherwise.\n    //\n    // Ordered this way so a token that already speaks the contract behaves\n    // exactly as before and this stays additive. Where it falls through,\n    // authorisation comes from the issuer's own model rather than from a claim\n    // the platform injected — which is what ADR-059 means by not running a\n    // second model beside the provider's.\n    roles: Array.isArray(payload.roles)\n      ? (payload.roles as unknown[]).map(String)\n      : typeof payload.roles === \"string\"\n        ? [payload.roles]\n        : Array.isArray(payload.role)\n          ? (payload.role as unknown[]).map(String)\n          : typeof payload.role === \"string\"\n            ? [payload.role]\n            : rolesGrantedInTenant(payload, tenantId),\n    iss: payload.iss ? String(payload.iss) : undefined,\n    aud: payload.aud as TenantClaims[\"aud\"],\n    exp: typeof payload.exp === \"number\" ? payload.exp : undefined,\n    iat: typeof payload.iat === \"number\" ? payload.iat : undefined,\n    nbf: typeof payload.nbf === \"number\" ? payload.nbf : undefined,\n    jti: payload.jti ? String(payload.jti) : undefined,\n    scope: payload.scope ? String(payload.scope) : undefined,\n  };\n}\n","import * as jose from \"jose\";\nimport { JwksFetchError } from \"../types.js\";\nimport { fetchJwksWithRetry, type JwksFetchFailure } from \"./jwks/fetch.js\";\nimport {\n  type JwksCacheOptions,\n  type ResolvedJwksOptions,\n  resolveJwksOptions,\n} from \"./jwks/options.js\";\nimport { fullJitterDelay } from \"./jwks/retry-policy.js\";\n\nexport type { JwksFetchFailure } from \"./jwks/fetch.js\";\nexport type { JwksCacheOptions } from \"./jwks/options.js\";\nexport { fullJitterDelay } from \"./jwks/retry-policy.js\";\n\n/**\n * The issuer's signing keys, held in ONE place.\n *\n * There is one store -- jose's RemoteJWKSet -- and one way into the network,\n * installed as its `customFetch`. jose keeps the key set, de-duplicates\n * concurrent fetches and refetches on an unknown `kid`. The modules under\n * ./jwks/ decide the rest:\n *\n *   options.ts       configuration, validated\n *   retry-policy.ts  what is retried, and the full-jitter delay\n *   fetch.ts         one fetch: per-attempt timeout over headers AND body, retries\n *   usable-keys.ts   what counts as a key this service can verify with\n *\n * and this class owns the lifecycle and the status.\n *\n * LIFECYCLE (ADR-022, stable-but-not-ready). A service calls `start()` at boot\n * and reports `status().ready` as its readiness. `start()` fetches immediately,\n * retries with capped full-jitter backoff until it succeeds, then refreshes in\n * the background, so requests verify against keys already held instead of each\n * cold pod's first requests waiting on a download. It never throws and never\n * exits the process: an unreachable issuer leaves the pod alive and unready, and\n * it becomes ready on its own when the issuer returns.\n */\nexport interface JwksStatus {\n  /**\n   * The service can verify tokens: a key set holding at least one usable\n   * signing key was fetched less than `maxStaleMs` ago. This is the dependency\n   * half of the readiness probe, and the value behind `dependency_status`.\n   */\n  ready: boolean;\n  /** Usable signing keys in the held set. */\n  keys: number;\n  lastSuccessAt?: number;\n  consecutiveFailures: number;\n  /** The last failure's reason. Internal detail: for logs, never a response body. */\n  lastError?: string;\n  /** `start()` is running the background refresh. */\n  maintaining: boolean;\n}\n\nexport class JwksCache {\n  private readonly opts: ResolvedJwksOptions;\n  private readonly store: jose.RemoteJWKSet;\n\n  private usableKeys = 0;\n  private lastSuccessAt?: number;\n  private consecutiveFailures = 0;\n  private lastError?: string;\n  /** No request reaches the issuer before this time: it answered with a long Retry-After. */\n  private retryAfterUntil = 0;\n  /** The running `start()`, if any. */\n  private run?: AbortController;\n  private timer?: ReturnType<typeof setTimeout>;\n\n  constructor(options: JwksCacheOptions) {\n    this.opts = resolveJwksOptions(options);\n    const o = this.opts;\n\n    // Creating the store fetches nothing; jose fetches on first use.\n    //\n    // jose's own timeout spans headers AND body, and a body that stalls past it\n    // is reported as \"Failed to parse the JSON Web Key Set HTTP response as JSON\"\n    // -- what a Waypoint SDK pod returned for a fetch Zitadel had served in under\n    // a second. So the fetch is ours, and jose's timeout is set to outlast every\n    // attempt of it.\n    //\n    // cacheMaxAge is the STALENESS bound, not the refresh period: the background\n    // refresh keeps the set younger than that, so a request does not block on a\n    // download unless refreshing has been failing for longer than maxStaleMs.\n    const budget =\n      o.fetchAttempts * o.fetchTimeoutMs + (o.fetchAttempts - 1) * o.retryMaxMs + 1_000;\n    this.store = jose.createRemoteJWKSet(new URL(o.jwksUrl), {\n      timeoutDuration: budget,\n      cooldownDuration: o.refreshIntervalMs,\n      cacheMaxAge: o.maxStaleMs,\n      [jose.customFetch]: (url, init) => this.fetch(url, init),\n    });\n  }\n\n  /** The key resolver `jwtVerify` uses. The one store; there is no other. */\n  async getSigningKey(): Promise<jose.JWTVerifyGetKey> {\n    return this.store;\n  }\n\n  /** One fetch, awaited. Resolves when a usable set is held; rejects with JwksFetchError. Prefer `start()`. */\n  async warm(): Promise<void> {\n    await this.store.reload();\n  }\n\n  /**\n   * Keep the keys fetched until `stop()`, or until `signal` aborts. Idempotent\n   * while running; never throws.\n   *\n   * Until the first success it retries with full-jitter backoff capped at\n   * `backoffMaxMs`, honouring a Retry-After. After it, it refreshes every\n   * `keyTtlMs` with ±10% jitter, so a fleet started together does not refresh\n   * together. Timers are unref'd and do not hold the process open.\n   *\n   * Each run owns an AbortController. Stopping aborts it: the pending timer is\n   * cleared, a retry pause in progress ends, an in-flight fetch is cancelled, and\n   * the loop cannot reschedule itself -- including when `start()` is called again\n   * before the old run's fetch has settled, which then cannot leave two loops.\n   * jose shares one download between everything waiting on it, so a stop also\n   * fails that download for its other waiters; a run started right after a stop\n   * sees one failure and retries it after a jittered pause.\n   */\n  start(options: { signal?: AbortSignal } = {}): void {\n    if (this.run) return;\n    const run = new AbortController();\n    this.run = run;\n    if (options.signal) {\n      if (options.signal.aborted) {\n        this.stop();\n        return;\n      }\n      options.signal.addEventListener(\"abort\", () => this.stopRun(run), {\n        once: true,\n        signal: run.signal,\n      });\n    }\n    let failures = 0;\n    const tick = async () => {\n      let next: number;\n      try {\n        await this.store.reload();\n        failures = 0;\n        next = this.opts.keyTtlMs * (0.9 + Math.random() * 0.2);\n      } catch {\n        failures++;\n        const backoff = fullJitterDelay(\n          failures,\n          Math.max(this.opts.retryBaseMs, 1),\n          this.opts.backoffMaxMs,\n        );\n        next = Math.max(backoff, this.retryAfterUntil - Date.now());\n      }\n      if (run.signal.aborted) return;\n      this.timer = setTimeout(() => void tick(), next);\n      this.timer.unref?.();\n    };\n    void tick();\n  }\n\n  /** End the background refresh. The held keys stay usable until stale. Idempotent. */\n  stop(): void {\n    if (this.run) this.stopRun(this.run);\n  }\n\n  private stopRun(run: AbortController): void {\n    if (this.run !== run) return;\n    run.abort();\n    this.run = undefined;\n    if (this.timer) clearTimeout(this.timer);\n    this.timer = undefined;\n  }\n\n  status(): JwksStatus {\n    const fresh =\n      this.lastSuccessAt !== undefined && Date.now() - this.lastSuccessAt < this.opts.maxStaleMs;\n    return {\n      ready: fresh && this.usableKeys > 0,\n      keys: this.usableKeys,\n      lastSuccessAt: this.lastSuccessAt,\n      consecutiveFailures: this.consecutiveFailures,\n      lastError: this.lastError,\n      maintaining: this.run !== undefined,\n    };\n  }\n\n  /**\n   * jose's `customFetch`: the only network path. Records the outcome, and hands\n   * jose either a buffered body or an error -- never a set without a usable key,\n   * so jose never replaces held keys with one.\n   */\n  private async fetch(url: string, init: RequestInit): Promise<Response> {\n    const holdoff = this.retryAfterUntil - Date.now();\n    if (holdoff > 0) {\n      const reason = `issuer asked to retry after ${Math.ceil(holdoff / 1000)}s; not contacted`;\n      this.recordFailure(reason);\n      throw this.error(reason, 0);\n    }\n\n    // A stop cancels a fetch in flight as well as the loop around it.\n    const signal =\n      this.run && init.signal ? AbortSignal.any([init.signal, this.run.signal]) : init.signal;\n    const outcome = await fetchJwksWithRetry(\n      url,\n      { ...init, signal },\n      { ...this.opts, report: (f) => this.report(f) },\n    );\n    if (outcome.ok) {\n      this.usableKeys = outcome.keys;\n      this.lastSuccessAt = Date.now();\n      this.consecutiveFailures = 0;\n      this.lastError = undefined;\n      return new Response(outcome.body, {\n        status: 200,\n        headers: { \"content-type\": \"application/json\" },\n      });\n    }\n    // Cancelled is not a failure: status keeps describing the issuer.\n    if (outcome.cancelled) throw this.error(outcome.reason, outcome.attempt);\n    if (outcome.retryAfterUntil) this.retryAfterUntil = outcome.retryAfterUntil;\n    this.recordFailure(outcome.reason);\n    throw this.error(outcome.reason, outcome.attempt, outcome.status);\n  }\n\n  private recordFailure(reason: string): void {\n    this.consecutiveFailures++;\n    this.lastError = reason;\n  }\n\n  private error(reason: string, attempt: number, status?: number): JwksFetchError {\n    const detail = `${reason}; ${attempt} of ${this.opts.fetchAttempts} attempt(s)`;\n    return new JwksFetchError(this.opts.jwksUrl, undefined, detail, status);\n  }\n\n  private report(failure: JwksFetchFailure): void {\n    try {\n      this.opts.onFetchFailure?.(failure);\n    } catch {\n      // A metrics hook must not change the outcome of a fetch.\n    }\n  }\n}\n","/**\n * How a failed JWKS fetch is retried. Pure functions: no I/O, no state.\n *\n *   network error, timeout          retry\n *   200, not JSON                   retry\n *   408, 429, 5xx                   retry; Retry-After honoured (see fetch.ts)\n *   200, no usable signing key      terminal: it will not change in a second\n *   any other status (400/401/403/  terminal: a wrong URL or a refusal, and\n *   404, 3xx -- redirects are not   repeating it only delays the error\n *   followed for a key set)\n */\n\n/** Whether an HTTP status from the JWKS endpoint is worth another attempt. */\nexport function isRetryableStatus(status: number): boolean {\n  return status === 408 || status === 429 || status >= 500;\n}\n\n/**\n * Delay before attempt `n + 1`, with full jitter (ADR-022): uniformly random in\n * [0, min(cap, base * 2^(n-1))], so a fleet failing together does not retry\n * together.\n */\nexport function fullJitterDelay(n: number, baseMs: number, capMs: number): number {\n  return Math.random() * Math.min(capMs, baseMs * 2 ** Math.max(0, n - 1));\n}\n\n/** A Retry-After header (seconds or an HTTP date) as milliseconds from now. */\nexport function parseRetryAfter(header: string | null): number | undefined {\n  if (!header) return undefined;\n  const seconds = Number(header);\n  if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;\n  const date = Date.parse(header);\n  return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());\n}\n","import * as jose from \"jose\";\n\n/**\n * Keys in a JWKS document that can verify a token here. This count is what\n * \"ready\" is defined on, so it must never count a key the verifier would reject.\n *\n * So the verifier decides. Each key goes through jose's own local selection, the\n * filter `jwtVerify` applies to the remote set, followed by the import. In jose\n * 6.2.12 (`isUsableJWK`) that is: `kty` for the algorithm; `alg`, when present,\n * equal to it; `use`, when present, `sig`; `key_ops`, when present, unique\n * strings including `verify`; `ext`, when present, a boolean; `crv` for EC.\n * Re-implementing it here would be a second copy free to drift from the first --\n * 6.2.12 already tightened `key_ops` and added `ext` over 6.2.9.\n *\n * A private or symmetric key is refused on top: it is not a public signing key,\n * whatever jose would make of it.\n */\nexport async function countUsableKeys(json: unknown, algorithms: string[]): Promise<number> {\n  const keys = (json as { keys?: unknown })?.keys;\n  if (!Array.isArray(keys)) return 0;\n  let usable = 0;\n  for (const jwk of keys as jose.JWK[]) {\n    if (await isUsable(jwk, algorithms)) usable++;\n  }\n  return usable;\n}\n\nasync function isUsable(jwk: jose.JWK, algorithms: string[]): Promise<boolean> {\n  if (typeof jwk !== \"object\" || jwk === null) return false;\n  if (\"d\" in jwk || jwk.kty === \"oct\") return false; // private or symmetric\n  let select: ReturnType<typeof jose.createLocalJWKSet>;\n  try {\n    // One key per set, so a document of several keys never answers \"multiple\n    // matching keys\" for a header that names no kid.\n    select = jose.createLocalJWKSet({ keys: [jwk] });\n  } catch {\n    return false;\n  }\n  for (const alg of algorithms) {\n    try {\n      await select({ alg });\n      return true;\n    } catch {\n      // Not selected, or not importable, for this algorithm; try the next.\n    }\n  }\n  return false;\n}\n","import { fullJitterDelay, isRetryableStatus, parseRetryAfter } from \"./retry-policy.js\";\nimport { countUsableKeys } from \"./usable-keys.js\";\n\n/** One failed attempt, reported to `onFetchFailure`. */\nexport interface JwksFetchFailure {\n  url: string;\n  attempt: number;\n  attempts: number;\n  /** What happened: timeout, network error, HTTP status, malformed or unusable key set. */\n  reason: string;\n  status?: number;\n  /** Whether another attempt follows within this fetch. */\n  retrying: boolean;\n}\n\nexport interface FetchPolicy {\n  fetchTimeoutMs: number;\n  fetchAttempts: number;\n  retryBaseMs: number;\n  retryMaxMs: number;\n  algorithms: string[];\n  report: (failure: JwksFetchFailure) => void;\n}\n\nexport type FetchOutcome =\n  | { ok: true; body: string; keys: number }\n  /**\n   * Stopped by the caller or by shutdown: not a dependency failure. Never\n   * reported to `onFetchFailure` and never counted against the issuer.\n   */\n  | { ok: false; cancelled: true; reason: string; attempt: number }\n  | {\n      ok: false;\n      cancelled?: false;\n      reason: string;\n      attempt: number;\n      status?: number;\n      /** Set when the issuer asked for longer than `retryMaxMs`: contact it no sooner. */\n      retryAfterUntil?: number;\n    };\n\n/** What one attempt produced, before the retry decision. */\ntype Attempt =\n  | { ok: true; body: string; keys: number }\n  | { ok: false; cancelled: true; reason: string }\n  | {\n      ok: false;\n      cancelled?: false;\n      reason: string;\n      status?: number;\n      retryable: boolean;\n      retryAfterMs?: number;\n    };\n\n/**\n * One JWKS fetch, attempted up to `fetchAttempts` times.\n *\n * The body is read inside the attempt's timeout, so a stall mid-body is a timed\n * out attempt and not a parse error. A response counts only if it holds a usable\n * signing key. Never throws: the caller turns a failed outcome into an error.\n *\n * An abort of `init.signal` (the caller, or the cache's shutdown) ends it as\n * `cancelled`, and is not reported: a deployment stopping is not the issuer\n * being unavailable, and ADR-022's dependency metrics must not say it was.\n */\nexport async function fetchJwksWithRetry(\n  url: string,\n  init: RequestInit,\n  policy: FetchPolicy,\n): Promise<FetchOutcome> {\n  const outer = init.signal ?? undefined;\n  let attempt = 0;\n  for (;;) {\n    attempt++;\n    const result = await attemptOnce(url, init, outer, policy);\n    if (result.ok) return result;\n    if (result.cancelled) return { ok: false, cancelled: true, reason: result.reason, attempt };\n\n    const longWait = result.retryAfterMs !== undefined && result.retryAfterMs > policy.retryMaxMs;\n    const retrying = result.retryable && !longWait && attempt < policy.fetchAttempts;\n    policy.report({\n      url,\n      attempt,\n      attempts: policy.fetchAttempts,\n      reason: result.reason,\n      status: result.status,\n      retrying,\n    });\n\n    if (!retrying) {\n      return {\n        ok: false,\n        reason: result.reason,\n        attempt,\n        status: result.status,\n        retryAfterUntil:\n          result.retryAfterMs !== undefined && longWait\n            ? Date.now() + result.retryAfterMs\n            : undefined,\n      };\n    }\n    const wait =\n      result.retryAfterMs !== undefined\n        ? result.retryAfterMs + Math.random() * policy.retryBaseMs\n        : fullJitterDelay(attempt, policy.retryBaseMs, policy.retryMaxMs);\n    if (!(await sleep(wait, outer))) {\n      return { ok: false, cancelled: true, reason: \"cancelled while waiting to retry\", attempt };\n    }\n  }\n}\n\n/** Wait `ms`, or less if `signal` aborts. Resolves false when aborted. The timer never outlives the abort. */\nfunction sleep(ms: number, signal: AbortSignal | undefined): Promise<boolean> {\n  if (signal?.aborted) return Promise.resolve(false);\n  return new Promise((resolve) => {\n    const onAbort = () => {\n      clearTimeout(timer);\n      resolve(false);\n    };\n    const timer = setTimeout(() => {\n      signal?.removeEventListener(\"abort\", onAbort);\n      resolve(true);\n    }, ms);\n    signal?.addEventListener(\"abort\", onAbort, { once: true });\n  });\n}\n\nasync function attemptOnce(\n  url: string,\n  init: RequestInit,\n  outer: AbortSignal | undefined,\n  policy: FetchPolicy,\n): Promise<Attempt> {\n  const timeout = AbortSignal.timeout(policy.fetchTimeoutMs);\n  const signal = outer ? AbortSignal.any([outer, timeout]) : timeout;\n  const started = Date.now();\n  try {\n    const res = await fetch(url, { ...init, signal });\n    if (res.status !== 200) {\n      await res.body?.cancel().catch(() => {});\n      const retryAfterMs = isRetryableStatus(res.status)\n        ? parseRetryAfter(res.headers.get(\"retry-after\"))\n        : undefined;\n      const reason = `HTTP ${res.status}${retryAfterMs !== undefined ? `, Retry-After ${Math.ceil(retryAfterMs / 1000)}s` : \"\"}`;\n      return {\n        ok: false,\n        reason,\n        status: res.status,\n        retryable: isRetryableStatus(res.status),\n        retryAfterMs,\n      };\n    }\n\n    const body = await res.text();\n    let json: unknown;\n    try {\n      json = JSON.parse(body);\n    } catch {\n      const type = res.headers.get(\"content-type\") ?? \"none\";\n      return {\n        ok: false,\n        reason: `response is not JSON (${body.length} bytes, content-type ${type})`,\n        status: 200,\n        retryable: true,\n      };\n    }\n    const keys = await countUsableKeys(json, policy.algorithms);\n    if (keys === 0) {\n      return {\n        ok: false,\n        reason: `key set has no usable signing key for ${policy.algorithms.join(\", \")}`,\n        status: 200,\n        retryable: false,\n      };\n    }\n    return { ok: true, body, keys };\n  } catch (err) {\n    const elapsed = Date.now() - started;\n    if (outer?.aborted)\n      return { ok: false, cancelled: true, reason: `cancelled after ${elapsed}ms` };\n    if (timeout.aborted) {\n      return {\n        ok: false,\n        reason: `timed out after ${elapsed}ms (limit ${policy.fetchTimeoutMs}ms, headers and body)`,\n        retryable: true,\n      };\n    }\n    const code = (err as { cause?: { code?: string } }).cause?.code ?? (err as Error).message;\n    return { ok: false, reason: `network error: ${code}`, retryable: true };\n  }\n}\n","import type { JwksFetchFailure } from \"./fetch.js\";\n\n/** What a JwksCache can be configured with. Every field but `jwksUrl` has a default. */\nexport interface JwksCacheOptions {\n  /** JWKS endpoint URL. `https:`; `http:` only for a loopback host or with `allowInsecureHttp`. */\n  jwksUrl: string;\n  /**\n   * Permit `http:` to a non-loopback host. For a development stack that has no\n   * TLS in front of its issuer; never for a deployed environment, where the key\n   * set is the root of every token's trust and must not be fetched in the clear.\n   */\n  allowInsecureHttp?: boolean;\n  /** Background refresh period once `start()` has been called, ms (default 300000 = 5 min). */\n  keyTtlMs?: number;\n  /**\n   * Oldest a key set may be and still be used, ms (default 900000 = 15 min).\n   * Past it, a request refetches before verifying and `status().ready` is false.\n   * Bounds how long a key the issuer has withdrawn can still verify a token.\n   */\n  maxStaleMs?: number;\n  /** Minimum interval between refetches caused by a token naming an unknown `kid`, ms (default 10000). */\n  refreshIntervalMs?: number;\n  /** Timeout for ONE fetch attempt, headers and body together, ms (default 10000). */\n  fetchTimeoutMs?: number;\n  /** Attempts within one fetch, i.e. while a request waits (default 2 -- one retry). */\n  fetchAttempts?: number;\n  /** Full-jitter backoff base, ms (default 250). */\n  retryBaseMs?: number;\n  /** Cap on the pause between attempts while a request waits, ms (default 2000). */\n  retryMaxMs?: number;\n  /** Cap on the background backoff while the issuer is unavailable, ms (default and maximum 300000 -- ADR-022). */\n  backoffMaxMs?: number;\n  /** Algorithms a key must support to count as usable (default: RS256, ES256). */\n  algorithms?: string[];\n  /**\n   * Called on every failed attempt, with the full detail. Where an application\n   * increments `dependency_unavailable_total` (ADR-022). Must not throw; if it\n   * does, the error is ignored.\n   */\n  onFetchFailure?: (failure: JwksFetchFailure) => void;\n}\n\n/** The options after validation: every value present and within bounds. */\nexport interface ResolvedJwksOptions {\n  jwksUrl: string;\n  keyTtlMs: number;\n  maxStaleMs: number;\n  refreshIntervalMs: number;\n  fetchTimeoutMs: number;\n  fetchAttempts: number;\n  retryBaseMs: number;\n  retryMaxMs: number;\n  backoffMaxMs: number;\n  algorithms: string[];\n  onFetchFailure?: (failure: JwksFetchFailure) => void;\n}\n\n/** ADR-022: backoff is capped at five minutes. */\nexport const ADR_022_BACKOFF_CAP_MS = 5 * 60_000;\n\nconst DEFAULTS = {\n  keyTtlMs: 5 * 60_000,\n  maxStaleMs: 15 * 60_000,\n  refreshIntervalMs: 10_000,\n  fetchTimeoutMs: 10_000,\n  fetchAttempts: 2,\n  retryBaseMs: 250,\n  retryMaxMs: 2_000,\n  backoffMaxMs: ADR_022_BACKOFF_CAP_MS,\n  algorithms: [\"RS256\", \"ES256\"],\n};\n\n/**\n * Validate, never normalise: a wrong value is a configuration error, and\n * silently rounding it would run the service on a policy nobody chose.\n * Throws RangeError for a value out of bounds, TypeError for an unparseable URL.\n */\nexport function resolveJwksOptions(opts: JwksCacheOptions): ResolvedJwksOptions {\n  const jwksUrl = checkedUrl(opts.jwksUrl, opts.allowInsecureHttp ?? false);\n  const fetchTimeoutMs = int(\n    \"fetchTimeoutMs\",\n    opts.fetchTimeoutMs,\n    DEFAULTS.fetchTimeoutMs,\n    100,\n    60_000,\n  );\n  const fetchAttempts = int(\"fetchAttempts\", opts.fetchAttempts, DEFAULTS.fetchAttempts, 1, 5);\n  const retryBaseMs = int(\"retryBaseMs\", opts.retryBaseMs, DEFAULTS.retryBaseMs, 0, 10_000);\n  const retryMaxMs = int(\"retryMaxMs\", opts.retryMaxMs, DEFAULTS.retryMaxMs, retryBaseMs, 30_000);\n  const backoffMaxMs = int(\n    \"backoffMaxMs\",\n    opts.backoffMaxMs,\n    DEFAULTS.backoffMaxMs,\n    retryBaseMs,\n    ADR_022_BACKOFF_CAP_MS,\n  );\n  const keyTtlMs = int(\"keyTtlMs\", opts.keyTtlMs, DEFAULTS.keyTtlMs, 1_000, 24 * 3_600_000);\n  const maxStaleMs = int(\n    \"maxStaleMs\",\n    opts.maxStaleMs,\n    Math.max(DEFAULTS.maxStaleMs, keyTtlMs),\n    keyTtlMs,\n    7 * 24 * 3_600_000,\n  );\n  const refreshIntervalMs = int(\n    \"refreshIntervalMs\",\n    opts.refreshIntervalMs,\n    Math.min(DEFAULTS.refreshIntervalMs, keyTtlMs),\n    0,\n    keyTtlMs,\n  );\n  const algorithms = opts.algorithms ?? DEFAULTS.algorithms;\n  if (algorithms.length === 0) {\n    throw new RangeError(\"JwksCacheOptions.algorithms must name at least one algorithm\");\n  }\n  return {\n    jwksUrl,\n    keyTtlMs,\n    maxStaleMs,\n    refreshIntervalMs,\n    fetchTimeoutMs,\n    fetchAttempts,\n    retryBaseMs,\n    retryMaxMs,\n    backoffMaxMs,\n    algorithms,\n    onFetchFailure: opts.onFetchFailure,\n  };\n}\n\nconst LOOPBACK = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\"]);\n\n/** A JWKS URL this runtime may fetch from. TypeError when unparseable, RangeError when not permitted. */\nfunction checkedUrl(raw: string, allowInsecureHttp: boolean): string {\n  const url = new URL(raw);\n  if (url.protocol === \"https:\") return url.href;\n  if (url.protocol === \"http:\" && (allowInsecureHttp || LOOPBACK.has(url.hostname)))\n    return url.href;\n  throw new RangeError(\n    `JwksCacheOptions.jwksUrl must be https:` +\n      (url.protocol === \"http:\"\n        ? ` (http: is permitted only for a loopback host, or with allowInsecureHttp)`\n        : \"\") +\n      `, got ${url.protocol}//${url.host}`,\n  );\n}\n\nfunction int(\n  name: string,\n  value: number | undefined,\n  fallback: number,\n  min: number,\n  max: number,\n): number {\n  const v = value ?? fallback;\n  if (!Number.isInteger(v) || v < min || v > max) {\n    throw new RangeError(\n      `JwksCacheOptions.${name} must be an integer in [${min}, ${max}], got ${String(value)}`,\n    );\n  }\n  return v;\n}\n","import * as jose from \"jose\";\nimport {\n  AuthError,\n  CallerNotAllowedError,\n  IdTokenPresentedError,\n  InvalidAudienceError,\n  InvalidIssuerError,\n  TenantMismatchError,\n  TokenExpiredError,\n  TokenMissingError,\n} from \"../types.js\";\nimport { claimsFromPayload, type TenantClaims } from \"./claims.js\";\nimport { JwksCache, type JwksStatus } from \"./jwks-cache.js\";\n\nexport interface JwtValidatorOptions {\n  /** JWKS endpoint URL */\n  jwksUrl: string;\n  /** Expected issuer — if provided, validation fails when issuer mismatches */\n  issuer?: string;\n  /** Expected audience — if provided, validation fails when audience mismatches */\n  audience?: string;\n  /** Allowed signing algorithms (default: [\"RS256\", \"ES256\"]) */\n  algorithms?: string[];\n  /** JWKS cache options */\n  jwksCache?: Partial<import(\"./jwks-cache.js\").JwksCacheOptions>;\n  /**\n   * Require a tenant claim. Default true.\n   *\n   * Set false only for a validator guarding a platform-scoped surface where no\n   * identity is expected to carry a tenant. A tenant-scoped service must leave\n   * this on: without it, a token minted for no tenant is accepted wherever\n   * tenant isolation is the boundary.\n   */\n  requireTenantId?: boolean;\n  /**\n   * The tenant this receiver belongs to. A token carrying a DIFFERENT tenant is\n   * refused (ADR-094 invariant 3).\n   *\n   * `requireTenantId` asks only that the claim exist, which is not isolation: a\n   * user of another tenant carries a valid tenant claim, just not this one.\n   * Omit this ONLY on a platform-scoped surface that no single tenant owns, and\n   * say so where you omit it.\n   */\n  expectedTenantId?: string;\n  /**\n   * Refuse a token that carries `at_hash`. Default true.\n   *\n   * A ZITADEL COMPATIBILITY INVARIANT, not a general OIDC rule. OIDC Core\n   * requires `at_hash` only where an access token is returned from the\n   * authorization endpoint (implicit and hybrid); in the authorization-code flow\n   * this platform uses it is OPTIONAL, so a conforming issuer may omit it. What\n   * holds is narrower and version-scoped:\n   *\n   *   for the pinned Zitadel, every ID token carries `at_hash` and no JWT\n   *   access token does -- `createIDToken` is the only place that sets it, and\n   *   it is called with a non-empty access token on every token-endpoint path.\n   *\n   * Re-establish it before trusting a different issuer or a Zitadel upgrade; an\n   * issuer that stops emitting it does not fail this check, it silently passes.\n   *\n   * It is a claim check rather than an audience check because in Zitadel the two\n   * tokens share an audience: `createIDToken` and `createJWT` are both handed\n   * `session.Audience`, so no audience distinguishes them.\n   *\n   * Sound against a hostile caller regardless: `at_hash` is signed, so it cannot\n   * be stripped from a genuine ID token without invalidating the signature.\n   *\n   * ORDERING. A deployment whose gateway still forwards the ID token will have\n   * EVERY request refused by this. The gateway must be forwarding an exchanged\n   * access token first (ADR-095 step 1); adopting the SDK version that carries\n   * this default is step 2, and the two are separate deploys on purpose.\n   *\n   * Set false only to stage that ordering on a box that cannot do both at once.\n   * It is not a setting to leave off: off, the confusion this exists to catch is\n   * a configuration slip away.\n   */\n  rejectIdTokens?: boolean;\n  /**\n   * The applications permitted to present a token here, by `azp`/`client_id`\n   * (ADR-094 invariant 2).\n   *\n   * THE cross-application control. An audience says a token may be accepted\n   * here; it does not say who asked for it, and Zitadel issues any project's\n   * audience to any client that requests it -- so a receiver checking only\n   * `aud` accepts a token any application on the box could mint for it. This is\n   * the check that distinguishes them.\n   *\n   * Absence of `azp` is a REFUSAL, not a pass. A token with no caller identity\n   * cannot be matched against an allowlist, and treating \"cannot tell\" as\n   * \"allowed\" is the failure this exists to prevent.\n   *\n   * Omitted (or empty) means no caller check, which is correct only where a\n   * receiver is unreachable by any other application. Say so where you omit it.\n   */\n  allowedAzp?: string[];\n  /**\n   * The callers this receiver admits, what each one is called, and what its\n   * tokens carry: `{ \"<azp>\": { appId, kind } }`.\n   *\n   * A MAP where `allowedAzp` is a list, and the difference is not cosmetic. A\n   * list says a caller may enter; it does not say who entered. A receiver that\n   * owns records per consuming application — waypoint ADR-042 partitions chat\n   * sessions and runs by `consumer_app_id` — would then have to take the name\n   * from the request, which is precisely what ADR-094 invariant 2b forbids.\n   *\n   * Only the platform can supply this. It knows both halves when it renders the\n   * allowlist, and neither end can be trusted to assert it: the caller would be\n   * naming itself, and the receiver has nothing to derive it from.\n   *\n   * The KIND is what the client's tokens carry (ADR-110): `user` for the client\n   * an application's backend obtains its users' tokens with, `service` for the\n   * machine client it calls as itself. The token cannot say which -- `azp` and\n   * `client_id` are one field here -- so only the platform, which provisioned\n   * the client, can.\n   *\n   * Set gate, name and kind together: a token whose `azp` is absent here is\n   * refused exactly as `allowedAzp` refuses, and one that passes arrives with\n   * `consumer_app_id` and `caller_kind` set on its claims. Supply this or\n   * `allowedAzp`, not both; if both are given this one decides, because it is\n   * the stricter statement.\n   *\n   * Build it from the platform's `OIDC_ALLOWED_AZP` with `parseAllowedCallers`.\n   */\n  allowedCallers?: Record<string, AllowedCaller>;\n}\n\n/** What a caller-map entry's tokens carry (ADR-110). */\nexport type CallerKind = \"user\" | \"service\";\n\n/** One admitted caller: the application its client belongs to, and its kind. */\nexport interface AllowedCaller {\n  appId: string;\n  kind: CallerKind;\n}\n\n/**\n * Read the platform's `OIDC_ALLOWED_AZP` into a caller map.\n *\n * The value is space- or comma-separated `<clientId>=<applicationId>:<kind>`\n * entries, kind being `user` or `service` (ADR-110).\n *\n * AN ENTRY WITHOUT AN APPLICATION AND A KIND ADMITS NOTHING, and is left out.\n * Those are values written before kinds existed; the platform re-renders each\n * caller's entries on that caller's next reconcile. Until then its tokens are\n * refused as CALLER_NOT_ALLOWED, which fails closed -- the alternative, admitting\n * a client without knowing whether its tokens carry a person, is the defect\n * kinds exist to remove.\n */\nexport function parseAllowedCallers(value: string | undefined): Record<string, AllowedCaller> {\n  const out: Record<string, AllowedCaller> = {};\n  for (const entry of (value ?? \"\").replace(/,/g, \" \").split(/\\s+/)) {\n    if (!entry) continue;\n    const eq = entry.indexOf(\"=\");\n    if (eq <= 0) continue;\n    const named = entry.slice(eq + 1);\n    const colon = named.lastIndexOf(\":\");\n    if (colon <= 0) continue;\n    const appId = named.slice(0, colon);\n    const kind = named.slice(colon + 1);\n    if (kind !== \"user\" && kind !== \"service\") continue;\n    out[entry.slice(0, eq)] = { appId, kind };\n  }\n  return out;\n}\n\nexport class JwtValidator {\n  private readonly jwksCache: JwksCache;\n  private readonly issuer?: string;\n  private readonly audience?: string;\n  private readonly algorithms: string[];\n  private readonly requireTenantId: boolean;\n  private readonly rejectIdTokens: boolean;\n  private readonly allowedAzp: string[];\n  private readonly allowedCallers?: Record<string, AllowedCaller>;\n  private readonly expectedTenantId?: string;\n\n  constructor(opts: JwtValidatorOptions) {\n    this.issuer = opts.issuer;\n    this.audience = opts.audience;\n    this.algorithms = opts.algorithms ?? [\"RS256\", \"ES256\"];\n    this.requireTenantId = opts.requireTenantId ?? true;\n    this.rejectIdTokens = opts.rejectIdTokens ?? true;\n    this.allowedAzp = opts.allowedAzp ?? [];\n    this.allowedCallers = opts.allowedCallers;\n    this.expectedTenantId = opts.expectedTenantId;\n\n    this.jwksCache = new JwksCache({\n      jwksUrl: opts.jwksUrl,\n      algorithms: this.algorithms,\n      ...opts.jwksCache,\n    });\n  }\n\n  /**\n   * Keep the issuer's keys held until stop() or `signal` aborts (ADR-022). Call once\n   * at boot; report `status().ready` from the readiness probe. Never throws: an\n   * unreachable issuer leaves the service alive and unready until it returns.\n   */\n  start(options?: { signal?: AbortSignal }): void {\n    this.jwksCache.start(options);\n  }\n\n  stop(): void {\n    this.jwksCache.stop();\n  }\n\n  /** Whether tokens can be verified now, and why not. See JwksStatus. */\n  status(): JwksStatus {\n    return this.jwksCache.status();\n  }\n\n  /** One fetch of the keys, awaited. Rejects with JwksFetchError. Prefer `start()`. */\n  async warm(): Promise<void> {\n    await this.jwksCache.warm();\n  }\n\n  /**\n   * Validate a JWT and return typed tenant claims.\n   * Throws on expired, invalid issuer, invalid audience, or missing required claims.\n   */\n  async validate(token: string): Promise<TenantClaims> {\n    if (!token) {\n      throw new TokenMissingError();\n    }\n\n    try {\n      const key = await this.jwksCache.getSigningKey();\n\n      const verifyOptions: jose.JWTVerifyOptions = {\n        algorithms: this.algorithms as jose.JWSAlgorithm[],\n      };\n      if (this.issuer) {\n        verifyOptions.issuer = this.issuer;\n      }\n      if (this.audience) {\n        verifyOptions.audience = this.audience;\n      }\n\n      const { payload } = await jose.jwtVerify(token, key, verifyOptions);\n\n      // Checked on the VERIFIED payload, and before anything is derived from it.\n      //\n      // On the verified payload because an unverified one would let a forged\n      // claim decide, and the point is to reject a genuine token of the wrong\n      // kind -- not to guess at an untrusted one. Before deriving claims because\n      // a refused token must not reach tenant or role resolution at all: those\n      // read an identity out of it, and an ID token has a perfectly good one.\n      //\n      // Presence is the whole test. The value is a hash of an access token this\n      // service was never given and cannot check, so nothing is gained by\n      // reading it -- an ID token is disqualified by HAVING one.\n      if (this.rejectIdTokens && \"at_hash\" in (payload as Record<string, unknown>)) {\n        throw new IdTokenPresentedError();\n      }\n\n      const claims = claimsFromPayload(payload as Record<string, unknown>);\n\n      // Checked BEFORE the tenant requirement below, deliberately. A token from\n      // an application this receiver does not admit is refused for that reason\n      // and not for whatever else happens to be wrong with it -- an operator\n      // told MISSING_TENANT_ID would go looking at scopes when the answer is\n      // that the caller should not be here at all.\n      // The map decides where one is given: it is the stricter statement, and a\n      // receiver that supplied both meant the one that also names the caller.\n      if (this.allowedCallers !== undefined) {\n        const permitted = Object.keys(this.allowedCallers);\n        if (claims.azp === undefined || !(claims.azp in this.allowedCallers)) {\n          throw new CallerNotAllowedError(claims.azp, permitted);\n        }\n        // Set from the ALLOWLIST, never from the token. The token says which\n        // client asked for it; only the platform's map says which application\n        // that client belongs to, and a token cannot be allowed to assert its\n        // own application (ADR-094 invariant 2b).\n        //\n        // The kind likewise: whether this token may be read as a PERSON is the\n        // platform's statement about the client, never the token's (ADR-110).\n        const caller = this.allowedCallers[claims.azp];\n        claims.consumer_app_id = caller.appId;\n        claims.caller_kind = caller.kind;\n      } else if (\n        this.allowedAzp.length > 0 &&\n        (claims.azp === undefined || !this.allowedAzp.includes(claims.azp))\n      ) {\n        throw new CallerNotAllowedError(claims.azp, this.allowedAzp);\n      }\n\n      // No platform-scoped exemption, deliberately.\n      //\n      // One existed while the tenant was an ATTRIBUTE written onto an identity,\n      // because an identity could then be created with none — so a platform\n      // admin had to be excused from a rule everyone else obeyed, and the excuse\n      // was a group string, which is a hole widened by anything that can claim\n      // to hold it.\n      //\n      // Where the tenant OWNS the identity instead, a tenant-less identity is\n      // not expressible: a platform admin belongs to the platform's own tenant\n      // and carries it like anyone else. There is no longer a state for the\n      // exemption to model, so the rule applies to everyone without one\n      // (ADR-059).\n      if (this.requireTenantId && !claims.tenant_id) {\n        throw new AuthError({\n          code: \"MISSING_TENANT_ID\",\n          message: \"Token missing required tenant_id claim\",\n        });\n      }\n\n      // COMPARED, not merely required (ADR-094 invariant 3).\n      //\n      // Requiring the claim to be PRESENT is not tenant isolation. Zitadel mints\n      // the tenant from the subject's own organisation, so a user of another\n      // tenant presents a token carrying a perfectly good tenant claim -- a\n      // different one. A receiver that only checks presence accepts it and then\n      // reads an identity out of it.\n      //\n      // Absent from `expectedTenantId`, this check does not run, which is\n      // correct only for a platform-scoped surface where no single tenant owns\n      // the receiver. Every tenant-scoped receiver must set it.\n      if (this.expectedTenantId !== undefined && claims.tenant_id !== this.expectedTenantId) {\n        throw new TenantMismatchError(this.expectedTenantId, claims.tenant_id);\n      }\n\n      return claims;\n    } catch (err) {\n      if (err instanceof AuthError) throw err;\n\n      const joseErr = err as { code?: string; message?: string };\n\n      if (joseErr.code === \"ERR_JWT_EXPIRED\") {\n        throw new TokenExpiredError(undefined, err);\n      }\n      // jose v6 reports both issuer and audience mismatches as\n      // ERR_JWT_CLAIM_VALIDATION_FAILED and names the offending claim on `claim`.\n      // The previous code tested \"ERR_JWT_INVALIDIssuer\" and\n      // \"ERR_JWT_INVALID_AUDIENCE\" — neither is emitted — so InvalidIssuerError and\n      // InvalidAudienceError were unreachable and a P0-1 audience violation looked\n      // identical to any other malformed token.\n      const claim = (err as { claim?: string }).claim;\n      if (joseErr.code === \"ERR_JWT_CLAIM_VALIDATION_FAILED\") {\n        // Report the claim's VALUE, not its name. Both errors take (expected,\n        // actual) and were being handed `claim`, which is the string \"iss\" or\n        // \"aud\" — so an audience mismatch read `expected \"<...>\", got \"\"aud\"\"`,\n        // naming the field instead of what the token actually carried. The one\n        // fact needed to diagnose the mismatch was the one thing omitted.\n        //\n        // Decoded without verification, and only to build the message: the token\n        // has already failed validation and nothing here is trusted or returned.\n        const actual = decodeClaimForDiagnostics(token, claim);\n        if (claim === \"iss\") {\n          throw new InvalidIssuerError(this.issuer ?? \"\", describeClaim(actual));\n        }\n        if (claim === \"aud\") {\n          throw new InvalidAudienceError(this.audience ?? \"\", describeClaim(actual));\n        }\n      }\n\n      throw new AuthError({\n        code: \"TOKEN_INVALID\",\n        message: `Token validation failed: ${joseErr.message ?? String(err)}`,\n        cause: err,\n      });\n    }\n  }\n}\n\n/**\n * Reads one claim out of an unverified token, for error messages only.\n *\n * The token reaching here has already failed verification, so the value is\n * untrusted by construction and is used solely to say what was seen. Returns\n * undefined rather than throwing: a malformed token must not turn a claim\n * mismatch into a different error on the way out.\n */\nfunction describeClaim(value: unknown): string {\n  if (value === undefined) return \"<absent>\";\n  if (typeof value === \"string\") return value;\n  return JSON.stringify(value);\n}\n\nfunction decodeClaimForDiagnostics(token: string, claim: string | undefined): unknown {\n  if (!claim) return undefined;\n  try {\n    return (jose.decodeJwt(token) as Record<string, unknown>)[claim];\n  } catch {\n    return undefined;\n  }\n}\n","import type { TenantClaims } from \"../jwt/claims.js\";\nimport type { ResolvedUser, ResolveUserOptions, SqlExecutor, SqlTransactor } from \"./types.js\";\n\n// The issuer this platform runs.\n//\n// It was \"ory\" until 2026-09-30 -- a default carried over from an identity\n// provider that preceded Zitadel. Nothing failed for as long as it was wrong,\n// because this value is only ever compared against itself: the library writes it,\n// looks a person up by it, and matches. A wrong name stays consistent with itself\n// and is invisible to every test of resolution. It was found by reading a row.\n//\n// `identities` is UNIQUE(provider, provider_user_id), so this value and the\n// stored one must move together. If you ever change it, rewrite the stored rows\n// in the same change -- otherwise every existing identity becomes unreachable,\n// resolution judges each person new, and a SECOND user row is created for them.\n// That insert succeeds, so nothing reports it.\nconst DEFAULT_PROVIDER = \"zitadel\";\nconst DEFAULT_SCHEMA = \"public\";\n\n/** Reject anything that could not be a bare SQL identifier. */\nfunction ident(name: string, what: string): string {\n  if (!/^[a-z_][a-z0-9_]*$/i.test(name)) {\n    throw new Error(`invalid ${what}: ${name}`);\n  }\n  return name;\n}\n\n/**\n * Resolve the tenant-local user for a validated set of OIDC claims, creating one\n * on first sight.\n *\n * WHY THIS IS A PLATFORM CONCERN\n *\n * The platform's tenant baseline ships `users` and `identities` in every tenant\n * database, with row-level security keyed on a tenant-local user id. Nothing\n * populated them: the identity provider knows a subject, the tenant's tables\n * expect a local uuid, and the mapping between the two is exactly what\n * `identities` exists to hold. Left to each tenant, this is the same fifty lines\n * written repeatedly and wrongly — most often by joining on email, which is the\n * bug described below.\n *\n * THE JOIN KEY IS THE SUBJECT, NEVER THE EMAIL\n *\n * Email is mutable in the identity provider and can be reassigned between people.\n * Joining on it silently merges two accounts the moment an address is changed or\n * reused, and the failure is a data-disclosure one rather than an error. The\n * subject is stable for the life of the identity, which is what\n * `identities.provider_user_id` is for.\n *\n * Email is still recorded and refreshed, because a tenant needs to display it —\n * but it is a property of the user, not a way to find them.\n *\n * CONCURRENCY\n *\n * Two requests from one person arriving together will both find nothing and both\n * insert. The unique constraint on (provider, provider_user_id) is what makes\n * that safe: the loser takes the `ON CONFLICT DO NOTHING` path and re-reads the\n * winner's row. This runs in one transaction so a failure cannot leave a `users`\n * row with no linked identity — an orphan that would be found by nothing and\n * re-created on every subsequent request.\n */\nexport async function resolveUser(\n  db: SqlTransactor,\n  claims: TenantClaims,\n  options: ResolveUserOptions = {},\n): Promise<ResolvedUser> {\n  const provider = options.provider ?? DEFAULT_PROVIDER;\n  const schema = ident(options.schema ?? DEFAULT_SCHEMA, \"schema\");\n\n  if (!claims.sub) {\n    throw new Error(\"cannot resolve a user from claims without a subject\");\n  }\n  // claimsFromPayload defaults a missing email to \"\", not undefined, so an\n  // emptiness check is required rather than a null check.\n  const email = claims.email || null;\n\n  return db.transaction(async (tx) => {\n    // THE APPLICATION'S OWN TABLES, READ AND WRITTEN DIRECTLY.\n    //\n    // This briefly called a SECURITY DEFINER function the platform created in the\n    // tenant's database, because ADR-093 had taken these tables away from the\n    // application and row-level security then blocked a lookup that runs BEFORE\n    // any user context exists. Both are gone: the platform provisions a database\n    // and a role, and everything inside it is the application's, so there is no\n    // privilege here the caller lacks and no function for the platform to own.\n    //\n    // What survives is the part that was never about privilege -- the race, and\n    // the rule about email below.\n    const found = await tx.query<{ user_id: string; email: string | null }>(\n      `SELECT i.user_id, u.email\n         FROM ${schema}.identities i\n         JOIN ${schema}.users u ON u.id = i.user_id\n        WHERE i.provider = $1 AND i.provider_user_id = $2`,\n      [provider, claims.sub],\n    );\n\n    if (found[0]) {\n      // Refresh a changed address so the application does not display a stale\n      // one. Guarded on inequality: an unconditional UPDATE would write on every\n      // authenticated request.\n      if (email && email !== found[0].email) {\n        await tx.query(`UPDATE ${schema}.users SET email = $1 WHERE id = $2`, [\n          email,\n          found[0].user_id,\n        ]);\n      }\n      return { userId: found[0].user_id, email: email ?? found[0].email ?? \"\", isNew: false };\n    }\n\n    // FIRST SIGHTING.\n    //\n    // An address is required to create, because `users.email` is NOT NULL in the\n    // shape this expects. Said here, naming the subject, rather than letting the\n    // insert fail: a not-null violation on a column the caller never mentioned is\n    // a confusing way to learn that the login produced no email claim.\n    if (!email) {\n      throw new Error(\n        `cannot provision a user for subject ${claims.sub} without an email claim; ` +\n          `the login must request the \"email\" scope`,\n      );\n    }\n\n    // An address already registered to a DIFFERENT subject is refused rather than\n    // adopted. `users.email` is UNIQUE, so the insert would fail anyway -- but the\n    // reason matters: linking a second subject to an existing person is an\n    // account-linking decision that needs proof the same human holds both, and\n    // silently attaching one is how an address reassigned at the provider hands a\n    // stranger someone else's records.\n    const taken = await tx.query<{ id: string }>(\n      `SELECT id FROM ${schema}.users WHERE email = $1`,\n      [email],\n    );\n    if (taken[0]) {\n      throw new Error(\n        `address is already registered to a different identity; linking subject ` +\n          `${claims.sub} to it requires an explicit verified-linking flow`,\n      );\n    }\n\n    // Two requests from the same person can arrive together, both see nothing\n    // above, and both try to create. The unique constraint on\n    // (provider, provider_user_id) decides it, and `ON CONFLICT DO NOTHING` makes\n    // the loser take a path that returns no row rather than raising.\n    const created = await tx.query<{ id: string }>(\n      `INSERT INTO ${schema}.users (email) VALUES ($1) RETURNING id`,\n      [email],\n    );\n    const candidate = created[0]?.id;\n    if (!candidate) {\n      throw new Error(`could not create a user for subject ${claims.sub}`);\n    }\n\n    const linked = await tx.query<{ user_id: string }>(\n      `INSERT INTO ${schema}.identities (user_id, provider, provider_user_id)\n       VALUES ($1, $2, $3)\n       ON CONFLICT (provider, provider_user_id) DO NOTHING\n       RETURNING user_id`,\n      [candidate, provider, claims.sub],\n    );\n\n    if (linked[0]) {\n      return { userId: linked[0].user_id, email: email ?? \"\", isNew: true };\n    }\n\n    // The loser. Its `users` row is an orphan nothing points at -- exactly the\n    // record ADR-057 names as invisible to every later lookup and re-created on\n    // every request -- so it is removed before adopting the winner. Deleting it\n    // is safe because it was inserted in THIS transaction and nothing else can\n    // have referenced it yet.\n    await tx.query(`DELETE FROM ${schema}.users WHERE id = $1`, [candidate]);\n\n    const winner = await tx.query<{ user_id: string; email: string | null }>(\n      `SELECT i.user_id, u.email\n         FROM ${schema}.identities i\n         JOIN ${schema}.users u ON u.id = i.user_id\n        WHERE i.provider = $1 AND i.provider_user_id = $2`,\n      [provider, claims.sub],\n    );\n    if (!winner[0]) {\n      // The insert conflicted, so a row exists; not finding it means the unique\n      // constraint is not the one this assumes. Surfaced rather than returning an\n      // id of undefined that fails somewhere later.\n      throw new Error(\n        `identity for subject ${claims.sub} conflicted but could not be read back; ` +\n          `check that ${schema}.identities has UNIQUE (provider, provider_user_id)`,\n      );\n    }\n    return { userId: winner[0].user_id, email: email ?? winner[0].email ?? \"\", isNew: false };\n  });\n}\n\n/**\n * Run `fn` in a transaction whose row-level security context is set to this user.\n *\n * FOR AN APPLICATION THAT CHOOSES ROW-LEVEL SECURITY. The platform ships no\n * policies -- it provisions a database and a role, and the schema is the\n * application's -- so nothing here is engaged unless the application wrote a\n * policy that reads\n * `current_setting('request.jwt.claims')::json->>'user_id'`.\n *\n * Worth knowing before adopting it: such a policy binds the application only\n * while the application sets the claim honestly. It catches a handler that forgot\n * a WHERE clause; it does not constrain code that sets a different user_id,\n * because the application holds the connection. That makes it a backstop against\n * developer error, not a security boundary -- which is a fine thing to want, as\n * long as it is not mistaken for the other.\n *\n * TRANSACTION-SCOPED, AND THAT IS NOT A DETAIL\n *\n * set_config's third argument is `is_local`, and it is `true` here. Tenants reach\n * PostgreSQL through PgBouncer in transaction pooling mode, where a server\n * connection is handed to a different client the moment a transaction ends. A\n * session-scoped setting would therefore outlive the request that set it and be\n * inherited by the next tenant user to borrow that connection — every RLS policy\n * would then evaluate against someone else's identity. Local scoping is what\n * makes pooling safe here.\n *\n * The claims are passed as a bound parameter rather than interpolated: SET does\n * not accept parameters, which is exactly why set_config exists, and building the\n * statement by string concatenation would put user-controlled text into SQL.\n */\nexport async function withUserContext<T>(\n  db: SqlTransactor,\n  context: { userId: string; tenantId?: string },\n  fn: (tx: SqlExecutor) => Promise<T>,\n): Promise<T> {\n  const claims = JSON.stringify({\n    user_id: context.userId,\n    ...(context.tenantId ? { tenant_id: context.tenantId } : {}),\n  });\n\n  return db.transaction(async (tx) => {\n    await tx.query(`SELECT set_config('request.jwt.claims', $1, true)`, [claims]);\n    return fn(tx);\n  });\n}\n","import type { Context, Handler, MiddlewareHandler } from \"hono\";\nimport type { TenantClaims } from \"../jwt/claims.js\";\nimport { resolveUser } from \"../user/resolve.js\";\nimport type { ResolveUserOptions, SqlTransactor } from \"../user/types.js\";\nimport { getPrincipal } from \"./hono.js\";\n\nconst ACTING_USER_KEY = \"auth:actingUser\" as const;\n\n/** The acting user, resolved to this app's own `users` row (ADR-057). */\nexport interface ActingUser {\n  /**\n   * Tenant-local user id -- the uuid every ownership column and row-level\n   * security policy keys on. Distinct from `subject`.\n   */\n  userId: string;\n  /** The identity provider's subject. Stable, but meaningful only to it. */\n  subject: string;\n  email: string;\n  tenantId: string;\n  /** True when this request provisioned the user (first sighting). */\n  isNew: boolean;\n}\n\nexport interface ActingUserOptions {\n  /** The app's own database, as the RUNTIME role (ADR-093). */\n  db: SqlTransactor;\n  resolve?: ResolveUserOptions;\n  /** Where resolution failures are reported. Defaults to console.warn. */\n  onError?: (err: unknown) => void;\n}\n\n/**\n * Resolve the validated principal to a tenant-local user, once per request.\n *\n * Mount AFTER `authMiddleware`: this trusts only the principal that middleware\n * established from a validated token, never a header. For an app whose\n * authenticating boundary also holds the database connection -- the common\n * case, which ADR-057 permits -- the two run in one process and nothing is\n * forwarded between them.\n *\n * A failure does not fail the request. ADR-057: absent identity is permitted,\n * unattributed writes are not. The handler that needs an owner calls\n * `requireActingUser()` and fails there, where the requirement is visible.\n */\nexport function actingUserMiddleware(opts: ActingUserOptions): MiddlewareHandler {\n  const report =\n    opts.onError ??\n    ((err: unknown) => {\n      console.warn(\n        \"acting user resolution failed:\",\n        err instanceof Error ? err.message : \"unknown error\",\n      );\n    });\n\n  return async (c, next) => {\n    const principal = getPrincipal(c);\n    if (principal?.subject) {\n      try {\n        // resolveUser reads only sub and email. Built explicitly rather than cast\n        // from the principal, so a claim this library does not intend to pass\n        // cannot reach the resolution function.\n        const claims: TenantClaims = {\n          sub: principal.subject,\n          email: principal.email,\n          tenant_id: principal.tenantId,\n          roles: principal.roles,\n          groups: [],\n        };\n        const user = await resolveUser(opts.db, claims, opts.resolve);\n        const acting: ActingUser = {\n          userId: user.userId,\n          subject: principal.subject,\n          email: user.email,\n          tenantId: principal.tenantId,\n          isNew: user.isNew,\n        };\n        c.set(ACTING_USER_KEY, acting);\n      } catch (err) {\n        report(err);\n      }\n    }\n    await next();\n  };\n}\n\n/** The acting user, or undefined when none was resolved. */\nexport function getActingUser(c: Context): ActingUser | undefined {\n  return c.get(ACTING_USER_KEY) as ActingUser | undefined;\n}\n\n/**\n * The acting user, or a thrown error.\n *\n * For handlers whose work is meaningless without an owner -- anything that\n * creates, mutates or lists a user's own records. Pair with `withUserContext`\n * so the row-level security policies see the same user.\n */\nexport function requireActingUser(c: Context): ActingUser {\n  const user = getActingUser(c);\n  if (!user) {\n    throw new Error(\"this operation requires an acting user, and none was resolved\");\n  }\n  return user;\n}\n\n/**\n * The identity endpoint `zero-ops-auth/client` reads (`GET /api/v1/auth/me`).\n *\n * Mount after `authMiddleware` and `actingUserMiddleware`. The response shape is\n * the client's `UserIdentity`, so every app answers the question the same way:\n * 401 means signed out, and an authenticated person whose tenant-local user\n * could not be resolved is `userId: null` -- signed in, ownership unknown --\n * rather than an error.\n */\nexport function identityHandler(): Handler {\n  return (c) => {\n    const principal = getPrincipal(c);\n    if (!principal?.subject) {\n      return c.json({ error: \"Unauthenticated\" }, 401);\n    }\n    const acting = getActingUser(c);\n    return c.json({\n      user: {\n        userId: acting?.userId ?? null,\n        subject: principal.subject,\n        email: acting?.email || principal.email || null,\n        role: principal.roles[0] ?? null,\n        tenantId: principal.tenantId || null,\n      },\n    });\n  };\n}\n\nexport { ACTING_USER_KEY };\n","import { createHash, randomBytes } from \"node:crypto\";\nimport type { TokenSet } from \"../authz/types.js\";\n\nexport interface OidcClientOptions {\n  /** OIDC issuer URL (e.g., \"https://auth.dev.nutgraf.in\") */\n  issuerUrl: string;\n  /** OAuth client ID */\n  clientId: string;\n  /** OAuth client secret (required for confidential clients) */\n  clientSecret?: string;\n  /** Redirect URI after authorization */\n  redirectUri: string;\n  /** Scopes to request */\n  scopes: string[];\n  /** Expected audience for the access token */\n  audience?: string;\n  /** HTTP fetch timeout in milliseconds (default: 10000) */\n  fetchTimeoutMs?: number;\n}\n\ninterface ProviderDiscovery {\n  authorization_endpoint: string;\n  token_endpoint: string;\n  revocation_endpoint?: string;\n}\n\ninterface TokenResponse {\n  access_token: string;\n  refresh_token?: string;\n  expires_in?: number;\n  scope?: string;\n  token_type?: string;\n  error?: string;\n  error_description?: string;\n}\n\nexport class OidcClient {\n  private readonly opts: OidcClientOptions;\n  private discoveryCache: ProviderDiscovery | null = null;\n  private discoveryPromise: Promise<ProviderDiscovery> | null = null;\n\n  constructor(opts: OidcClientOptions) {\n    this.opts = opts;\n  }\n\n  private async discover(): Promise<ProviderDiscovery> {\n    if (this.discoveryCache) return this.discoveryCache;\n    if (this.discoveryPromise) return this.discoveryPromise;\n\n    this.discoveryPromise = this.doDiscover();\n    try {\n      const result = await this.discoveryPromise;\n      return result;\n    } finally {\n      this.discoveryPromise = null;\n    }\n  }\n\n  private async doDiscover(): Promise<ProviderDiscovery> {\n    const url = `${this.opts.issuerUrl}/.well-known/openid-configuration`;\n    const res = await fetch(url, {\n      signal: AbortSignal.timeout(this.opts.fetchTimeoutMs ?? 10_000),\n    });\n    if (!res.ok) {\n      throw new Error(`OIDC discovery failed: HTTP ${res.status}`);\n    }\n    const doc = (await res.json()) as ProviderDiscovery;\n    this.discoveryCache = doc;\n    return doc;\n  }\n\n  private authHeaders(): Headers {\n    const headers = new Headers();\n    headers.set(\"content-type\", \"application/x-www-form-urlencoded\");\n\n    if (this.opts.clientSecret) {\n      const credentials = Buffer.from(\n        `${encodeURIComponent(this.opts.clientId)}:${encodeURIComponent(this.opts.clientSecret)}`,\n      ).toString(\"base64\");\n      headers.set(\"authorization\", `Basic ${credentials}`);\n    }\n\n    return headers;\n  }\n\n  private async exchangeForTokens(body: Record<string, string>): Promise<TokenSet> {\n    const provider = await this.discover();\n    const form = new URLSearchParams();\n    for (const [key, value] of Object.entries(body)) {\n      form.set(key, value);\n    }\n\n    const res = await fetch(provider.token_endpoint, {\n      method: \"POST\",\n      headers: this.authHeaders(),\n      body: form,\n      signal: AbortSignal.timeout(this.opts.fetchTimeoutMs ?? 10_000),\n    });\n\n    const data = (await res.json().catch(() => ({}))) as TokenResponse;\n\n    if (!res.ok || !data.access_token) {\n      throw new Error(\n        `Token exchange failed: HTTP ${res.status} ${data.error ?? \"\"} ${data.error_description ?? \"\"}`.trim(),\n      );\n    }\n\n    // No assumed lifetime. A token whose expiry is unknown would be held as\n    // valid for however long a guess said, and presented after the issuer had\n    // already expired it.\n    if (typeof data.expires_in !== \"number\" || data.expires_in <= 0) {\n      throw new Error(\n        \"Token exchange failed: the issuer returned no expires_in, so the token's lifetime is unknown\",\n      );\n    }\n    return {\n      accessToken: data.access_token,\n      refreshToken: data.refresh_token ?? null,\n      expiresAt: Date.now() + data.expires_in * 1000,\n      scope: data.scope,\n      tokenType: data.token_type,\n    };\n  }\n\n  /**\n   * Build an authorization URL with optional PKCE support.\n   * Returns the URL, state, and code verifier (if PKCE was used).\n   */\n  async buildAuthorizationUrl(opts?: {\n    state?: string;\n    codeChallenge?: string;\n    codeChallengeMethod?: \"S256\";\n    /**\n     * The verifier matching `codeChallenge`. Passed through to the return value so\n     * a caller can hand both to exchangeCode() without threading it separately —\n     * the previous signature promised a codeVerifier it could never produce.\n     */\n    codeVerifier?: string;\n    additionalParams?: Record<string, string>;\n  }): Promise<{ url: string; state: string; codeVerifier?: string }> {\n    const provider = await this.discover();\n    const state = opts?.state ?? randomBytes(32).toString(\"hex\");\n\n    const params = new URLSearchParams({\n      client_id: this.opts.clientId,\n      response_type: \"code\",\n      redirect_uri: this.opts.redirectUri,\n      scope: this.opts.scopes.join(\" \"),\n      state,\n    });\n\n    if (this.opts.audience) {\n      params.set(\"audience\", this.opts.audience);\n    }\n\n    if (opts?.codeChallenge) {\n      params.set(\"code_challenge\", opts.codeChallenge);\n      params.set(\"code_challenge_method\", opts.codeChallengeMethod ?? \"S256\");\n    }\n\n    if (opts?.additionalParams) {\n      for (const [key, value] of Object.entries(opts.additionalParams)) {\n        params.set(key, value);\n      }\n    }\n\n    return {\n      url: `${provider.authorization_endpoint}?${params.toString()}`,\n      state,\n      // Was a dead ternary that always yielded undefined, so callers had to retain\n      // the verifier from generatePkce() themselves or silently break PKCE.\n      codeVerifier: opts?.codeVerifier,\n    };\n  }\n\n  /**\n   * Generate PKCE code verifier and challenge.\n   */\n  static generatePkce(): { codeVerifier: string; codeChallenge: string } {\n    const codeVerifier = randomBytes(32)\n      .toString(\"base64url\")\n      .replace(/[^a-zA-Z0-9]/g, \"\")\n      .slice(0, 128);\n    const codeChallenge = createHash(\"sha256\").update(codeVerifier).digest(\"base64url\");\n    return { codeVerifier, codeChallenge };\n  }\n\n  /**\n   * Exchange an authorization code for tokens.\n   */\n  async exchangeCode(opts: { code: string; codeVerifier?: string }): Promise<TokenSet> {\n    const body: Record<string, string> = {\n      grant_type: \"authorization_code\",\n      code: opts.code,\n      redirect_uri: this.opts.redirectUri,\n    };\n\n    if (opts.codeVerifier) {\n      body.code_verifier = opts.codeVerifier;\n    }\n\n    return this.exchangeForTokens(body);\n  }\n\n  /**\n   * Refresh an access token using a refresh token.\n   */\n  async refreshTokens(refreshToken: string): Promise<TokenSet> {\n    return this.exchangeForTokens({\n      grant_type: \"refresh_token\",\n      refresh_token: refreshToken,\n    });\n  }\n\n  /**\n   * Revoke a token (access or refresh).\n   */\n  async revokeToken(token: string): Promise<void> {\n    const provider = await this.discover();\n    const endpoint = provider.revocation_endpoint;\n\n    if (!endpoint) {\n      throw new Error(\"OIDC provider does not support token revocation\");\n    }\n\n    const res = await fetch(endpoint, {\n      method: \"POST\",\n      headers: this.authHeaders(),\n      body: new URLSearchParams({\n        token,\n        client_id: this.opts.clientId,\n      }),\n      signal: AbortSignal.timeout(this.opts.fetchTimeoutMs ?? 10_000),\n    });\n\n    if (!res.ok && res.status !== 200) {\n      throw new Error(`Token revocation failed: HTTP ${res.status}`);\n    }\n  }\n}\n","import { createHash, randomBytes } from \"node:crypto\";\n\n/**\n * Generate a cryptographically random OAuth state parameter.\n * Returns a 32-byte hex string.\n */\nexport function generateOAuthState(): string {\n  return randomBytes(32).toString(\"hex\");\n}\n\n/**\n * SHA-256 hash of the state parameter.\n * Used for storing the hash while sending the raw state to the client.\n */\nexport function hashState(state: string): string {\n  return createHash(\"sha256\").update(state).digest(\"hex\");\n}\n","import { createHash, randomBytes } from \"node:crypto\";\nimport type Redis from \"ioredis\";\nimport type { TokenSet } from \"../authz/types.js\";\n\nexport interface PendingOAuthFlow {\n  subject: string;\n  state: string;\n  createdAt: number;\n  /**\n   * The PKCE verifier the flow's authorization request was challenged with,\n   * held server-side until the callback redeems the code with it.\n   */\n  codeVerifier?: string;\n}\n\nexport interface TokenStore {\n  get(subject: string): Promise<TokenSet | null>;\n  put(subject: string, tokens: TokenSet): Promise<void>;\n  delete(subject: string): Promise<void>;\n  acquireRefreshLock(subject: string, ttlMs?: number): Promise<string | null>;\n  releaseRefreshLock(subject: string, owner: string): Promise<boolean>;\n  beginFlow(\n    subject: string,\n    flowTtlMs?: number,\n    codeVerifier?: string,\n  ): Promise<{ state: string; stateHash: string }>;\n  resolveFlow(state: string, flowTtlMs?: number): Promise<PendingOAuthFlow | undefined>;\n  /**\n   * Mutex-protected refresh. Declared here because a consumer typing its field as\n   * `TokenStore` would otherwise lose access to it and fall back to an unguarded\n   * refresh — the exact race acquireRefreshLock exists to prevent.\n   */\n  refreshToken(subject: string, refreshFn: () => Promise<TokenSet>): Promise<TokenSet>;\n}\n\nconst DEFAULT_TOKEN_PREFIX = \"auth:tokens:\";\nconst DEFAULT_FLOW_PREFIX = \"auth:flows:\";\nconst DEFAULT_LOCK_PREFIX = \"auth:lock:\";\nconst DEFAULT_FLOW_TTL_MS = 5 * 60 * 1000;\nconst DEFAULT_LOCK_TTL_MS = 30 * 1000;\nconst TOKEN_TTL_SLACK_MS = 60 * 1000;\nconst REFRESH_LOCK_WAIT_MS = 10_000;\n\nfunction sleep(ms: number): Promise<void> {\n  return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport interface RedisTokenStoreOptions {\n  /** Key prefix for token storage (default: \"auth:tokens:\") */\n  tokenPrefix?: string;\n  /** Key prefix for flow storage (default: \"auth:flows:\") */\n  flowPrefix?: string;\n  /** Key prefix for lock storage (default: \"auth:lock:\") */\n  lockPrefix?: string;\n  /** Default flow TTL in milliseconds (default: 300000 = 5 minutes) */\n  defaultFlowTtlMs?: number;\n  /** Default lock TTL in milliseconds (default: 30000) */\n  defaultLockTtlMs?: number;\n}\n\n/**\n * Redis-backed token store with cross-replica mutex for safe refresh rotation.\n *\n * Uses SET NX PX for distributed locking so concurrent refresh across replicas\n * is serialized — a single refresh-token rotation must not invalidate a second,\n * concurrent refresh.\n */\nexport class RedisTokenStore implements TokenStore {\n  private readonly redis: Redis;\n  private readonly tokenPrefix: string;\n  private readonly flowPrefix: string;\n  private readonly lockPrefix: string;\n  private readonly defaultFlowTtlMs: number;\n  private readonly defaultLockTtlMs: number;\n\n  constructor(redis: Redis, opts?: RedisTokenStoreOptions) {\n    this.redis = redis;\n    this.tokenPrefix = opts?.tokenPrefix ?? DEFAULT_TOKEN_PREFIX;\n    this.flowPrefix = opts?.flowPrefix ?? DEFAULT_FLOW_PREFIX;\n    this.lockPrefix = opts?.lockPrefix ?? DEFAULT_LOCK_PREFIX;\n    this.defaultFlowTtlMs = opts?.defaultFlowTtlMs ?? DEFAULT_FLOW_TTL_MS;\n    this.defaultLockTtlMs = opts?.defaultLockTtlMs ?? DEFAULT_LOCK_TTL_MS;\n  }\n\n  private tokenKey(subject: string): string {\n    return `${this.tokenPrefix}${subject}`;\n  }\n\n  private flowKey(state: string): string {\n    return `${this.flowPrefix}${state}`;\n  }\n\n  private lockKey(subject: string): string {\n    return `${this.lockPrefix}${subject}`;\n  }\n\n  async get(subject: string): Promise<TokenSet | null> {\n    const raw = await this.redis.get(this.tokenKey(subject));\n    if (!raw) return null;\n    try {\n      return JSON.parse(raw) as TokenSet;\n    } catch {\n      return null;\n    }\n  }\n\n  async put(subject: string, tokens: TokenSet): Promise<void> {\n    const ttlMs = Math.max(tokens.expiresAt - Date.now() + TOKEN_TTL_SLACK_MS, TOKEN_TTL_SLACK_MS);\n    await this.redis.set(this.tokenKey(subject), JSON.stringify(tokens), \"PX\", ttlMs);\n  }\n\n  async delete(subject: string): Promise<void> {\n    await this.redis.del(this.tokenKey(subject));\n  }\n\n  async acquireRefreshLock(subject: string, ttlMs?: number): Promise<string | null> {\n    const lockValue = randomBytes(8).toString(\"hex\");\n    const ttl = ttlMs ?? this.defaultLockTtlMs;\n    const result = await this.redis.set(this.lockKey(subject), lockValue, \"PX\", ttl, \"NX\");\n    return result === \"OK\" ? lockValue : null;\n  }\n\n  /**\n   * Release the refresh lock ONLY if this caller still owns it.\n   *\n   * Previously a GET, a comparison, then a DEL — three round trips with a gap. If\n   * the lock expired between the GET and the DEL, and another replica acquired it,\n   * this call deleted the new owner's lock and two replicas refreshed concurrently.\n   * Hydra rotates refresh tokens, so the loser's token is invalidated and that\n   * subject is silently signed out. The compare-and-delete is now one atomic script.\n   */\n  async releaseRefreshLock(subject: string, owner: string): Promise<boolean> {\n    const script =\n      \"if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end\";\n    const released = await this.redis.eval(script, 1, this.lockKey(subject), owner);\n    return released === 1;\n  }\n\n  /**\n   * Refresh tokens with a cross-replica mutex.\n   * The holder stores the rotated token set atomically before releasing the lock.\n   * Waiters poll until the lock clears, then read the stored result.\n   */\n  async refreshToken(subject: string, refreshFn: () => Promise<TokenSet>): Promise<TokenSet> {\n    const lockValue = await this.acquireRefreshLock(subject);\n\n    if (lockValue) {\n      try {\n        const fresh = await refreshFn();\n        await this.put(subject, fresh);\n        return fresh;\n      } finally {\n        await this.releaseRefreshLock(subject, lockValue);\n      }\n    }\n\n    // Another replica holds the lock — poll until it releases\n    const deadline = Date.now() + REFRESH_LOCK_WAIT_MS;\n    while (Date.now() < deadline) {\n      await sleep(50);\n      const locked = await this.redis.exists(this.lockKey(subject));\n      if (!locked) {\n        const stored = await this.get(subject);\n        if (stored) return stored;\n      }\n    }\n\n    throw new Error(\"Timed out waiting for concurrent refresh\");\n  }\n\n  async beginFlow(\n    subject: string,\n    flowTtlMs?: number,\n    codeVerifier?: string,\n  ): Promise<{ state: string; stateHash: string }> {\n    const state = randomBytes(32).toString(\"hex\");\n    const stateHash = createHash(\"sha256\").update(state).digest(\"hex\");\n    const flow: PendingOAuthFlow = {\n      subject,\n      state,\n      createdAt: Date.now(),\n      ...(codeVerifier ? { codeVerifier } : {}),\n    };\n    const ttl = Math.max(flowTtlMs ?? this.defaultFlowTtlMs, 1);\n    await this.redis.set(this.flowKey(state), JSON.stringify(flow), \"PX\", ttl);\n    return { state, stateHash };\n  }\n\n  async resolveFlow(state: string, flowTtlMs?: number): Promise<PendingOAuthFlow | undefined> {\n    const raw = await this.redis.get(this.flowKey(state));\n    await this.redis.del(this.flowKey(state));\n    if (!raw) return undefined;\n\n    let flow: PendingOAuthFlow;\n    try {\n      flow = JSON.parse(raw) as PendingOAuthFlow;\n    } catch {\n      return undefined;\n    }\n\n    const ttl = flowTtlMs ?? this.defaultFlowTtlMs;\n    if (Date.now() - flow.createdAt > ttl) {\n      return undefined;\n    }\n\n    return flow;\n  }\n}\n","/**\n * The environment contract between the platform and an application.\n *\n * THE ONE PLACE these names are spelled. Every key here is written by the\n * platform -- the hub-operator into the tenant's Infisical folder, delivered by\n * an ExternalSecret, or a ConfigMap the tenant chart mounts -- and an application\n * that spells one itself has taken a copy of a platform decision.\n *\n * Why that matters beyond tidiness: when the platform renamed the caller\n * allowlist from a list to a map, every application that had written\n * `process.env.OIDC_ALLOWED_AZP` and split it on spaces was silently wrong, and\n * nothing in its own repository said so. A name read through this module moves\n * when the platform moves it, and a name that disappears is a type error rather\n * than an empty string.\n *\n * Nothing here is a default. A missing value is reported by the reader that needs\n * it, naming the key and what the application loses without it -- never filled in\n * with a fallback, because every fallback this package has carried pointed at\n * production.\n */\n\n/** Keys the platform publishes. Read them through the helpers below. */\nexport const PLATFORM_ENV = {\n  /** The issuer's base URL. */\n  issuerUrl: \"OIDC_ISSUER_URL\",\n  /**\n   * The issuer's JWKS endpoint, published because it cannot be derived.\n   *\n   * Assembling it from the issuer defeats an application on this platform:\n   * `/.well-known/jwks.json` is Hydra's convention, and Zitadel serves\n   * `/oauth/v2/keys` and answers 404 there. The failure arrives after a login\n   * has already succeeded, as \"Expected 200 OK from the JSON Web Key Set HTTP\n   * response\", naming neither the path nor the provider.\n   */\n  jwksUrl: \"OIDC_JWKS_URL\",\n  /** This application's own OAuth client id, which is also its own audience. */\n  clientId: \"OIDC_CLIENT_ID\",\n  /** The organisation that owns this application's identities. */\n  orgId: \"OIDC_ORG_ID\",\n  /** This application's identity project, which is what its audience names. */\n  projectId: \"OIDC_PROJECT_ID\",\n  /**\n   * The callers this application admits, as `<clientId>=<appId>` entries\n   * (ADR-094 invariant 2). Read with `parseAllowedCallers`.\n   */\n  allowedCallers: \"OIDC_ALLOWED_AZP\",\n  /**\n   * The audience scopes this application must request at login so its gateway\n   * can exchange for a token another application will accept (ADR-095).\n   */\n  backendAudienceScopes: \"OIDC_BACKEND_AUDIENCE_SCOPES\",\n  /** The confidential client this application's gateway exchanges as. */\n  exchangeClientId: \"OIDC_EXCHANGE_CLIENT_ID\",\n  exchangeClientSecret: \"OIDC_EXCHANGE_CLIENT_SECRET\",\n  /**\n   * The machine identity this application calls ANOTHER APPLICATION as, with no\n   * user in the request (ADR-097).\n   *\n   * Not a variant of the exchange client above, and the distinction is the whole\n   * point: that one authenticates a token exchange carrying a person, this one\n   * authenticates this application acting as itself. A receiver admits both,\n   * because it matches `azp || client_id` and they fill different claims -- but\n   * nothing may read a person out of a token minted from this pair.\n   *\n   * Present only for an application that declares `backendDependencies`.\n   */\n  serviceClientId: \"OIDC_SERVICE_CLIENT_ID\",\n  serviceClientSecret: \"OIDC_SERVICE_CLIENT_SECRET\",\n} as const;\n\n/**\n * The scopes a login must request to produce a token this platform can use.\n *\n * Raw issuer vocabulary, kept here so an application never writes it. Both of\n * the reserved scopes are load-bearing and neither is guessable:\n *\n *   - without `urn:zitadel:iam:user:resourceowner` the token carries NO tenant\n *     claim, and every receiver refuses it as tenant-less;\n *   - without `urn:zitadel:iam:org:project:roles` it carries no roles at all.\n *\n * Zitadel does not reject an unrecognised scope, it simply does not grant it. So\n * an application that invents its own scope names gets a token that verifies\n * correctly and arrives empty, and the failure shows up as an empty permission\n * set on the first API call rather than as anything wrong with the login.\n */\nexport const PLATFORM_LOGIN_SCOPES: readonly string[] = [\n  \"openid\",\n  \"profile\",\n  \"email\",\n  \"offline_access\",\n  \"urn:zitadel:iam:user:resourceowner\",\n  \"urn:zitadel:iam:org:project:roles\",\n];\n\n/** Raised when the platform has not supplied a value the application needs. */\nexport class PlatformConfigError extends Error {\n  readonly missing: readonly string[];\n  constructor(missing: readonly string[], context: string) {\n    super(\n      `The platform has not supplied ${missing.join(\", \")}, which ${context}.\\n\\n` +\n        `These are delivered by the platform, not set by this application: check the ` +\n        `ExternalSecret and ConfigMap this workload mounts before changing anything here.`,\n    );\n    this.name = \"PlatformConfigError\";\n    this.missing = missing;\n  }\n}\n\n/** A source of configuration. Defaults to the process environment. */\nexport type EnvSource = Record<string, string | undefined>;\n\n/**\n * Read the named keys, or throw naming every one that is missing at once.\n *\n * All of them, not the first: an application started with three values missing\n * should learn that in one restart rather than three.\n */\nexport function requirePlatformEnv<K extends readonly (keyof typeof PLATFORM_ENV)[]>(\n  keys: K,\n  context: string,\n  env: EnvSource = process.env,\n): Record<K[number], string> {\n  const out = {} as Record<K[number], string>;\n  const missing: string[] = [];\n  for (const key of keys) {\n    const name = PLATFORM_ENV[key];\n    const value = env[name]?.trim();\n    if (!value) {\n      missing.push(name);\n      continue;\n    }\n    out[key as K[number]] = value;\n  }\n  if (missing.length > 0) throw new PlatformConfigError(missing, context);\n  return out;\n}\n\n/** Read one optional key. Absent and empty are the same answer. */\nexport function platformEnv(\n  key: keyof typeof PLATFORM_ENV,\n  env: EnvSource = process.env,\n): string | undefined {\n  return env[PLATFORM_ENV[key]]?.trim() || undefined;\n}\n","import { JwtValidator, parseAllowedCallers } from \"../jwt/validator.js\";\nimport { type EnvSource, PLATFORM_ENV, platformEnv, requirePlatformEnv } from \"./env.js\";\n\n/**\n * Validators configured for the surfaces this platform actually has.\n *\n * WHY FACTORIES AND NOT DOCUMENTATION. `JwtValidator` has four security-relevant\n * switches -- `audience`, `allowedAzp`/`allowedCallers`, `rejectIdTokens`,\n * `requireTenantId` -- and the correct setting of each depends on facts about\n * Zitadel and about this platform's gateway that live nowhere near an\n * application's repository. Asking every product team to get four switches right\n * from an ADR means every team re-derives the same reasoning, and one of them\n * gets it wrong quietly: the failure mode of a wrong switch is a token accepted,\n * not an error.\n *\n * It has already happened once. The caller allowlist was rendered with the\n * PUBLIC browser client id, which would have admitted any token from the calling\n * application's own login. Nothing failed, because admitting too much never\n * fails.\n *\n * So the platform names the surfaces and owns the switches. A product team picks\n * the surface it is building and gets a validator that is right for it.\n */\n\nexport interface SurfaceValidatorOptions {\n  /** Configuration source. Defaults to the process environment. */\n  env?: EnvSource;\n  /** JWKS cache tuning, when an application has a reason to differ. */\n  jwksCache?: Partial<import(\"../jwt/jwks-cache.js\").JwksCacheOptions>;\n}\n\n/**\n * For a BFF sitting behind this tenant's gateway, validating the session\n * credential the gateway forwards.\n *\n * REFUSES AN ID TOKEN, like every other surface. There is no browser exception\n * and there is no switch to turn one on.\n *\n * ACCEPTS AN ID TOKEN, because that is what the gateway forwards. The caller\n * allowlist below is what makes that safe.\n *\n * This surface briefly refused them, on the belief that the gateway could mint an\n * access token instead. It cannot on the deployed issuer, and that was found by\n * RUNNING it rather than reading it. Zitadel v4.15.3 validates exchange scopes\n * with\n *\n *     !contains(subjectScopes, scope) || !contains(actorScopes, scope)\n *\n * -- the scope must be on BOTH input tokens -- and an id-token subject carries\n * none. So every requested scope is refused:\n *\n *     {\"error\":\"invalid_scope\",\"error_description\":\"scope\n *      \\\"urn:zitadel:iam:user:resourceowner\\\" not found in subject or actor token\"}\n *\n * and requesting no scopes yields a token with no tenant claim, which a receiver\n * refuses as tenant-less. No RELEASED Zitadel validates it otherwise: the union\n * check that would is in no tag, and there is no published v5 image.\n *\n * `azp` must be this application's own gateway client, so a sibling\n * application's token is refused even though it carries this project's audience\n * by construction -- Zitadel issues any project's audience to any client that\n * asks, so the audience has never been the control.\n *\n * SERVICE-TO-SERVICE IS UNAFFECTED. Client credentials has no subject token, so\n * there is no union check to fail; that path is `consumerApiValidator` and it is\n * not waiting on anything (ADR-097).\n */\nexport function browserSessionValidator(opts: SurfaceValidatorOptions = {}): JwtValidator {\n  const env = opts.env ?? process.env;\n  const cfg = requirePlatformEnv(\n    [\"issuerUrl\", \"jwksUrl\", \"clientId\", \"orgId\"],\n    \"a BFF cannot validate the session its gateway forwards\",\n    env,\n  );\n\n  return new JwtValidator({\n    jwksUrl: cfg.jwksUrl,\n    issuer: cfg.issuerUrl,\n    // This application's own client: the audience the gateway requested at login,\n    // and the `azp` on the id token it forwards.\n    audience: cfg.clientId,\n    allowedAzp: [cfg.clientId],\n    // See the note above. Set by the platform WITH its reason, so it is not a\n    // line an application flips to make an error go away.\n    rejectIdTokens: false,\n    requireTenantId: true,\n    // COMPARED, not merely required. A sibling tenant's user carries a valid\n    // tenant claim -- a different one -- and presence alone accepts it.\n    expectedTenantId: cfg.orgId,\n    jwksCache: opts.jwksCache,\n  });\n}\n\n/**\n * For a surface another APPLICATION calls (waypoint ADR-042).\n *\n * ACCESS TOKENS ONLY. The browser-session exception above is scoped to that hop\n * and must not travel: two meanings for \"authenticated principal\" on one box\n * means a receiver has to know which kind of caller it faces before it knows\n * which rules apply, and that is the confusion ADR-094 invariant 1 exists to\n * remove.\n *\n * Uses the caller MAP, so the receiver can name its caller. A list would admit\n * without naming, and a receiver that partitions records per consuming\n * application would then have to take the name from the request -- exactly what\n * invariant 2b forbids. `claims.consumer_app_id` is set from the map, never from\n * the token.\n *\n * Refuses to build when the platform has published no callers. An empty\n * allowlist on this surface is not \"admit nobody\", it is \"check nothing\", and a\n * cross-application surface with no caller check is open to every application on\n * the box.\n */\nexport function consumerApiValidator(opts: SurfaceValidatorOptions = {}): JwtValidator {\n  const env = opts.env ?? process.env;\n  const cfg = requirePlatformEnv(\n    [\"issuerUrl\", \"jwksUrl\", \"projectId\", \"orgId\"],\n    \"a cross-application surface cannot validate its callers\",\n    env,\n  );\n\n  const raw = platformEnv(\"allowedCallers\", env);\n  const allowedCallers = parseAllowedCallers(raw);\n  if (Object.keys(allowedCallers).length === 0 && raw?.trim()) {\n    // Entries exist and none is typed: values written before kinds (ADR-110).\n    // Refused rather than read as \"no caller check\", and named, so the wait is\n    // not mistaken for a surface nobody calls.\n    throw new Error(\n      `${PLATFORM_ENV.allowedCallers} holds no entry of the form ` +\n        `<clientId>=<appId>:<user|service>, so this surface admits no caller.\\n\\n` +\n        `The platform re-renders each caller's entries with their kind on that ` +\n        `caller's next reconcile (ADR-110).`,\n    );\n  }\n  if (Object.keys(allowedCallers).length === 0) {\n    throw new Error(\n      `${PLATFORM_ENV.allowedCallers} is empty, so this cross-application surface would ` +\n        `admit every application on this box.\\n\\n` +\n        `The platform writes it when another application declares ` +\n        `backendDependencies naming this one. Until one does, this surface has no ` +\n        `callers and should not be mounted.`,\n    );\n  }\n\n  return new JwtValidator({\n    jwksUrl: cfg.jwksUrl,\n    issuer: cfg.issuerUrl,\n    // The PROJECT, not the client: an exchanged token is audienced to the target\n    // application's project, which is what the caller requested a scope for.\n    audience: cfg.projectId,\n    allowedCallers,\n    rejectIdTokens: true,\n    requireTenantId: true,\n    // COMPARED, not merely required. A sibling tenant's user carries a valid\n    // tenant claim -- a different one -- and presence alone accepts it.\n    expectedTenantId: cfg.orgId,\n    jwksCache: opts.jwksCache,\n  });\n}\n","import type { Context, Handler, MiddlewareHandler } from \"hono\";\nimport type { AuthenticatedPrincipal } from \"../authz/types.js\";\nimport type { JwtValidator } from \"../jwt/validator.js\";\nimport { authMiddleware, PRINCIPAL_KEY } from \"../middleware/hono.js\";\nimport type { EnvSource } from \"./env.js\";\nimport { browserSessionValidator } from \"./validators.js\";\n\n/**\n * A BFF's authentication, set up once: the validator and its key lifecycle,\n * readiness, the middleware, and the local-stack stand-in.\n *\n * Every BFF wrote this by hand, and each copy got a different part of it wrong:\n * one never started the validator, so its first request after every restart\n * waited on a key download; another started it but hooked SIGTERM to do so,\n * which stops Node exiting on the signal. Here the rules live in one place:\n *\n *   - ONE validator for the process, started at construction (ADR-022). Its\n *     refresh timers are unref'd, so nothing here holds the process open or\n *     needs a signal handler; pass `signal` only to stop it early.\n *   - READINESS is `readiness` (or `ready()`): 503 until the issuer's keys are\n *     held. Serve it on the path the readiness probe uses -- not the liveness\n *     path, which must never depend on the issuer.\n *   - LOCAL MODE is `<APPID>_ENV=local`, e.g. ORANGER_ENV=local. There is no\n *     platform sign-in on a local stack, so every request under the mount gets\n *     a stand-in principal and no token is checked. It is REFUSED, at\n *     construction, when NODE_ENV is production: a deployed BFF that believes it\n *     is local would admit everyone, so the process does not start.\n */\nexport interface BffAuthOptions {\n  /** This application's id. Selects the local-mode switch, `<APPID>_ENV`. */\n  appId: string;\n  /** The validator to use. Defaults to `browserSessionValidator({ env })`, which is right for a BFF behind its gateway. */\n  validator?: JwtValidator;\n  /** Configuration source. Defaults to the process environment. */\n  env?: EnvSource;\n  /**\n   * Paths under the mount that need no session, as prefixes matched on segment\n   * boundaries: \"/api/v1/auth\" matches /api/v1/auth and /api/v1/auth/callback,\n   * not /api/v1/authors. For routes that run before a session exists (a login\n   * start, an identity probe). In local mode they get the stand-in like any other.\n   */\n  publicPaths?: string[];\n  /**\n   * The local stand-in principal. A fixed principal, or a function of the\n   * request (for a stack that wants to impersonate several users). Defaults to\n   * one fixed user: `local-user`, tenant from LOCAL_TENANT_ID, no roles.\n   * Never used outside local mode.\n   */\n  localPrincipal?: AuthenticatedPrincipal | ((c: Context) => AuthenticatedPrincipal);\n  /** Stops the validator's key refresh when aborted. Optional: nothing needs stopping for the process to exit. */\n  signal?: AbortSignal;\n  /** Where a JWKS failure's detail goes. Passed to authMiddleware. */\n  onDependencyError?: (err: unknown) => void;\n}\n\nexport interface BffAuth {\n  /** True on a local stack: no token is checked, every request is the stand-in. */\n  readonly local: boolean;\n  /** The validator, outside local mode. */\n  readonly validator?: JwtValidator;\n  /** Mount on the API, e.g. `app.use(\"/api/*\", auth.middleware)`. */\n  readonly middleware: MiddlewareHandler;\n  /** The readiness handler: 200 once the keys are held (always, locally), 503 before. */\n  readonly readiness: Handler;\n  /** The readiness fact, for an app that combines it with readiness of its own. */\n  ready(): boolean;\n  /** Stop the key refresh. Idempotent. */\n  stop(): void;\n}\n\nexport function bffAuth(opts: BffAuthOptions): BffAuth {\n  const env = opts.env ?? process.env;\n  if (!/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/.test(opts.appId)) {\n    throw new Error(`bffAuth: appId ${JSON.stringify(opts.appId)} is not an application id`);\n  }\n  const switchName = `${opts.appId.toUpperCase().replace(/-/g, \"_\")}_ENV`;\n  const local = env[switchName] === \"local\";\n  if (local && env.NODE_ENV === \"production\") {\n    throw new Error(\n      `bffAuth: ${switchName}=local with NODE_ENV=production. Local mode admits every request as a ` +\n        `stand-in user, so it is refused in production; unset ${switchName} on a deployed BFF.`,\n    );\n  }\n\n  const publicPaths = (opts.publicPaths ?? []).map((p) => p.replace(/\\/+$/, \"\"));\n  const isPublic = (path: string) =>\n    publicPaths.some((p) => path === p || path.startsWith(`${p}/`));\n\n  if (local) {\n    const fallback: AuthenticatedPrincipal = {\n      subject: \"local-user\",\n      email: `local-user@${opts.appId}.local`,\n      tenantId: env.LOCAL_TENANT_ID ?? \"\",\n      roles: [],\n      issuer: \"local\",\n    };\n    const principalFor = (c: Context): AuthenticatedPrincipal => {\n      const p = opts.localPrincipal ?? fallback;\n      return typeof p === \"function\" ? p(c) : p;\n    };\n    console.warn(\n      `${switchName}=local: every request is a local stand-in user; no session is validated`,\n    );\n    return {\n      local: true,\n      validator: undefined,\n      middleware: async (c, next) => {\n        c.set(PRINCIPAL_KEY as never, principalFor(c) as never);\n        await next();\n      },\n      readiness: (c) => c.json({ status: \"ok\", auth: \"local\" }),\n      ready: () => true,\n      stop: () => {},\n    };\n  }\n\n  const validator = opts.validator ?? browserSessionValidator({ env });\n  validator.start({ signal: opts.signal });\n  const guard = authMiddleware({ validator, onDependencyError: opts.onDependencyError });\n\n  return {\n    local: false,\n    validator,\n    middleware: async (c, next) => (isPublic(c.req.path) ? next() : guard(c, next)),\n    readiness: (c) =>\n      validator.status().ready\n        ? c.json({ status: \"ok\" })\n        : c.json({ status: \"auth-keys-unavailable\" }, 503),\n    ready: () => validator.status().ready,\n    stop: () => validator.stop(),\n  };\n}\n","import { timingSafeEqual } from \"node:crypto\";\nimport type { MiddlewareHandler } from \"hono\";\nimport { type AuthenticatedPrincipal, PRINCIPAL_KEY } from \"../index.js\";\n\n/**\n * The trusted channel between an application's BFF and its own SDK (ADR-057).\n *\n * Both halves of one rule, in one module, for one reason: they are a matched\n * pair of header names, and they were being written out by hand on both sides of\n * a call that crosses a repository boundary. oranger's SDK says so in its own\n * comment -- \"the two are separate services with no shared module, so a rename\n * changes both files in one commit\" -- which is a convention, not a mechanism.\n *\n * In waypoint the caller half is spelled in EIGHT places, each as\n * `process.env.WAYPOINT_INTERNAL_TOKEN ? { ... } : {}`. That ternary is the\n * defect this module removes: with the token absent the call is made with no\n * header at all, so it fails at the far end as a bare 401 naming nothing. A\n * missing credential should stop the caller, not travel.\n *\n * ADR-057 makes this safe only when BOTH hold: the token proves which service is\n * calling, AND a network policy lets nothing else reach the receiver. This module\n * is the first half. The second is the CiliumNetworkPolicy in the receiver's\n * chart, and neither is sufficient alone.\n *\n * SCOPE. This is an intra-application channel. It is not a cross-application\n * mechanism and must not become one: the identity here is ASSERTED by the caller,\n * which is acceptable between two workloads of one application in one namespace\n * and is not acceptable across an application boundary, where identity must come\n * from a validated token (ADR-094 invariant 2b).\n */\n\n/** Header names for one application, derived from its id. */\nexport interface InternalChannelHeaders {\n  readonly token: string;\n  readonly subject: string;\n  readonly email: string;\n  readonly tenant: string;\n  readonly roles: string;\n}\n\n/**\n * Header names for an application, derived rather than written.\n *\n * `x-<appId>-internal-token`, `x-<appId>-user-subject`, and so on — the spelling\n * both applications already use, now produced from the one input that decides it.\n */\nexport function internalChannelHeaders(appId: string): InternalChannelHeaders {\n  const a = appId.toLowerCase();\n  return {\n    token: `x-${a}-internal-token`,\n    subject: `x-${a}-user-subject`,\n    email: `x-${a}-user-email`,\n    tenant: `x-${a}-user-tenant`,\n    roles: `x-${a}-user-roles`,\n  };\n}\n\n/** Raised when a caller tried to make an internal call with no credential. */\nexport class InternalTokenMissingError extends Error {\n  constructor(appId: string) {\n    super(\n      `No internal token for ${appId}, so this call cannot be authenticated.\\n\\n` +\n        `The platform seeds ${appId.toUpperCase().replace(/-/g, \"_\")}_INTERNAL_TOKEN into this ` +\n        `application's Infisical folder and delivers it by ExternalSecret. A workload ` +\n        `without it has not received its secret — check the ExternalSecret, rather than ` +\n        `making the call without the header.`,\n    );\n    this.name = \"InternalTokenMissingError\";\n  }\n}\n\n/**\n * THE CALLER HALF: the headers a BFF sends to its own SDK.\n *\n * Throws when the token is absent. That is the whole point — see the module note\n * above. An application that genuinely wants an unauthenticated internal call\n * does not want this function.\n *\n * The acting user is optional: ADR-057 permits an internal call with no acting\n * user, and such a call simply runs without one. What is not permitted is a call\n * with a user and no token, because then the identity headers are an assertion\n * anything on the network could make.\n */\nexport function internalCallHeaders(\n  appId: string,\n  token: string | undefined,\n  actingUser?: Pick<AuthenticatedPrincipal, \"subject\" | \"email\" | \"tenantId\" | \"roles\">,\n): Record<string, string> {\n  if (!token) throw new InternalTokenMissingError(appId);\n\n  const h = internalChannelHeaders(appId);\n  const out: Record<string, string> = { [h.token]: token };\n  if (!actingUser) return out;\n\n  out[h.subject] = actingUser.subject;\n  if (actingUser.email) out[h.email] = actingUser.email;\n  if (actingUser.tenantId) out[h.tenant] = actingUser.tenantId;\n  // Carried, not dropped. An empty list here is indistinguishable from \"this user\n  // holds no roles\", so discarding them would silently deny every role-gated\n  // operation the receiver ever grows.\n  if (actingUser.roles?.length) out[h.roles] = actingUser.roles.join(\",\");\n  return out;\n}\n\n/**\n * THE RECEIVER HALF: refuse any caller that cannot prove it is this\n * application's own BFF.\n *\n * Constant-time comparison, and length-checked first because `timingSafeEqual`\n * throws on a length mismatch rather than returning false.\n */\nexport function requireInternalCaller(appId: string, token: string): MiddlewareHandler {\n  if (!token) throw new InternalTokenMissingError(appId);\n  const header = internalChannelHeaders(appId).token;\n  const expected = Buffer.from(token);\n\n  return async (c, next) => {\n    const got = Buffer.from(c.req.header(header) ?? \"\");\n    if (got.length !== expected.length || !timingSafeEqual(got, expected)) {\n      return c.json({ error: \"Unauthorized\" }, 401);\n    }\n    await next();\n  };\n}\n\n/**\n * THE RECEIVER HALF: establish the principal the BFF validated, so the platform's\n * own `actingUserMiddleware` resolves it exactly as it would a token this service\n * had validated itself.\n *\n * Mount ONLY after `requireInternalCaller`. Without that, these headers are an\n * assertion any caller can make, and this function would turn it into an\n * authenticated principal.\n */\nexport function forwardedPrincipal(appId: string): MiddlewareHandler {\n  const h = internalChannelHeaders(appId);\n\n  return async (c, next) => {\n    const subject = c.req.header(h.subject);\n    if (subject) {\n      const principal: AuthenticatedPrincipal = {\n        subject,\n        email: c.req.header(h.email) ?? \"\",\n        tenantId: c.req.header(h.tenant) ?? \"\",\n        roles: (c.req.header(h.roles) ?? \"\")\n          .split(\",\")\n          .map((r) => r.trim())\n          .filter(Boolean),\n      };\n      c.set(PRINCIPAL_KEY, principal);\n    }\n    await next();\n  };\n}\n","import { type EnvSource, requirePlatformEnv } from \"./env.js\";\n\n/**\n * A token for calling ANOTHER APPLICATION, with no user in the request (ADR-097).\n *\n * WHY THE PLATFORM OWNS THIS AND NOT EACH APPLICATION\n *\n * The flow is standard OAuth 2.0 client credentials, but the two scopes it must\n * request are raw issuer vocabulary:\n *\n *     urn:zitadel:iam:org:project:id:<targetProjectId>:aud\n *     urn:zitadel:iam:user:resourceowner\n *\n * The first is what puts the target's audience on the token; without it the\n * receiver refuses a token that is otherwise valid. The second is what puts the\n * TENANT on it; without it the receiver refuses it as tenant-less, correctly. An\n * application writing these by hand gets an `invalid_target` or a tenant-less\n * rejection with nothing naming the missing scope, and every team re-derives the\n * same two strings.\n *\n * So the platform names them once, from the target application's id, and a\n * product team asks for \"a token to call waypoint\".\n *\n * WHY THE USER'S IDENTITY IS NOT HERE\n *\n * Because it cannot be, on the deployed issuer. Propagating a user across an\n * application boundary needs an RFC 8693 exchange, and Zitadel v4.15.3 requires\n * every requested scope to be present on BOTH the subject and actor tokens --\n * an id-token subject carries none, so every scope is refused. A token from here\n * carries the SERVICE's identity and nothing may map its subject to a person\n * (ADR-097 invariant 8). When a call genuinely needs the acting user, the honest\n * answer is that the platform cannot carry it yet.\n */\n\n/** What the issuer returns, and the only fields this reads. */\ninterface TokenResponse {\n  access_token?: string;\n  expires_in?: number;\n  token_type?: string;\n  error?: string;\n  error_description?: string;\n}\n\nexport interface ServiceTokenOptions {\n  /**\n   * The application being called, as it is named in `backendDependencies` --\n   * \"waypoint\", not a URL and not a project id. The project id is looked up from\n   * the key the platform publishes for that dependency.\n   */\n  target: string;\n  /** Configuration source. Defaults to the process environment. */\n  env?: EnvSource;\n  /**\n   * Seconds before expiry at which a cached token is replaced. A token that\n   * expires in flight fails the call it was fetched for, so this is not tuning:\n   * it is the margin between \"still valid here\" and \"still valid when it\n   * arrives\".\n   */\n  refreshMarginSeconds?: number;\n  /** Injection point for tests. Defaults to global fetch. */\n  fetchImpl?: typeof fetch;\n}\n\n/** The per-dependency key the platform publishes the target's project id under. */\nexport function backendProjectIdKey(target: string): string {\n  return `OIDC_BACKEND_PROJECT_ID_${target.toUpperCase().replace(/-/g, \"_\")}`;\n}\n\n/** The audience scope that makes a token acceptable to the target. */\nexport function projectAudienceScope(projectId: string): string {\n  return `urn:zitadel:iam:org:project:id:${projectId}:aud`;\n}\n\n/** The scope that puts the tenant on the token. */\nexport const RESOURCE_OWNER_SCOPE = \"urn:zitadel:iam:user:resourceowner\";\n\nexport interface ServiceTokenSource {\n  /** A valid access token for the target, minting or reusing one as needed. */\n  token(): Promise<string>;\n}\n\n/**\n * Build a token source for one target application.\n *\n * REFUSES TO BUILD when the platform has published no service identity. That\n * happens for an application that declares no `backendDependencies`, and the\n * failure it prevents is the worst-shaped one available: a call made with no\n * credential reaches the target, is refused, and reads as an authorization\n * problem at the far end rather than a missing declaration at this one.\n */\nexport function serviceTokenSource(opts: ServiceTokenOptions): ServiceTokenSource {\n  const env = opts.env ?? process.env;\n  const target = opts.target;\n  if (!target) {\n    throw new Error(\"serviceTokenSource: a target application id is required\");\n  }\n\n  const cfg = requirePlatformEnv(\n    [\"issuerUrl\", \"serviceClientId\", \"serviceClientSecret\"],\n    `this application cannot call ${target} as itself`,\n    env,\n  );\n\n  // Read directly: this key's name is DERIVED from the target, so it is not one\n  // of PLATFORM_ENV's fixed entries. The derivation is the contract, and it is\n  // the same one the operator publishes under and the chart mounts from.\n  const projectKey = backendProjectIdKey(target);\n  const targetProjectId: string | undefined = env[projectKey];\n  if (!targetProjectId) {\n    throw new Error(\n      `${projectKey} is not set, so a token for ${target} would carry no audience ` +\n        `and ${target} would refuse it.\\n\\n` +\n        `The platform writes it when this application declares ` +\n        `identity.backendDependencies: [${target}]. Until it does, this ` +\n        `application has no dependency on ${target} and should not call it.`,\n    );\n  }\n\n  // Re-bound after the guard: `mint` is a closure, and TypeScript does not carry\n  // a narrowing across one.\n  const projectId: string = targetProjectId;\n\n  const margin = opts.refreshMarginSeconds ?? 30;\n  const doFetch = opts.fetchImpl ?? fetch;\n  const tokenUrl = `${cfg.issuerUrl.replace(/\\/$/, \"\")}/oauth/v2/token`;\n\n  // Cached across calls: a token endpoint round trip per outbound request would\n  // put the issuer in the path of every cross-application call, which is the\n  // cost this design exists to avoid.\n  let cached: { token: string; expiresAt: number } | null = null;\n  let inFlight: Promise<string> | null = null;\n\n  async function mint(): Promise<string> {\n    const body = new URLSearchParams({\n      grant_type: \"client_credentials\",\n      scope: `${projectAudienceScope(projectId)} ${RESOURCE_OWNER_SCOPE}`,\n    });\n\n    const res = await doFetch(tokenUrl, {\n      method: \"POST\",\n      headers: {\n        \"Content-Type\": \"application/x-www-form-urlencoded\",\n        // Client secret basic: the credential never appears in a body that a\n        // proxy or an access log might keep.\n        Authorization:\n          \"Basic \" +\n          Buffer.from(\n            `${encodeURIComponent(cfg.serviceClientId)}:${encodeURIComponent(cfg.serviceClientSecret)}`,\n          ).toString(\"base64\"),\n      },\n      body,\n    });\n\n    const json = (await res.json().catch(() => ({}))) as TokenResponse;\n    if (!res.ok || !json.access_token) {\n      // The issuer's own words, kept. `invalid_scope` here names the scope it\n      // refused, which is the only thing that distinguishes a missing audience\n      // from a missing tenant claim.\n      const detail = json.error\n        ? `${json.error}${json.error_description ? `: ${json.error_description}` : \"\"}`\n        : `HTTP ${res.status}`;\n      throw new Error(`service token for ${target} refused by the issuer (${detail})`);\n    }\n\n    const ttl = typeof json.expires_in === \"number\" ? json.expires_in : 0;\n    cached = {\n      token: json.access_token,\n      // A response without expires_in is treated as expiring immediately rather\n      // than as never expiring: reusing a token of unknown lifetime is how a\n      // caller starts sending expired credentials and blames the receiver.\n      expiresAt: ttl > 0 ? Date.now() + (ttl - margin) * 1000 : 0,\n    };\n    return json.access_token;\n  }\n\n  return {\n    async token(): Promise<string> {\n      if (cached && Date.now() < cached.expiresAt) {\n        return cached.token;\n      }\n      // One mint at a time. Without this, a burst of concurrent calls on a cold\n      // cache each open their own token request, and the issuer sees a\n      // thundering herd from every replica at once.\n      if (!inFlight) {\n        inFlight = mint().finally(() => {\n          inFlight = null;\n        });\n      }\n      return inFlight;\n    },\n  };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACMO,IAAM,YAAN,cAAwB,MAAM;AAAA,EAC1B;AAAA,EAET,YAAY,MAAwB;AAClC,UAAM,KAAK,SAAS,EAAE,OAAO,KAAK,MAAM,CAAC;AACzC,SAAK,OAAO;AACZ,SAAK,OAAO,KAAK;AAAA,EACnB;AACF;AAEO,IAAM,oBAAN,cAAgC,UAAU;AAAA,EAC/C,YAAY,UAAU,qBAAqB,OAAiB;AAC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