@substrat-run/vertical-auth
Pluggable authentication for a vertical — one interface the application codes against, and three interchangeable implementations behind it. It is the concrete form of the identity seam for verticals, the counterpart to @substrat-run/oidc-rp, which serves the platform's own surfaces.
A vertical scaffolded with create-substrat gets sign-in from workerDoor (@substrat-run/vertical-host/worker-door), which is built on this package: it calls instanceAuthFor, mounts the login, session and owner-claim routes, and leaves the vertical without any session handling or owner-claim logic of its own.
The AuthProvider contract
import type { AuthProvider, AuthSubject, ResolveOptions } from '@substrat-run/vertical-auth';
interface AuthProvider {
handle(request: Request): Promise<Response>; // /api/auth/* — login, logout, callbacks
resolve(headers: Headers, url?: string, options?: ResolveOptions): Promise<AuthSubject | null>; // request → verified subject
}
interface AuthSubject {
sub: string; // the provider's stable subject id
email: string | null;
name: string | null;
emailVerified?: boolean; // what the provider says about `email` — three states, not two
delegation?: { actor: string; scope: string[] }; // another app acting for this user, within `scope`
}delegation is set only on a delegated bearer: another app of the team calling this app's MCP endpoint for the user, with a token the team auth server minted by token exchange. It is admitted only when the vertical opts in with instanceAuthFor({ …, delegation: { actors } }), and only through the MCP endpoint's channel: resolve(headers, url, { delegated: mcpChannelOf(c) }), with mcpChannelOf from @substrat-run/vertical-host. actors is the acting apps' client ids: a list, or a function of the install's delivered wiring ({ identity, config }) that returns one, since a client id is per team auth server. A resolver that throws or returns nothing usable admits no delegated token. maxLifetimeSeconds can lower the lifetime bound (five minutes). Without the option, any bearer carrying act is refused. A delivered audience that is not the MCP endpoint's resource refuses every delegated token too. The verifier warns, once per isolate for each issuer and audience, when the endpoint's channel names a resource other than it. See calls made for a user by another app.
The provider proves who a caller is and nothing more. Authorization stays in the kernel — roles, grants and tenancy are never this package's concern. Mapping sub to a Substrat PrincipalId is a separate, per-scope step (the identity directory below), which is what lets the implementation swap without touching the app.
emailVerified is three-state. true and false are the provider asserting something about the address; undefined is the provider saying nothing — what an OIDC issuer that never emits email_verified looks like, and what a session minted before the field existed looks like for the rest of its life. Both OIDC providers carry the issuer's email_verified claim through unchanged. Nothing in this package gates on it: a vertical's invites are claimed by token, not by address. A vertical that does key something on an address should ask identifyEmail from @substrat-run/oidc-rp, the rule the platform's own apps use: only true passes, and undefined is refused like false (#1359).
instanceAuthFor — what a vertical actually mounts
A vertical does not pick a provider at build time. One serving script runs every install, and each install may have been given a different issuer in the dashboard, so the provider is a function of this scope's delivered configuration. instanceAuthFor is that whole step — read the delivered config, parse substrat:auth, resolve the declared settings, and hand back the selector for a provider — in one DO hop. Nothing is selected during the hop: provider() is a closure, and the selection (and any AuthConfigError) happens when it is called.
import { instanceAuthFor, AuthConfigError } from '@substrat-run/vertical-auth';
const instance = await instanceAuthFor({
directory: identityDo(env, node), // the tenant's IdentityDO stub
scopeId: node.scopeId,
envSpec: TICKET0_ENV, // the vertical's declared env spec
env, // the worker's own bindings
});
// { identity, sessionSecret, settings, config, provider() }| Field | What it is |
|---|---|
identity | the parsed substrat:auth choice, or null when nothing usable was delivered |
sessionSecret | the tenant's DO-minted session-signing secret |
settings | the declared env spec, resolved delivered > binding > manifest default |
config | the whole delivered map, for a vertical's own non-declared keys |
provider() | the AuthProvider this instance's configuration selects |
Three things it owns, each of which a caller assembling this by hand gets wrong:
provideris a function, not a field. A route that only readssettingsmust not fail because nobody has configured a login yet, so selection — and its throw — happens when the provider is asked for, not when the config is read.- Settings resolve delivered > binding > default. A spec
defaultrides as a binding shared by every install of one serving script, so readingenv.OIDC_ISSUERdirectly hands every tenant the same string no matter what any of them saved in the dashboard. That was a real bug in one of the four hand-written copies this replaces. AuthConfigErrorcarries its HTTP status with the throw. An instance nobody has configured yet is a503;AUTH_PROVIDER=oidcwith noOIDC_ISSUERis a500, because a deployment that asked for a provider and did not finish configuring it is an operator's mistake, not a tenant's missing choice. A plainErrorwould have arrived as a 500 by accident. Each worker re-raises it in its own framework's exception:
try {
return instance.provider();
} catch (err) {
if (err instanceof AuthConfigError) throw new HTTPException(err.status, { message: err.message });
throw err;
}meridian, manyfold and ticket0 all mount it, and so does the create-substrat template — through workerDoor rather than by calling it: the door takes the AUTH directory binding, reads the instance's configuration with instanceAuthFor, and mounts /api/auth/*, /api/me and /api/claim-owner. A worker that wants something other than the door's composition calls instanceAuthFor itself, as above. Member invites are not in the door: mount mountInviteRoutes from @substrat-run/vertical-auth with your own admin gate.
What it selects between
The composition is OIDC-only; provider() selects one of these two providers.
| Export | Login happens | Selected when |
|---|---|---|
oidcRpAuthProvider | server-side, in your worker | a substrat:auth choice was delivered with mode: 'oidc' and both an issuer and a clientId — the hosted path, one script and many issuers |
oidcAuthProvider | at the issuer; the app verifies a presented JWT | nothing usable was delivered and AUTH_PROVIDER=oidc names a fixed OIDC_ISSUER — standalone deploys, or an SPA already holding a token from Supabase, Auth0, AuthHero, Keycloak, Zitadel |
oidcAuthProvider is discovery-driven: the issuer URL is the only wired-in value, and the ID token is signature-verified against the issuer's JWKS. oidcRpAuthProvider runs Authorization-Code + PKCE through @substrat-run/oidc-rp, so verticals and the platform share one verifier rather than two copies of the security-critical path. With neither — no usable delivered OIDC choice, and no AUTH_PROVIDER=oidc with an OIDC_ISSUER — the composition fails closed: provider() throws AuthConfigError with a 503. A delivered choice missing its issuer or clientId is the same 503.
Signing out, and the issuer's own session
GET /api/auth/logout clears this app's session cookie and sends the browser to a same-origin returnTo. That is not the whole sign-out: the issuer holds a session on its own domain, so the next "Sign in" is a silent re-authentication as the same person, and "use another account" never works.
GET /api/auth/logout?federated ends that one too, through OIDC RP-Initiated Logout — the issuer's end_session_endpoint, with the ID token from this login as id_token_hint. The hint is what makes it a straight redirect: without it the issuer cannot tell a real sign-out from a link somebody was tricked into following, so it may interrupt with a Confirm logout page. The platform's auth server does not for this request, a browser GET naming the client; another issuer can. The provider keeps that token in its own cookie, scoped to the logout path and SameSite=Strict, and hands it back exactly once.
Two conditions live at the issuer, not here — at an Auth Server app they are the two fields on the application: RP-initiated logout must be enabled for the client, and the exact post_logout_redirect_uri the provider sends must be on the post-logout list, which is separate from the sign-in callbacks. There are two, both the app's origin plus a fixed path: / when the logout link carried no returnTo, and /api/auth/logged-out when it did — register both. The returnTo itself (an invite link's /invite/<token>, say) never reaches the issuer: the provider parks it in a short-lived HttpOnly, SameSite=Laxsb_oidc_return cookie, and /api/auth/logged-out reads it once, clears it and redirects there (same-origin paths only; anything else lands on /). An origin alone does not match, and the mismatch is quiet: the person is signed out and left at the issuer instead of coming back. At an issuer that asks for confirmation, the first sign-out after turning them on can still show its page: the ID token minted before then carries no session id for the issuer to match, and the next sign-in puts one there.
Local sign-out happens first, always. An issuer that is down, advertises no end-session endpoint, or refuses the redirect URI can only leave its own session standing — never keep somebody signed in here.
The identity directory
IdentityDO is one Durable Object per tenant, running its own SQLite. It stores ownership, invites, sites, scope configuration, and the OIDC session-signing secret. Credentials belong to the configured OIDC issuer. It is one of the vertical's own DO classes, so it stays sandbox-clean: the platform refuses cross-script bindings, not a vertical's own.
Its sub → principal mapping is provider-agnostic and used under both OIDC providers:
setPendingOwner— records the owner seat at provision. The seat is minted empty (the platform knows the principal it minted, not the login the tenant's issuer will emit) and bound later by a verified subject. For 15 minutes after provision the first authenticated subject claims it — the install flow, where the installer opens the app seconds later. After that a plain sign-in binds nobody, so an instance nobody opened is not a seat anyone can take indefinitely. A re-provision keeps the window it has and never re-opens a claimed seat. Pass the provision body'sparentScopeIdas the third argument. It is set when a running scope asked for this one (provision-sibling), and then the seat is bound at once to the login the parent scope binds to the owner, with no window. If the parent binds nobody to the owner, the seat waits for a claim link.resolvePrincipal— the per-request lookup that turns a verifiedsubinto thePrincipalIdthe kernel checks permissions against (and performs the first-sign-in claim while the window is open).ownerSeat/recordOwnerClaim/claimOwnerByCapability— the claim link. Once the window has closed (or instead of relying on it), the platform asks for a short-lived/?claim=<secret>link under its secret — the dashboard's Owner seat card. The link is abecomecapability in the scope's own storage: it expires after 15 minutes, works once, can be revoked, and its use is recorded on the scope's event log. The directory records which capability is the current link, so minting again retires the earlier one.mintOwnerClaimLinkmints the capability, records it and revokes the previous one in one call, so the vertical'smintOwnerClaimhook is a one-liner.mountOwnerClaim, from@substrat-run/vertical-auth/owner-claim-routes, is the redemption route (POST /api/claim-owner): it checks the secret is the current link, exchanges it, and binds the signed-in subject, with one refusal for every failure. A closed window is not a lost instance: the seat stays pending —needsSetupkeeps saying so, andownerSeatsays why — until a claim binds it.mountSession, from@substrat-run/vertical-auth/session-route, isGET /api/me, the read every screen makes first. The vertical supplies how a request resolves to a principal and any fields of its own. The route answers{ principal, display, email }with those fields beside it,{ status: 'needs-setup', firstSignInOpen }while the owner seat is unclaimed, or 401, and reports the login's place to the identity pool.displayis the issuer's name, else the email, else "You". A seat reserved for an address addsownerAddressReserved: trueto theneeds-setupanswer: no first-sign-in window is open, but a sign-in whose issuer verified that address claims the seat, so the app should offer one. The address is never in the answer.resolveSignedIn(directory, scopeId, subject)— the principal a signed-in subject is in a scope, for a worker that resolves its own callers:resolvePrincipal, then the claim of a seat reserved for the address the subject's issuer verified.transferOwner(scopeId, from, to)— the owner hand-over. Moves the owner of record, whichsetPendingOwnernever does after its first write, and which a reconcile re-seats when a scope is locked out. It refuses, changing nothing, when the seat is still unclaimed,fromis not the current record, or no subject in the scope is bound toto. It never re-opens a claimed seat. A record already namingtocounts as a retry only for the samefrom:alreadywhile the hand-over is open,doneoncecompleteOwnerTransferhas closed it. While one is open, any other hand-over on the scope is refused asin-flight, and iftohas since been removed, the open one's own resend is refused aswedgedrather than finished.abandonOwnerTransfercloses it without seating or revoking anyone, and only then: an open hand-over whosetocan still take it answershealthy, since resending it finishes it. After an abandon the originalfromkeeps any owner seat it still holds, until the next owner removes it in the app. Wire both as vertical-host's hooks of the same names, which seat and revoke between them.createInvite/listInvites/getInvite/revokeInvite/inviteMatches/inviteLink/claimInviteByCapability/openInviteFor/admitInvite— member invites, the post-setup join path. An invite pre-mints a member principal, grants it a role at scope level, and mints its link: abecomecapability in the scope's own storage, minted by the member who invites. It works once, expires 14 days after it is minted (MEMBER_INVITE_TTL_MS;mintMemberInvite'sexpiresAt: nullkeeps one open until withdrawn), can be revoked, and its mint and its use are on the scope's event log (capability.become-minted,capability.exercised). The inviter may mint it only while they hold everything the invited principal holds at the scope, entity-narrowed grants included, and never for a principal holding nothing there (an invite at a role that confers no permission at all is refused409). The directory records the secret's hash and which capability the invite is; accepting checks the secret is an open invite, exchanges it in the scope, and binds the invitee's verifiedsubto that principal. The inviter is not re-checked at accept, but the link is: if what the invited principal holds (its role keys, direct and narrowed grants) has changed since the link was minted, the link is revoked and refused. A role's definition is not part of that, since it is the vertical's code. An invite naming an address is for that address: accepting it is refused, before the scope is asked, for a session whose issuer did not verify that address, so a forwarded link opens nothing and its use stays for the person named. Addresses are compared Unicode-normalised (NFC), with ASCII letters lowercased; other letters are compared as written, since a full lowercase merges characters no normalisation equates. A refused accept says the invite may be for another address, without saying which step refused; someone already in (a worker door admitted them by address first) is answered with their principal instead. An address has one open invite per scope:createInviterefuses a second until the first is accepted or withdrawn, and the routes answer that409. An invite naming no address is a bearer link, for an issuer that verifies no address.admitByAddressneeds no link at all: given a signed-in subject bound to nobody in the scope, it finds the open invite naming their verified address (openInviteFor), has the scope exchange that invite's link by id (exchangeBecomeLinkById, for a link labelledMEMBER_INVITE_LABELonly, with every judgement the secret's exchange makes), and binds them (admitInvite, which never re-binds a subject a racing admission bound first). The worker door runs it on every request from such a subject.mountMemberInvites(app, deps), from the same subpath, is the pair of routes a door mounts to make and withdraw such invites (POST /api/member-invitesandPOST /api/member-invites/:principal/withdraw): the worker door when it is giveninvites, and a dev server through@substrat-run/dev-issuer'sdevMemberInvites. An invite runs the vertical'ssendas the inviter before it records the row anything admits by, so an invite the vertical refuses never admits anyone; a withdrawal asks the platform's bound and runs the vertical'scancelbefore it takes the platform's half.GET /api/invitesshows each invite'slink(open,used,expired, orrevokedwith its reason), so a dead link never reads as open. Withdrawing the invite revokes the link first, then removes the row. An invite minted before this (a hash-only row) can no longer be created:createInviterequires the capability id and refuses a missing one (#2496), andcreateLegacyInvitein@substrat-run/vertical-auth/member-directoryis the one explicit way to write such a row, for a test that covers the ones still pending. Rows already stored are still accepted by their hash throughclaimInviteuntil the first vertical-auth release published on or after 2027-01-09, which stops admitting them; before it, the platform withdraws any still pending, and an invite withdrawn that way has to be sent again. They are measured (#2175):legacyInviteCount(scopeId)counts a scope's unclaimed hash-only invites, and the routes write alegacy-invites-pendingwarn line (a scope id and a count, nothing identifying) — from the list only while that count is above zero, at most hourly per isolate, and from every accept that claims an invite through the legacy branch. No such line for a settled period means the branch has nothing left to serve only once count support is confirmed (a directory withoutlegacyInviteCount, or a count that could not be read, emits no measurement) and the list reads succeeded for every relevant scope. The four HTTP routes over these —GET/POST /api/invites,POST /api/invites/:principal/revoke,POST /api/accept-invite— are written once asmountInviteRoutes(app, deps)from@substrat-run/vertical-auth/invite-routes— a subpath, because it is the one module here that importshonoat runtime, and the root import must stay free of it for a consumer that wants only anAuthProvider. A vertical supplies only what is its own: how a request resolves to a scope, what "admin" means (itsrequireAdminreturns the{ principal }it admitted), which roles a teammate may be invited at, its directory, the host'sassignScopeRoleBounded,revokeScopeRole,revokeScopeRolesBounded,mintBecomeCapabilityBounded,revokeBecomeCapability,exchangeCapabilityandbecomeLinkStates, and its auth provider. The admin gate runs before the body is read; after it, creating an invite and revoking one both apply the assignment bound and refuse403naming what is missing, with nothing granted, recorded or removed. Creating is bounded by the role it confers. Revoking is bounded by the roles the invite's principal holds now, asked in the scope task that takes them back, and never by the role the row recorded when it was minted, which a later role move can leave stale. The grant goes with the row, and so does the link, revoked in the scope. A mount without the bounded revoke, the capability verbs, or a gate that names no caller refuses both routes rather than running them unbounded. Every error the mount raises itself is anHTTPException— a body that is not JSON or does not fit the route's schema is a 400 naming the problem, never a bareSyntaxErrororZodError— so the vertical's ownonErrorrenders them with no branch for this mount; what its own deps throw passes through untouched. The grant and the invite row live in two Durable Objects, so when the row cannot be written after the role was granted the mount revokes the link and the grant before reporting the failure, which is whatrevokeScopeRoleis for.mountUnbindRoute(app, deps), from the same subpath, is the lever beside a binding invite (#1686). That is a member invite whose link also carriesbind: { entity }: whoever claims it is bound to their own record. In the exchange's one transaction, the record's declared principal column is set to them and they get the record's declared shape. That shape is anENTITY_GRANTSentry with a table holder andbind: { permission }, and the rights come from it, not from the link. The minter must hold the bind key on the record, both at mint and again at the claim, so a link whose minter has lost the key, or left, is refused with the one refusal and stays unspent. A record that already names someone refuses the link, and so does one someone already holds the shape on with its column empty (a person given it before the column was written: unbind them first). Nothing is ever re-bound.POST /api/bindings/:entityType/:entityId/unbindcalls the host'sunbindEntityHolderBounded. It clears the column and releases everyone holding the shape on the record, found by their marker rather than by the column, answering{ unbound: [<principal>, …], revokedLinks: [<capability>, …] }. In the same transaction it revokes every binding link still pending on the record, since a link must not outlive the binding it was made for. Or it answers 403 naming the bind key the caller lacks on that record, or 404 for a type the scope does not bind. People already bound keep the shape until an unbind, an erasure or a retirement of its keys releases them, whatever a later version declares. So a version that removes the shape, moves its holder, makes it a sharing shape or drops a key from it without retiring that key is refused wherever it would run where the shape binds (a promote, a bind, a route onto the serving script), a rollback to a version from before the shape included, until it retires every key (#2178): keep the shape with the keys inretiredand none inpermissions, then drop or move it in a later version, once the retirement has finished in every install (#2185: each primary install is judged from the version it last reconciled and whether that reconcile finished the version's retirements. One that left a retirement open, one built on anadapter-cloudflareorvertical-hostthat predates the report, and one with no receipt, such as just after a kill switch or a restore, all wait; the sweep reconciles them again on its next pass. A copy never reconciles, so a retirement never reaches it, and its own bind is judged only on what it runs). Dropping onlybindis allowed: it stops new links, and the people already bound keep the shape. They stay guarded after it (#2184): each install's reconcile reports the binding shapes links have ever bound in it, and a later version that removes such a shape, moves its holder, or drops one of its keys unretired is refused the same way while any install bound it, or has not reported yet (an install built on anadapter-cloudflareorvertical-hostthat predates the report counts every table-held bootstrap shape of its version as bound, until the vertical pushes on current releases of both). A vertical suppliesnodeFor,callerOf(who is asking, 401 for nobody) and the host verb. There is no admin gate, because the kernel's bound is the key on the record. An erasure of the record, or of its person, unbinds too.mountBindLinkRoutes(app, deps), from the same subpath, binds someone who is already a member to a record (#2817, K-60). A binding invite cannot name them: its principal is minted for the invite, and a member's own seat is never offered as a link again. A bind link names one member and one record, and binds that member when their own session presents it. No principal changes hands.POST /api/bindings/:entityType/:entityId/linkswith{ principal, expiresAt?, label? }calls the host'smintBindLinkBoundedand answers201 { id, token, expiresAt }. Its refusals:- 403 naming the bind key the caller lacks on the record;
- 404 for a type the scope does not bind, or a record that is not there;
- 409 for a record already bound or held;
- 400 for a principal who is no member here. A member is a principal holding at least one permission at the scope's node, through a role or a grant at the scope or tenant level; entity-narrowed grants alone do not make one.
POST /api/bindings/acceptwith{ token }exchanges the link for the caller, who is its presenter (exchangeCapabilitywith{ mode: 'bind', presenter }), and answers{ principal, bound }. It answers 400 for every refusal: a link addressed to someone else, used, revoked or expired, a presenter who is no longer a member, a record bound meanwhile, a minter who has lost the key, or the vertical's own UNIQUE index on its binding column refusing a second record for that person. That last one rolls back with the use untaken. An owner binding themselves mints to their own principal and accepts. A link is single use. The unbind route on its record withdraws a pending one, and the erasure of the member it names revokes it (a used or expired link is left as it reads). The kernel does not limit how many records of one type a member holds. A vertical that wants one per person refuses the mint itself and can add a UNIQUE index on the binding column, which this route answers as a refusal. A vertical suppliesnodeFor,callerOfand the two host verbs.membersHook({ roles, directory }), from the same subpath, is what a vertical handsvertical-host'smembersto let the dashboard manage its members.rolesis the list it givesmountInviteRoutes. Both doors mint an invite with the onemintMemberInvite, so a dashboard invite is accepted at the app's own/api/accept-invite. Accepting only binds the login in the directory; the role was granted when the invite was made. A removal from the dashboard withdraws the invite in that same directory, so an old link accepted after it finds nothing.
Cookie-domain safety
resolveCookieDomain decides the session cookie's Domain for multi-surface installs, and refuses to set one on a public suffix — the boundary where one tenant's cookie could reach another. It is guarded by the real Public Suffix List via @substrat-run/psl, not a label-count heuristic.
Runtime
Workers-targeted: jose + Web Crypto, no node:*. IdentityDO extends the cloudflare:workers DurableObject base, and the vertical's worker bundles this package and re-exports the DO class so wrangler can see it.