import { MiddlewareHandler, Context, Handler } from 'hono'; import * as jose from 'jose'; import Redis from 'ioredis'; /** * Hono middleware that checks if the authenticated principal has one of the * required roles. * * Returns 403 if the principal's roles do not include any of the listed roles. * * Usage: * app.delete("/api/:id", requireRole("admin"), deleteHandler); * app.post("/api/config", requireRole("platform_admin", "tenant_admin"), handler); */ declare function requireRole(...requiredRoles: string[]): MiddlewareHandler; interface TenantBoundaryOptions { /** * Function to extract the resource tenant ID from the request. * Default: reads from route param "tenantId" or query param "tenant_id". */ getTenantId?: (c: Context) => string | undefined; } /** * Hono middleware that enforces tenant boundary: * principal.tenantId == resource.tenantId. * * Returns 403 if the authenticated principal's tenant does not match the * resource's tenant. * * Usage: * app.get("/api/v1/spokes/:tenantId", requireTenantBoundary(), handler); */ declare function requireTenantBoundary(opts?: TenantBoundaryOptions): MiddlewareHandler; interface AuthenticatedPrincipal { subject: string; email: string; tenantId: string; tenantTier?: string; roles: string[]; issuer?: string; audience?: string; } interface TokenSet { accessToken: string; refreshToken?: string | null; expiresAt: number; scope?: string; tokenType?: string; } interface AuthorizationDecision { allowed: boolean; reason?: string; } interface Resource { tenantId: string; id?: string; type?: string; } interface Operation { method: string; path: string; resource?: Resource; } interface TenantClaims { /** Subject (user ID) */ sub: string; /** User email */ email: string; /** * Standard OIDC claim. Optional because not every provider or flow emits it, * and an absent claim must not be read as "verified". */ email_verified?: boolean; /** Tenant ID — required for tenant-scoped authorization */ tenant_id: string; /** * Human-readable tenant name, when the provider supplies one. * * Never load-bearing: tenant_id is the identifier and the only thing an * authorization decision may use. This is for display and logs, where an * issuer-allocated identifier is unreadable — they are commonly opaque * numbers, while the tenant has a name a human recognises. */ tenant_name?: string; /** Tenant tier (e.g., "free", "pro", "enterprise") */ tenant_tier?: string; /** User roles */ roles: string[]; /** * `azp` — the client the token was issued to (ADR-094 invariant 2). * * The AUTHORIZED PARTY, not the subject and not the audience. It answers * "which application asked for this token", which is the only claim that can: * `aud` names who may accept it, and Zitadel issues any project's audience to * any client that asks, so `aud` cannot say who is calling. * * Optional because it genuinely is: a `client_credentials` token carries no * `azp`. Absence must therefore be a REFUSAL where a caller identity is * required, never a pass — which is what `allowedAzp` on the validator does. * * Zitadel spells it `azp` on ID tokens and `client_id` on access tokens, and * both are read here so a receiver does not have to know which it holds. */ azp?: string; /** * The APPLICATION the calling client belongs to, resolved from the receiver's * caller map (ADR-094 invariant 2b). * * Not a claim. No token carries it and none may: `azp` names a client, and * only the platform knows which application the platform registered that * client for. A receiver partitioning records per consuming application uses * this and never a field from the request. * * Undefined when the validator was given no caller map. */ consumer_app_id?: string; /** * What the calling client's tokens carry, from the receiver's caller map * (ADR-110): `user` -- the subject is the person the calling application acts * for -- or `service` -- the subject is the calling application's machine * identity, and nothing may read a person out of it (ADR-097 invariant 8). * * Not a claim, for the same reason as `consumer_app_id`: the token cannot say, * because Zitadel spells the client claim the same way for both. Undefined * when the validator was given no caller map. */ caller_kind?: "user" | "service"; /** * Platform-assigned groups (ADR-058). * * The auth-proxy injects this claim, and the API server matches it for * Kubernetes RBAC — but this library dropped it, so no consumer could read * the one claim that identifies a platform-scoped identity. That is why a * platform admin, who legitimately has no tenant, could not be told apart * from a token that was simply missing its tenant. */ groups: string[]; /** JWT issuer */ iss?: string; /** JWT audience */ aud?: string | string[]; /** Expiration time (unix seconds) */ exp?: number; /** Issued at (unix seconds) */ iat?: number; /** Not before (unix seconds) */ nbf?: number; /** JWT ID */ jti?: string; /** Token scope (space-delimited) */ scope?: string; } declare function claimsFromPayload(payload: Record): TenantClaims; /** One failed attempt, reported to `onFetchFailure`. */ interface JwksFetchFailure { url: string; attempt: number; attempts: number; /** What happened: timeout, network error, HTTP status, malformed or unusable key set. */ reason: string; status?: number; /** Whether another attempt follows within this fetch. */ retrying: boolean; } /** What a JwksCache can be configured with. Every field but `jwksUrl` has a default. */ interface JwksCacheOptions { /** JWKS endpoint URL. `https:`; `http:` only for a loopback host or with `allowInsecureHttp`. */ jwksUrl: string; /** * Permit `http:` to a non-loopback host. For a development stack that has no * TLS in front of its issuer; never for a deployed environment, where the key * set is the root of every token's trust and must not be fetched in the clear. */ allowInsecureHttp?: boolean; /** Background refresh period once `start()` has been called, ms (default 300000 = 5 min). */ keyTtlMs?: number; /** * Oldest a key set may be and still be used, ms (default 900000 = 15 min). * Past it, a request refetches before verifying and `status().ready` is false. * Bounds how long a key the issuer has withdrawn can still verify a token. */ maxStaleMs?: number; /** Minimum interval between refetches caused by a token naming an unknown `kid`, ms (default 10000). */ refreshIntervalMs?: number; /** Timeout for ONE fetch attempt, headers and body together, ms (default 10000). */ fetchTimeoutMs?: number; /** Attempts within one fetch, i.e. while a request waits (default 2 -- one retry). */ fetchAttempts?: number; /** Full-jitter backoff base, ms (default 250). */ retryBaseMs?: number; /** Cap on the pause between attempts while a request waits, ms (default 2000). */ retryMaxMs?: number; /** Cap on the background backoff while the issuer is unavailable, ms (default and maximum 300000 -- ADR-022). */ backoffMaxMs?: number; /** Algorithms a key must support to count as usable (default: RS256, ES256). */ algorithms?: string[]; /** * Called on every failed attempt, with the full detail. Where an application * increments `dependency_unavailable_total` (ADR-022). Must not throw; if it * does, the error is ignored. */ onFetchFailure?: (failure: JwksFetchFailure) => void; } /** * Delay before attempt `n + 1`, with full jitter (ADR-022): uniformly random in * [0, min(cap, base * 2^(n-1))], so a fleet failing together does not retry * together. */ declare function fullJitterDelay(n: number, baseMs: number, capMs: number): number; /** * The issuer's signing keys, held in ONE place. * * There is one store -- jose's RemoteJWKSet -- and one way into the network, * installed as its `customFetch`. jose keeps the key set, de-duplicates * concurrent fetches and refetches on an unknown `kid`. The modules under * ./jwks/ decide the rest: * * options.ts configuration, validated * retry-policy.ts what is retried, and the full-jitter delay * fetch.ts one fetch: per-attempt timeout over headers AND body, retries * usable-keys.ts what counts as a key this service can verify with * * and this class owns the lifecycle and the status. * * LIFECYCLE (ADR-022, stable-but-not-ready). A service calls `start()` at boot * and reports `status().ready` as its readiness. `start()` fetches immediately, * retries with capped full-jitter backoff until it succeeds, then refreshes in * the background, so requests verify against keys already held instead of each * cold pod's first requests waiting on a download. It never throws and never * exits the process: an unreachable issuer leaves the pod alive and unready, and * it becomes ready on its own when the issuer returns. */ interface JwksStatus { /** * The service can verify tokens: a key set holding at least one usable * signing key was fetched less than `maxStaleMs` ago. This is the dependency * half of the readiness probe, and the value behind `dependency_status`. */ ready: boolean; /** Usable signing keys in the held set. */ keys: number; lastSuccessAt?: number; consecutiveFailures: number; /** The last failure's reason. Internal detail: for logs, never a response body. */ lastError?: string; /** `start()` is running the background refresh. */ maintaining: boolean; } declare class JwksCache { private readonly opts; private readonly store; private usableKeys; private lastSuccessAt?; private consecutiveFailures; private lastError?; /** No request reaches the issuer before this time: it answered with a long Retry-After. */ private retryAfterUntil; /** The running `start()`, if any. */ private run?; private timer?; constructor(options: JwksCacheOptions); /** The key resolver `jwtVerify` uses. The one store; there is no other. */ getSigningKey(): Promise; /** One fetch, awaited. Resolves when a usable set is held; rejects with JwksFetchError. Prefer `start()`. */ warm(): Promise; /** * Keep the keys fetched until `stop()`, or until `signal` aborts. Idempotent * while running; never throws. * * Until the first success it retries with full-jitter backoff capped at * `backoffMaxMs`, honouring a Retry-After. After it, it refreshes every * `keyTtlMs` with ±10% jitter, so a fleet started together does not refresh * together. Timers are unref'd and do not hold the process open. * * Each run owns an AbortController. Stopping aborts it: the pending timer is * cleared, a retry pause in progress ends, an in-flight fetch is cancelled, and * the loop cannot reschedule itself -- including when `start()` is called again * before the old run's fetch has settled, which then cannot leave two loops. * jose shares one download between everything waiting on it, so a stop also * fails that download for its other waiters; a run started right after a stop * sees one failure and retries it after a jittered pause. */ start(options?: { signal?: AbortSignal; }): void; /** End the background refresh. The held keys stay usable until stale. Idempotent. */ stop(): void; private stopRun; status(): JwksStatus; /** * jose's `customFetch`: the only network path. Records the outcome, and hands * jose either a buffered body or an error -- never a set without a usable key, * so jose never replaces held keys with one. */ private fetch; private recordFailure; private error; private report; } interface JwtValidatorOptions { /** JWKS endpoint URL */ jwksUrl: string; /** Expected issuer — if provided, validation fails when issuer mismatches */ issuer?: string; /** Expected audience — if provided, validation fails when audience mismatches */ audience?: string; /** Allowed signing algorithms (default: ["RS256", "ES256"]) */ algorithms?: string[]; /** JWKS cache options */ jwksCache?: Partial; /** * Require a tenant claim. Default true. * * Set false only for a validator guarding a platform-scoped surface where no * identity is expected to carry a tenant. A tenant-scoped service must leave * this on: without it, a token minted for no tenant is accepted wherever * tenant isolation is the boundary. */ requireTenantId?: boolean; /** * The tenant this receiver belongs to. A token carrying a DIFFERENT tenant is * refused (ADR-094 invariant 3). * * `requireTenantId` asks only that the claim exist, which is not isolation: a * user of another tenant carries a valid tenant claim, just not this one. * Omit this ONLY on a platform-scoped surface that no single tenant owns, and * say so where you omit it. */ expectedTenantId?: string; /** * Refuse a token that carries `at_hash`. Default true. * * A ZITADEL COMPATIBILITY INVARIANT, not a general OIDC rule. OIDC Core * requires `at_hash` only where an access token is returned from the * authorization endpoint (implicit and hybrid); in the authorization-code flow * this platform uses it is OPTIONAL, so a conforming issuer may omit it. What * holds is narrower and version-scoped: * * for the pinned Zitadel, every ID token carries `at_hash` and no JWT * access token does -- `createIDToken` is the only place that sets it, and * it is called with a non-empty access token on every token-endpoint path. * * Re-establish it before trusting a different issuer or a Zitadel upgrade; an * issuer that stops emitting it does not fail this check, it silently passes. * * It is a claim check rather than an audience check because in Zitadel the two * tokens share an audience: `createIDToken` and `createJWT` are both handed * `session.Audience`, so no audience distinguishes them. * * Sound against a hostile caller regardless: `at_hash` is signed, so it cannot * be stripped from a genuine ID token without invalidating the signature. * * ORDERING. A deployment whose gateway still forwards the ID token will have * EVERY request refused by this. The gateway must be forwarding an exchanged * access token first (ADR-095 step 1); adopting the SDK version that carries * this default is step 2, and the two are separate deploys on purpose. * * Set false only to stage that ordering on a box that cannot do both at once. * It is not a setting to leave off: off, the confusion this exists to catch is * a configuration slip away. */ rejectIdTokens?: boolean; /** * The applications permitted to present a token here, by `azp`/`client_id` * (ADR-094 invariant 2). * * THE cross-application control. An audience says a token may be accepted * here; it does not say who asked for it, and Zitadel issues any project's * audience to any client that requests it -- so a receiver checking only * `aud` accepts a token any application on the box could mint for it. This is * the check that distinguishes them. * * Absence of `azp` is a REFUSAL, not a pass. A token with no caller identity * cannot be matched against an allowlist, and treating "cannot tell" as * "allowed" is the failure this exists to prevent. * * Omitted (or empty) means no caller check, which is correct only where a * receiver is unreachable by any other application. Say so where you omit it. */ allowedAzp?: string[]; /** * The callers this receiver admits, what each one is called, and what its * tokens carry: `{ "": { appId, kind } }`. * * A MAP where `allowedAzp` is a list, and the difference is not cosmetic. A * list says a caller may enter; it does not say who entered. A receiver that * owns records per consuming application — waypoint ADR-042 partitions chat * sessions and runs by `consumer_app_id` — would then have to take the name * from the request, which is precisely what ADR-094 invariant 2b forbids. * * Only the platform can supply this. It knows both halves when it renders the * allowlist, and neither end can be trusted to assert it: the caller would be * naming itself, and the receiver has nothing to derive it from. * * The KIND is what the client's tokens carry (ADR-110): `user` for the client * an application's backend obtains its users' tokens with, `service` for the * machine client it calls as itself. The token cannot say which -- `azp` and * `client_id` are one field here -- so only the platform, which provisioned * the client, can. * * Set gate, name and kind together: a token whose `azp` is absent here is * refused exactly as `allowedAzp` refuses, and one that passes arrives with * `consumer_app_id` and `caller_kind` set on its claims. Supply this or * `allowedAzp`, not both; if both are given this one decides, because it is * the stricter statement. * * Build it from the platform's `OIDC_ALLOWED_AZP` with `parseAllowedCallers`. */ allowedCallers?: Record; } /** What a caller-map entry's tokens carry (ADR-110). */ type CallerKind = "user" | "service"; /** One admitted caller: the application its client belongs to, and its kind. */ interface AllowedCaller { appId: string; kind: CallerKind; } /** * Read the platform's `OIDC_ALLOWED_AZP` into a caller map. * * The value is space- or comma-separated `=:` * entries, kind being `user` or `service` (ADR-110). * * AN ENTRY WITHOUT AN APPLICATION AND A KIND ADMITS NOTHING, and is left out. * Those are values written before kinds existed; the platform re-renders each * caller's entries on that caller's next reconcile. Until then its tokens are * refused as CALLER_NOT_ALLOWED, which fails closed -- the alternative, admitting * a client without knowing whether its tokens carry a person, is the defect * kinds exist to remove. */ declare function parseAllowedCallers(value: string | undefined): Record; declare class JwtValidator { private readonly jwksCache; private readonly issuer?; private readonly audience?; private readonly algorithms; private readonly requireTenantId; private readonly rejectIdTokens; private readonly allowedAzp; private readonly allowedCallers?; private readonly expectedTenantId?; constructor(opts: JwtValidatorOptions); /** * Keep the issuer's keys held until stop() or `signal` aborts (ADR-022). Call once * at boot; report `status().ready` from the readiness probe. Never throws: an * unreachable issuer leaves the service alive and unready until it returns. */ start(options?: { signal?: AbortSignal; }): void; stop(): void; /** Whether tokens can be verified now, and why not. See JwksStatus. */ status(): JwksStatus; /** One fetch of the keys, awaited. Rejects with JwksFetchError. Prefer `start()`. */ warm(): Promise; /** * Validate a JWT and return typed tenant claims. * Throws on expired, invalid issuer, invalid audience, or missing required claims. */ validate(token: string): Promise; } /** * Minimal SQL surface the user-resolution helpers need. * * Deliberately not tied to a driver. Tenants use postgres.js, node-postgres and * drizzle in different combinations, and a shared auth package that forces one of * them becomes a dependency conflict rather than an abstraction. Callers adapt * whatever client they already have; the adapter is a few lines and lives with * the code that owns the connection. */ interface SqlExecutor { /** * Execute a parameterised statement and return the rows. * * Parameters are $1, $2, … — every value below is passed this way rather than * interpolated, including the JSON handed to set_config. */ query>(sql: string, params?: readonly unknown[]): Promise; } /** * A client able to run a set of statements inside one transaction. * * Required, not optional, for {@link withUserContext}: the row-level security * settings it applies are transaction-scoped by design, so there is no correct * way to apply them without one. */ interface SqlTransactor { transaction(fn: (tx: SqlExecutor) => Promise): Promise; } /** A tenant-local user, as the tenant's own database understands them. */ interface ResolvedUser { /** * The tenant-local user id — a UUID in the tenant's `users` table. * * This is NOT the OIDC subject. They are different UUIDs for the same person, * and conflating them is the mistake this module exists to prevent: row-level * security, foreign keys and every ownership column key on this value, while * the subject is only meaningful to the identity provider. */ userId: string; email: string; /** True when this call created the user, rather than finding one. */ isNew: boolean; } interface ResolveUserOptions { /** * Identity provider name recorded in `identities.provider`. * * Defaults to "zitadel", the issuer this platform runs. Overriding it is only * correct when a tenant genuinely federates a second provider — the same * subject from two providers must not collapse to one user. * * "ory" is not accepted: it was this default until 0.16.0 and the tenant * baseline now rejects it, because accepting both names for one issuer is what * creates a second user row for a person who already has one. */ provider?: string; /** Schema holding the platform baseline tables. Defaults to "public". */ schema?: string; } declare const ACTING_USER_KEY: "auth:actingUser"; /** The acting user, resolved to this app's own `users` row (ADR-057). */ interface ActingUser { /** * Tenant-local user id -- the uuid every ownership column and row-level * security policy keys on. Distinct from `subject`. */ userId: string; /** The identity provider's subject. Stable, but meaningful only to it. */ subject: string; email: string; tenantId: string; /** True when this request provisioned the user (first sighting). */ isNew: boolean; } interface ActingUserOptions { /** The app's own database, as the RUNTIME role (ADR-093). */ db: SqlTransactor; resolve?: ResolveUserOptions; /** Where resolution failures are reported. Defaults to console.warn. */ onError?: (err: unknown) => void; } /** * Resolve the validated principal to a tenant-local user, once per request. * * Mount AFTER `authMiddleware`: this trusts only the principal that middleware * established from a validated token, never a header. For an app whose * authenticating boundary also holds the database connection -- the common * case, which ADR-057 permits -- the two run in one process and nothing is * forwarded between them. * * A failure does not fail the request. ADR-057: absent identity is permitted, * unattributed writes are not. The handler that needs an owner calls * `requireActingUser()` and fails there, where the requirement is visible. */ declare function actingUserMiddleware(opts: ActingUserOptions): MiddlewareHandler; /** The acting user, or undefined when none was resolved. */ declare function getActingUser(c: Context): ActingUser | undefined; /** * The acting user, or a thrown error. * * For handlers whose work is meaningless without an owner -- anything that * creates, mutates or lists a user's own records. Pair with `withUserContext` * so the row-level security policies see the same user. */ declare function requireActingUser(c: Context): ActingUser; /** * The identity endpoint `zero-ops-auth/client` reads (`GET /api/v1/auth/me`). * * Mount after `authMiddleware` and `actingUserMiddleware`. The response shape is * the client's `UserIdentity`, so every app answers the question the same way: * 401 means signed out, and an authenticated person whose tenant-local user * could not be resolved is `userId: null` -- signed in, ownership unknown -- * rather than an error. */ declare function identityHandler(): Handler; declare const PRINCIPAL_KEY: "auth:principal"; interface AuthMiddlewareOptions { /** JwtValidator instance */ validator: JwtValidator; /** Required scopes — if provided, token must contain all listed scopes */ requiredScopes?: string[]; /** Custom header to extract token from (default: "Authorization") */ headerName?: string; /** * Where a JWKS failure's detail goes (URL, cause, attempts). Defaults to * console.warn. The response carries only the code: that detail describes the * service's own infrastructure and is not the caller's to read. */ onDependencyError?: (err: unknown) => void; } /** * Hono middleware that extracts a Bearer token, validates it via JwtValidator, * and sets the authenticated principal on the context. * * Usage: * app.use("/api/*", authMiddleware({ validator })); * // c.get("principal") → AuthenticatedPrincipal */ declare function authMiddleware(opts: AuthMiddlewareOptions): MiddlewareHandler; /** * Extract the authenticated principal from the Hono context. * Must be called after authMiddleware has run. */ declare function getPrincipal(c: Context): AuthenticatedPrincipal | undefined; interface OidcClientOptions { /** OIDC issuer URL (e.g., "https://auth.dev.nutgraf.in") */ issuerUrl: string; /** OAuth client ID */ clientId: string; /** OAuth client secret (required for confidential clients) */ clientSecret?: string; /** Redirect URI after authorization */ redirectUri: string; /** Scopes to request */ scopes: string[]; /** Expected audience for the access token */ audience?: string; /** HTTP fetch timeout in milliseconds (default: 10000) */ fetchTimeoutMs?: number; } declare class OidcClient { private readonly opts; private discoveryCache; private discoveryPromise; constructor(opts: OidcClientOptions); private discover; private doDiscover; private authHeaders; private exchangeForTokens; /** * Build an authorization URL with optional PKCE support. * Returns the URL, state, and code verifier (if PKCE was used). */ buildAuthorizationUrl(opts?: { state?: string; codeChallenge?: string; codeChallengeMethod?: "S256"; /** * The verifier matching `codeChallenge`. Passed through to the return value so * a caller can hand both to exchangeCode() without threading it separately — * the previous signature promised a codeVerifier it could never produce. */ codeVerifier?: string; additionalParams?: Record; }): Promise<{ url: string; state: string; codeVerifier?: string; }>; /** * Generate PKCE code verifier and challenge. */ static generatePkce(): { codeVerifier: string; codeChallenge: string; }; /** * Exchange an authorization code for tokens. */ exchangeCode(opts: { code: string; codeVerifier?: string; }): Promise; /** * Refresh an access token using a refresh token. */ refreshTokens(refreshToken: string): Promise; /** * Revoke a token (access or refresh). */ revokeToken(token: string): Promise; } /** * Generate a cryptographically random OAuth state parameter. * Returns a 32-byte hex string. */ declare function generateOAuthState(): string; /** * SHA-256 hash of the state parameter. * Used for storing the hash while sending the raw state to the client. */ declare function hashState(state: string): string; interface PendingOAuthFlow { subject: string; state: string; createdAt: number; /** * The PKCE verifier the flow's authorization request was challenged with, * held server-side until the callback redeems the code with it. */ codeVerifier?: string; } interface TokenStore { get(subject: string): Promise; put(subject: string, tokens: TokenSet): Promise; delete(subject: string): Promise; acquireRefreshLock(subject: string, ttlMs?: number): Promise; releaseRefreshLock(subject: string, owner: string): Promise; beginFlow(subject: string, flowTtlMs?: number, codeVerifier?: string): Promise<{ state: string; stateHash: string; }>; resolveFlow(state: string, flowTtlMs?: number): Promise; /** * Mutex-protected refresh. Declared here because a consumer typing its field as * `TokenStore` would otherwise lose access to it and fall back to an unguarded * refresh — the exact race acquireRefreshLock exists to prevent. */ refreshToken(subject: string, refreshFn: () => Promise): Promise; } interface RedisTokenStoreOptions { /** Key prefix for token storage (default: "auth:tokens:") */ tokenPrefix?: string; /** Key prefix for flow storage (default: "auth:flows:") */ flowPrefix?: string; /** Key prefix for lock storage (default: "auth:lock:") */ lockPrefix?: string; /** Default flow TTL in milliseconds (default: 300000 = 5 minutes) */ defaultFlowTtlMs?: number; /** Default lock TTL in milliseconds (default: 30000) */ defaultLockTtlMs?: number; } /** * Redis-backed token store with cross-replica mutex for safe refresh rotation. * * Uses SET NX PX for distributed locking so concurrent refresh across replicas * is serialized — a single refresh-token rotation must not invalidate a second, * concurrent refresh. */ declare class RedisTokenStore implements TokenStore { private readonly redis; private readonly tokenPrefix; private readonly flowPrefix; private readonly lockPrefix; private readonly defaultFlowTtlMs; private readonly defaultLockTtlMs; constructor(redis: Redis, opts?: RedisTokenStoreOptions); private tokenKey; private flowKey; private lockKey; get(subject: string): Promise; put(subject: string, tokens: TokenSet): Promise; delete(subject: string): Promise; acquireRefreshLock(subject: string, ttlMs?: number): Promise; /** * Release the refresh lock ONLY if this caller still owns it. * * Previously a GET, a comparison, then a DEL — three round trips with a gap. If * the lock expired between the GET and the DEL, and another replica acquired it, * this call deleted the new owner's lock and two replicas refreshed concurrently. * Hydra rotates refresh tokens, so the loser's token is invalidated and that * subject is silently signed out. The compare-and-delete is now one atomic script. */ releaseRefreshLock(subject: string, owner: string): Promise; /** * Refresh tokens with a cross-replica mutex. * The holder stores the rotated token set atomically before releasing the lock. * Waiters poll until the lock clears, then read the stored result. */ refreshToken(subject: string, refreshFn: () => Promise): Promise; beginFlow(subject: string, flowTtlMs?: number, codeVerifier?: string): Promise<{ state: string; stateHash: string; }>; resolveFlow(state: string, flowTtlMs?: number): Promise; } /** * The environment contract between the platform and an application. * * THE ONE PLACE these names are spelled. Every key here is written by the * platform -- the hub-operator into the tenant's Infisical folder, delivered by * an ExternalSecret, or a ConfigMap the tenant chart mounts -- and an application * that spells one itself has taken a copy of a platform decision. * * Why that matters beyond tidiness: when the platform renamed the caller * allowlist from a list to a map, every application that had written * `process.env.OIDC_ALLOWED_AZP` and split it on spaces was silently wrong, and * nothing in its own repository said so. A name read through this module moves * when the platform moves it, and a name that disappears is a type error rather * than an empty string. * * Nothing here is a default. A missing value is reported by the reader that needs * it, naming the key and what the application loses without it -- never filled in * with a fallback, because every fallback this package has carried pointed at * production. */ /** Keys the platform publishes. Read them through the helpers below. */ declare const PLATFORM_ENV: { /** The issuer's base URL. */ readonly issuerUrl: "OIDC_ISSUER_URL"; /** * The issuer's JWKS endpoint, published because it cannot be derived. * * Assembling it from the issuer defeats an application on this platform: * `/.well-known/jwks.json` is Hydra's convention, and Zitadel serves * `/oauth/v2/keys` and answers 404 there. The failure arrives after a login * has already succeeded, as "Expected 200 OK from the JSON Web Key Set HTTP * response", naming neither the path nor the provider. */ readonly jwksUrl: "OIDC_JWKS_URL"; /** This application's own OAuth client id, which is also its own audience. */ readonly clientId: "OIDC_CLIENT_ID"; /** The organisation that owns this application's identities. */ readonly orgId: "OIDC_ORG_ID"; /** This application's identity project, which is what its audience names. */ readonly projectId: "OIDC_PROJECT_ID"; /** * The callers this application admits, as `=` entries * (ADR-094 invariant 2). Read with `parseAllowedCallers`. */ readonly allowedCallers: "OIDC_ALLOWED_AZP"; /** * The audience scopes this application must request at login so its gateway * can exchange for a token another application will accept (ADR-095). */ readonly backendAudienceScopes: "OIDC_BACKEND_AUDIENCE_SCOPES"; /** The confidential client this application's gateway exchanges as. */ readonly exchangeClientId: "OIDC_EXCHANGE_CLIENT_ID"; readonly exchangeClientSecret: "OIDC_EXCHANGE_CLIENT_SECRET"; /** * The machine identity this application calls ANOTHER APPLICATION as, with no * user in the request (ADR-097). * * Not a variant of the exchange client above, and the distinction is the whole * point: that one authenticates a token exchange carrying a person, this one * authenticates this application acting as itself. A receiver admits both, * because it matches `azp || client_id` and they fill different claims -- but * nothing may read a person out of a token minted from this pair. * * Present only for an application that declares `backendDependencies`. */ readonly serviceClientId: "OIDC_SERVICE_CLIENT_ID"; readonly serviceClientSecret: "OIDC_SERVICE_CLIENT_SECRET"; }; /** * The scopes a login must request to produce a token this platform can use. * * Raw issuer vocabulary, kept here so an application never writes it. Both of * the reserved scopes are load-bearing and neither is guessable: * * - without `urn:zitadel:iam:user:resourceowner` the token carries NO tenant * claim, and every receiver refuses it as tenant-less; * - without `urn:zitadel:iam:org:project:roles` it carries no roles at all. * * Zitadel does not reject an unrecognised scope, it simply does not grant it. So * an application that invents its own scope names gets a token that verifies * correctly and arrives empty, and the failure shows up as an empty permission * set on the first API call rather than as anything wrong with the login. */ declare const PLATFORM_LOGIN_SCOPES: readonly string[]; /** Raised when the platform has not supplied a value the application needs. */ declare class PlatformConfigError extends Error { readonly missing: readonly string[]; constructor(missing: readonly string[], context: string); } /** A source of configuration. Defaults to the process environment. */ type EnvSource = Record; /** * Read the named keys, or throw naming every one that is missing at once. * * All of them, not the first: an application started with three values missing * should learn that in one restart rather than three. */ declare function requirePlatformEnv(keys: K, context: string, env?: EnvSource): Record; /** Read one optional key. Absent and empty are the same answer. */ declare function platformEnv(key: keyof typeof PLATFORM_ENV, env?: EnvSource): string | undefined; /** * A BFF's authentication, set up once: the validator and its key lifecycle, * readiness, the middleware, and the local-stack stand-in. * * Every BFF wrote this by hand, and each copy got a different part of it wrong: * one never started the validator, so its first request after every restart * waited on a key download; another started it but hooked SIGTERM to do so, * which stops Node exiting on the signal. Here the rules live in one place: * * - ONE validator for the process, started at construction (ADR-022). Its * refresh timers are unref'd, so nothing here holds the process open or * needs a signal handler; pass `signal` only to stop it early. * - READINESS is `readiness` (or `ready()`): 503 until the issuer's keys are * held. Serve it on the path the readiness probe uses -- not the liveness * path, which must never depend on the issuer. * - LOCAL MODE is `_ENV=local`, e.g. ORANGER_ENV=local. There is no * platform sign-in on a local stack, so every request under the mount gets * a stand-in principal and no token is checked. It is REFUSED, at * construction, when NODE_ENV is production: a deployed BFF that believes it * is local would admit everyone, so the process does not start. */ interface BffAuthOptions { /** This application's id. Selects the local-mode switch, `_ENV`. */ appId: string; /** The validator to use. Defaults to `browserSessionValidator({ env })`, which is right for a BFF behind its gateway. */ validator?: JwtValidator; /** Configuration source. Defaults to the process environment. */ env?: EnvSource; /** * Paths under the mount that need no session, as prefixes matched on segment * boundaries: "/api/v1/auth" matches /api/v1/auth and /api/v1/auth/callback, * not /api/v1/authors. For routes that run before a session exists (a login * start, an identity probe). In local mode they get the stand-in like any other. */ publicPaths?: string[]; /** * The local stand-in principal. A fixed principal, or a function of the * request (for a stack that wants to impersonate several users). Defaults to * one fixed user: `local-user`, tenant from LOCAL_TENANT_ID, no roles. * Never used outside local mode. */ localPrincipal?: AuthenticatedPrincipal | ((c: Context) => AuthenticatedPrincipal); /** Stops the validator's key refresh when aborted. Optional: nothing needs stopping for the process to exit. */ signal?: AbortSignal; /** Where a JWKS failure's detail goes. Passed to authMiddleware. */ onDependencyError?: (err: unknown) => void; } interface BffAuth { /** True on a local stack: no token is checked, every request is the stand-in. */ readonly local: boolean; /** The validator, outside local mode. */ readonly validator?: JwtValidator; /** Mount on the API, e.g. `app.use("/api/*", auth.middleware)`. */ readonly middleware: MiddlewareHandler; /** The readiness handler: 200 once the keys are held (always, locally), 503 before. */ readonly readiness: Handler; /** The readiness fact, for an app that combines it with readiness of its own. */ ready(): boolean; /** Stop the key refresh. Idempotent. */ stop(): void; } declare function bffAuth(opts: BffAuthOptions): BffAuth; /** * The trusted channel between an application's BFF and its own SDK (ADR-057). * * Both halves of one rule, in one module, for one reason: they are a matched * pair of header names, and they were being written out by hand on both sides of * a call that crosses a repository boundary. oranger's SDK says so in its own * comment -- "the two are separate services with no shared module, so a rename * changes both files in one commit" -- which is a convention, not a mechanism. * * In waypoint the caller half is spelled in EIGHT places, each as * `process.env.WAYPOINT_INTERNAL_TOKEN ? { ... } : {}`. That ternary is the * defect this module removes: with the token absent the call is made with no * header at all, so it fails at the far end as a bare 401 naming nothing. A * missing credential should stop the caller, not travel. * * ADR-057 makes this safe only when BOTH hold: the token proves which service is * calling, AND a network policy lets nothing else reach the receiver. This module * is the first half. The second is the CiliumNetworkPolicy in the receiver's * chart, and neither is sufficient alone. * * SCOPE. This is an intra-application channel. It is not a cross-application * mechanism and must not become one: the identity here is ASSERTED by the caller, * which is acceptable between two workloads of one application in one namespace * and is not acceptable across an application boundary, where identity must come * from a validated token (ADR-094 invariant 2b). */ /** Header names for one application, derived from its id. */ interface InternalChannelHeaders { readonly token: string; readonly subject: string; readonly email: string; readonly tenant: string; readonly roles: string; } /** * Header names for an application, derived rather than written. * * `x--internal-token`, `x--user-subject`, and so on — the spelling * both applications already use, now produced from the one input that decides it. */ declare function internalChannelHeaders(appId: string): InternalChannelHeaders; /** Raised when a caller tried to make an internal call with no credential. */ declare class InternalTokenMissingError extends Error { constructor(appId: string); } /** * THE CALLER HALF: the headers a BFF sends to its own SDK. * * Throws when the token is absent. That is the whole point — see the module note * above. An application that genuinely wants an unauthenticated internal call * does not want this function. * * The acting user is optional: ADR-057 permits an internal call with no acting * user, and such a call simply runs without one. What is not permitted is a call * with a user and no token, because then the identity headers are an assertion * anything on the network could make. */ declare function internalCallHeaders(appId: string, token: string | undefined, actingUser?: Pick): Record; /** * THE RECEIVER HALF: refuse any caller that cannot prove it is this * application's own BFF. * * Constant-time comparison, and length-checked first because `timingSafeEqual` * throws on a length mismatch rather than returning false. */ declare function requireInternalCaller(appId: string, token: string): MiddlewareHandler; /** * THE RECEIVER HALF: establish the principal the BFF validated, so the platform's * own `actingUserMiddleware` resolves it exactly as it would a token this service * had validated itself. * * Mount ONLY after `requireInternalCaller`. Without that, these headers are an * assertion any caller can make, and this function would turn it into an * authenticated principal. */ declare function forwardedPrincipal(appId: string): MiddlewareHandler; interface ServiceTokenOptions { /** * The application being called, as it is named in `backendDependencies` -- * "waypoint", not a URL and not a project id. The project id is looked up from * the key the platform publishes for that dependency. */ target: string; /** Configuration source. Defaults to the process environment. */ env?: EnvSource; /** * Seconds before expiry at which a cached token is replaced. A token that * expires in flight fails the call it was fetched for, so this is not tuning: * it is the margin between "still valid here" and "still valid when it * arrives". */ refreshMarginSeconds?: number; /** Injection point for tests. Defaults to global fetch. */ fetchImpl?: typeof fetch; } /** The per-dependency key the platform publishes the target's project id under. */ declare function backendProjectIdKey(target: string): string; /** The audience scope that makes a token acceptable to the target. */ declare function projectAudienceScope(projectId: string): string; /** The scope that puts the tenant on the token. */ declare const RESOURCE_OWNER_SCOPE = "urn:zitadel:iam:user:resourceowner"; interface ServiceTokenSource { /** A valid access token for the target, minting or reusing one as needed. */ token(): Promise; } /** * Build a token source for one target application. * * REFUSES TO BUILD when the platform has published no service identity. That * happens for an application that declares no `backendDependencies`, and the * failure it prevents is the worst-shaped one available: a call made with no * credential reaches the target, is refused, and reads as an authorization * problem at the far end rather than a missing declaration at this one. */ declare function serviceTokenSource(opts: ServiceTokenOptions): ServiceTokenSource; /** * Validators configured for the surfaces this platform actually has. * * WHY FACTORIES AND NOT DOCUMENTATION. `JwtValidator` has four security-relevant * switches -- `audience`, `allowedAzp`/`allowedCallers`, `rejectIdTokens`, * `requireTenantId` -- and the correct setting of each depends on facts about * Zitadel and about this platform's gateway that live nowhere near an * application's repository. Asking every product team to get four switches right * from an ADR means every team re-derives the same reasoning, and one of them * gets it wrong quietly: the failure mode of a wrong switch is a token accepted, * not an error. * * It has already happened once. The caller allowlist was rendered with the * PUBLIC browser client id, which would have admitted any token from the calling * application's own login. Nothing failed, because admitting too much never * fails. * * So the platform names the surfaces and owns the switches. A product team picks * the surface it is building and gets a validator that is right for it. */ interface SurfaceValidatorOptions { /** Configuration source. Defaults to the process environment. */ env?: EnvSource; /** JWKS cache tuning, when an application has a reason to differ. */ jwksCache?: Partial; } /** * For a BFF sitting behind this tenant's gateway, validating the session * credential the gateway forwards. * * REFUSES AN ID TOKEN, like every other surface. There is no browser exception * and there is no switch to turn one on. * * ACCEPTS AN ID TOKEN, because that is what the gateway forwards. The caller * allowlist below is what makes that safe. * * This surface briefly refused them, on the belief that the gateway could mint an * access token instead. It cannot on the deployed issuer, and that was found by * RUNNING it rather than reading it. Zitadel v4.15.3 validates exchange scopes * with * * !contains(subjectScopes, scope) || !contains(actorScopes, scope) * * -- the scope must be on BOTH input tokens -- and an id-token subject carries * none. So every requested scope is refused: * * {"error":"invalid_scope","error_description":"scope * \"urn:zitadel:iam:user:resourceowner\" not found in subject or actor token"} * * and requesting no scopes yields a token with no tenant claim, which a receiver * refuses as tenant-less. No RELEASED Zitadel validates it otherwise: the union * check that would is in no tag, and there is no published v5 image. * * `azp` must be this application's own gateway client, so a sibling * application's token is refused even though it carries this project's audience * by construction -- Zitadel issues any project's audience to any client that * asks, so the audience has never been the control. * * SERVICE-TO-SERVICE IS UNAFFECTED. Client credentials has no subject token, so * there is no union check to fail; that path is `consumerApiValidator` and it is * not waiting on anything (ADR-097). */ declare function browserSessionValidator(opts?: SurfaceValidatorOptions): JwtValidator; /** * For a surface another APPLICATION calls (waypoint ADR-042). * * ACCESS TOKENS ONLY. The browser-session exception above is scoped to that hop * and must not travel: two meanings for "authenticated principal" on one box * means a receiver has to know which kind of caller it faces before it knows * which rules apply, and that is the confusion ADR-094 invariant 1 exists to * remove. * * Uses the caller MAP, so the receiver can name its caller. A list would admit * without naming, and a receiver that partitions records per consuming * application would then have to take the name from the request -- exactly what * invariant 2b forbids. `claims.consumer_app_id` is set from the map, never from * the token. * * Refuses to build when the platform has published no callers. An empty * allowlist on this surface is not "admit nobody", it is "check nothing", and a * cross-application surface with no caller check is open to every application on * the box. */ declare function consumerApiValidator(opts?: SurfaceValidatorOptions): JwtValidator; interface AuthErrorOptions { code: string; message: string; cause?: unknown; } declare class AuthError extends Error { readonly code: string; constructor(opts: AuthErrorOptions); } declare class TokenExpiredError extends AuthError { constructor(message?: string, cause?: unknown); } declare class InvalidIssuerError extends AuthError { constructor(expected: string, actual: string); } declare class InvalidAudienceError extends AuthError { constructor(expected: string, actual: string | string[]); } declare class InsufficientScopeError extends AuthError { constructor(required: string[], actual: string[]); } declare class TenantMismatchError extends AuthError { constructor(expected: string, actual: string); } declare class RoleDeniedError extends AuthError { constructor(required: string[]); } declare class TokenMissingError extends AuthError { constructor(message?: string); } /** * The receiver could not obtain the issuer's keys. Nothing is known about the * token, so this is the RECEIVER's failure, not the caller's: middleware answers * it 503, never 401 (a 401 tells a client its credential is bad, and it is not). * * The message names the URL, the cause and the attempts. It is for the service's * own logs; a response body carries only the code. */ declare class JwksFetchError extends AuthError { /** The upstream HTTP status, when there was one. */ readonly status?: number; constructor(url: string, cause?: unknown, detail?: string, status?: number); } declare class KeyNotFoundError extends AuthError { constructor(kid: string); } /** * A token that identifies a login was presented where a credential for this API * was required. * * Separate from TOKEN_INVALID deliberately: the token is well-formed, correctly * signed by the right issuer, and carries the right audience. It is the wrong * KIND of token, and an operator reading TOKEN_INVALID would look for a signing * or clock problem that does not exist (ADR-095). */ declare class IdTokenPresentedError extends AuthError { constructor(); } /** * The token names a calling application that is not on this receiver's * allowlist, or names none at all (ADR-094 invariant 2). * * Its own code because the remedy differs from every other rejection: the token * is valid, the user is real, and what is wrong is WHICH application asked for * it. That is a configuration answer -- add the caller to the allowlist, or stop * it calling -- not a credential one. */ declare class CallerNotAllowedError extends AuthError { constructor(azp: string | undefined, allowed: string[]); } /** * Resolve the tenant-local user for a validated set of OIDC claims, creating one * on first sight. * * WHY THIS IS A PLATFORM CONCERN * * The platform's tenant baseline ships `users` and `identities` in every tenant * database, with row-level security keyed on a tenant-local user id. Nothing * populated them: the identity provider knows a subject, the tenant's tables * expect a local uuid, and the mapping between the two is exactly what * `identities` exists to hold. Left to each tenant, this is the same fifty lines * written repeatedly and wrongly — most often by joining on email, which is the * bug described below. * * THE JOIN KEY IS THE SUBJECT, NEVER THE EMAIL * * Email is mutable in the identity provider and can be reassigned between people. * Joining on it silently merges two accounts the moment an address is changed or * reused, and the failure is a data-disclosure one rather than an error. The * subject is stable for the life of the identity, which is what * `identities.provider_user_id` is for. * * Email is still recorded and refreshed, because a tenant needs to display it — * but it is a property of the user, not a way to find them. * * CONCURRENCY * * Two requests from one person arriving together will both find nothing and both * insert. The unique constraint on (provider, provider_user_id) is what makes * that safe: the loser takes the `ON CONFLICT DO NOTHING` path and re-reads the * winner's row. This runs in one transaction so a failure cannot leave a `users` * row with no linked identity — an orphan that would be found by nothing and * re-created on every subsequent request. */ declare function resolveUser(db: SqlTransactor, claims: TenantClaims, options?: ResolveUserOptions): Promise; /** * Run `fn` in a transaction whose row-level security context is set to this user. * * FOR AN APPLICATION THAT CHOOSES ROW-LEVEL SECURITY. The platform ships no * policies -- it provisions a database and a role, and the schema is the * application's -- so nothing here is engaged unless the application wrote a * policy that reads * `current_setting('request.jwt.claims')::json->>'user_id'`. * * Worth knowing before adopting it: such a policy binds the application only * while the application sets the claim honestly. It catches a handler that forgot * a WHERE clause; it does not constrain code that sets a different user_id, * because the application holds the connection. That makes it a backstop against * developer error, not a security boundary -- which is a fine thing to want, as * long as it is not mistaken for the other. * * TRANSACTION-SCOPED, AND THAT IS NOT A DETAIL * * set_config's third argument is `is_local`, and it is `true` here. Tenants reach * PostgreSQL through PgBouncer in transaction pooling mode, where a server * connection is handed to a different client the moment a transaction ends. A * session-scoped setting would therefore outlive the request that set it and be * inherited by the next tenant user to borrow that connection — every RLS policy * would then evaluate against someone else's identity. Local scoping is what * makes pooling safe here. * * The claims are passed as a bound parameter rather than interpolated: SET does * not accept parameters, which is exactly why set_config exists, and building the * statement by string concatenation would put user-controlled text into SQL. */ declare function withUserContext(db: SqlTransactor, context: { userId: string; tenantId?: string; }, fn: (tx: SqlExecutor) => Promise): Promise; export { ACTING_USER_KEY, type ActingUser, type ActingUserOptions, type AllowedCaller, AuthError, type AuthMiddlewareOptions, type AuthenticatedPrincipal, type AuthorizationDecision, type BffAuth, type BffAuthOptions, type CallerKind, CallerNotAllowedError, type EnvSource, IdTokenPresentedError, InsufficientScopeError, type InternalChannelHeaders, InternalTokenMissingError, InvalidAudienceError, InvalidIssuerError, JwksCache, type JwksCacheOptions, JwksFetchError, type JwksFetchFailure, type JwksStatus, JwtValidator, type JwtValidatorOptions, KeyNotFoundError, OidcClient, type OidcClientOptions, type Operation, PLATFORM_ENV, PLATFORM_LOGIN_SCOPES, PRINCIPAL_KEY, type PendingOAuthFlow, PlatformConfigError, RESOURCE_OWNER_SCOPE, RedisTokenStore, type RedisTokenStoreOptions, type ResolveUserOptions, type ResolvedUser, type Resource, RoleDeniedError, type ServiceTokenOptions, type ServiceTokenSource, type SqlExecutor, type SqlTransactor, type SurfaceValidatorOptions, type TenantBoundaryOptions, type TenantClaims, TenantMismatchError, TokenExpiredError, TokenMissingError, type TokenSet, type TokenStore, actingUserMiddleware, authMiddleware, backendProjectIdKey, bffAuth, browserSessionValidator, claimsFromPayload, consumerApiValidator, forwardedPrincipal, fullJitterDelay, generateOAuthState, getActingUser, getPrincipal, hashState, identityHandler, internalCallHeaders, internalChannelHeaders, parseAllowedCallers, platformEnv, projectAudienceScope, requireActingUser, requireInternalCaller, requirePlatformEnv, requireRole, requireTenantBoundary, resolveUser, serviceTokenSource, withUserContext };