auth
Bearer-token authentication behind one small contract, plus a role check. No vendor SDK: vendor providers (Firebase and
others) live in platform packages and implement AuthProvider.
API
Contract
type Principal<TClaims = Record<string, unknown>> = { claims: TClaims; id: string; roles: string[] };
type AuthRequest<TContext = unknown> = { context: TContext; procedure: unknown };
type AuthProvider<TContext = unknown, TClaims = Record<string, unknown>> = {
verifyToken: (token: string, request: AuthRequest<TContext>) => Promise<Principal<TClaims> | undefined> | Principal<TClaims> | undefined;
};A provider returns undefined when the token is not its kind (the next provider in a chain gets it) and throws when it
handles the token and rejects it. claims is whatever the service needs beyond id and roles, typed by the service.
Exports
| Export | What it does |
|---|---|
authenticateRequest({ authProvider, context, procedure }): Promise<Principal<TClaims>> | Reads authorization: Bearer …, or the whole cookie header when there is no bearer token (a browser), and verifies it. Neither → USER_UNAUTHENTICATED (missing_token); a token nobody claims or a plain provider error → USER_UNAUTHENTICATED (invalid_token, logged); an AppError from a provider passes through unchanged. Call it from a product's own middleware when it needs more than authentication (intent RBAC, say). |
createAuthenticateMiddleware<TContext, TClaims>(authProvider) | oRPC middleware: authenticateRequest, then logger.setUser(principal.id), then principal on context. Never authorizes. |
createRequireIntent<TContext, TIntent, TRole>({ getWorkspaceId?, isIntentAllowed, resolveRole }) | oRPC middleware for intent-based RBAC. Reads the procedure's meta.intent (none → a plain error, never a pass), the workspace id from input.workspaceId (override with getWorkspaceId; missing → INPUT_VALIDATION_ERROR), and asks resolveRole({ context, userId, workspaceId }). No role → 403 not_a_member; isIntentAllowed(intent, role) false → 403 insufficient_role; otherwise membership: { role, workspaceId } is added to context. Roles and intents are plain strings; the caller injects them (the table is ROLE_INTENTS in workspace-model). Declare intent? in the contract's meta type. Handlers should use context.membership.workspaceId, not the input. |
createIamSessionAuthProvider<TContext>({ cacheTtlMs, fetch, getSessionUrl, now? }) | Session auth for every service: forwards the request's session cookie (or bearer token) unchanged to IAM get-session and returns the Principal (id, roles from the admin role, claims email/name/image). A refused session, banned user, 5xx or network error throws USER_UNAUTHENTICATED (invalid_token); it never passes. Caches successes by a SHA-256 of the credential for min(cacheTtlMs, 300 s) (and not past session.expiresAt), at most 1000 entries. Never logs the credential. Put it last in a chain (it claims every credential), and do not combine it with createJwtAuthProvider. Pass a fetch with AbortSignal.timeout to bound a hung IAM. |
requireRole<TContext>(...roles) | oRPC middleware: 401 without a principal, 403 (insufficient_role) unless the principal has one of roles. No roles = authenticated only. |
createAuthProviderChain<TContext, TClaims>(providers) | Tries providers in order; the first principal wins, a throw stops the chain. |
createAccessTokenAuthProvider<TLogger, TId, TOwnerId, TScope, TIntent, TOwner>(config) | Opaque personal access tokens (<prefix>…), see below. Returns AuthProvider<AccessTokenRequestContext<TLogger>, TOwner & AccessTokenClaims<TScope>>. |
createJwtAuthProvider({ secret | jwksUrl, audience?, issuer?, rolesClaim? }) | Verifies a signed JWT with jose. id = sub, roles from rolesClaim (default roles), claims = JwtProfileClaims (email, name, picture when present as strings). |
createDevAuthProvider({ roles? }) | Trusts the token as the id, grants roles (default ["admin"]), claims: {}. The generated default; never for production. |
Types: AuthenticateContext, AuthenticateRequestContext, AuthenticateRequestParams, AuthenticateMiddleware,
RequireRoleContext, RequireRoleMiddleware, RequireIntentContext, RequireIntentDeps, RequireIntentMiddleware, IntentMeta, Membership, IamSessionAuthProviderConfig, IamSessionClaims, IamSessionRequestContext, AccessTokenAuthProviderConfig, AccessTokenClaims, AccessTokenLogger,
AccessTokenRateLimiter, AccessTokenRecord, AccessTokenRequestContext, RateLimitRule, JwtAuthProviderConfig,
JwtProfileClaims, DevAuthProviderConfig.
createJwtAuthProvider and createDevAuthProvider are typed as a one-argument verifyToken that always returns a
principal, so a vendor provider can wrap them; both still fit any AuthProvider slot.
Access tokens
The token is hashed (hashToken) and looked up (findActiveByHash); it is never sent to an identity provider. The order is.
resolveIntent(procedure, logger): the intent the procedure needs, usually from its meta (throw when it has none).- Lookup: unknown, revoked or expired →
USER_UNAUTHENTICATED. - Every
rateLimitRulesentry is checked againstcontext.rateLimiter, keyedaccessToken:<id>:<windowMs>. Over a limit →RATE_LIMIT_EXCEEDEDand aretry-afterheader; a failing limiter store lets the request through (logged). isIntentAllowed(intent, scope)false →USER_UNAUTHORIZED, before the owner is loaded.resolveOwner(ownerId):nullrejects (USER_UNAUTHENTICATED); return{}to accept an owner with nothing to add.touchLastUsed: a failure is logged, the request still succeeds.
The principal is { id: String(ownerId), roles: [], claims: { ...owner, accessTokenId, accessTokenScope } }.
Usage
const authProvider = createAuthProviderChain<RequestContext>([
createAccessTokenAuthProvider({ findActiveByHash, hashToken, isIntentAllowed, prefix: "pat_", rateLimitRules, resolveIntent, resolveOwner, touchLastUsed }),
createJwtAuthProvider({ audience, issuer, jwksUrl }),
]);
const authenticate = createAuthenticateMiddleware<RequestContext>(authProvider);
const protectedImplementer = publicImplementer.use(authenticate).use(requireRole("admin"));The chain's TClaims must fit every provider's claims (here the default Record<string, unknown>); pass a union or a
wider type when providers differ. Roles-to-intents policy and anything product-specific (teams, workspaces, plan limits) stay in the product's own middleware.
Tests
Specs sit next to each source file.
Commands
pnpm nx run auth:typecheck # type-check the package
pnpm nx run auth:test # run the Vitest suite