Skip to content

Authentication & identity ​

The kernel authorizes; it never authenticates. Every operation runs against an ambient PrincipalId that is already established by the time the kernel sees it — the kernel never learns how a caller proved who they are, only who they are. Authentication is a swappable adapter at the edge (decision D-16).

The line: authenticate vs authorize ​

  • Authorization is the kernel's — roles, grants, tenancy, the tuple evaluator (permissions). This is enforced on every operation and cannot be delegated to an outside system.
  • Authentication is an adapter's — it takes a request (a session cookie, a bearer token, an OIDC sub) and resolves it to a PrincipalId + home node. Nothing more.
  • An external IdP's organizations/roles are a projection of kernel tuples, never the source of truth. If you let an IdP's RBAC decide access, you have two permission systems fighting — exactly what the three-layer rule forbids.

The neutral seam ​

The control-plane directory holds one provider-agnostic mapping:

sql
_substrat_identities (
  provider     TEXT,   -- 'better-auth' | 'oidc:<issuer>' | …
  external_id  TEXT,   -- the provider's stable user id (e.g. the OIDC `sub`)
  principal_id TEXT,   -- the Substrat principal it resolves to
  tenant_id    TEXT,
  scope_id     TEXT,   -- NULL = tenant-level home
  PRIMARY KEY (tenant_id, provider, external_id)
)

exposed on the host admin as two methods:

ts
linkIdentity(actor, { provider, externalId, principal, tenantId, scopeId? }): void // audited; idempotent per (tenantId, provider, externalId)
resolveIdentity(tenantId, provider, externalId): { principal, scopeId } | undefined

Because the mapping is keyed by provider, several auth adapters — and several OIDC upstreams — coexist without collision. Adding one is additive: no schema change, no permission, no kernel change.

Pools are registered, and declare their topology. Before a provider may link anything it registers as central (one pool serving many tenants — the same externalId everywhere is the same human) or tenant-bound (one pool, one tenant — the same externalId elsewhere is a different human). An unregistered provider is refused rather than defaulted: without that fact the kernel would be guessing whether two people are one.

ts
await host.admin.registerIdentityPool(actor, {
  provider: 'oidc:https://issuer.example',
  topology: 'tenant-bound',
  tenantId,                       // null for a central pool
});

Topology, not audience. A padel player on a branded multi-club platform is a consumer who wants the central topology, while a shopper on a white-label store is a consumer who must not have it — so the audience is shorthand and the topology is the enforceable fact. A provider string names exactly one pool, so separate per-tenant deployments take distinct provider strings (oidc:<issuer>).

And keyed by tenant. The full key is (tenantId, provider, externalId), with the tenant as an input to the lookup rather than something derived from the identity. That matters as soon as tenants have their own identity pools: an external subject id is unique only within its pool, so two white-label shops can both issue user 123 to different people. A globally-keyed mapping would resolve the second as the first.

The same key is what lets one login belong to several tenants — a consultant administering five customers is one external identity with one row per tenant, and one principal per tenant. Shared identity, separate authority.

The caller always knows which tenant it is asking about: the request arrived on that tenant's hostname, or carried a pool-scoped token.

"Which tenants is this login in?" is a separate call, and central-only:

ts
await host.admin.listIdentityTenants(actor, provider, externalId); // → TenantId[]

It throws on a tenant-bound pool. Not because the answer would leak — the caller already knows that pool's tenant — but because asking is a category error: where the same externalId names different people per tenant, a tenant list has no meaning. Enumerate, then resolve within the one you picked.

When the caller wants the whole picture — a team switcher, or a per-request "who is this login, in the team they selected" — asking once per tenant is the wrong shape: on a hosted directory every one of those reads is a round trip, and the cost grows with the number of tenants the login is in. listIdentityMemberships is the same central-only question with the follow-ups already attached:

ts
await host.admin.listIdentityMemberships(actor, provider, externalId);
// → [{ tenant, principal, scope: { id, vertical, status } | null }]

One read, one access-log row. Each entry carries the tenant row whole — status included, and a non-active tenant is returned rather than filtered, because whether a deleting team still resolves is the caller's policy — the login's principal in it, and the scope the link was made in. It throws on a tenant-bound or unregistered pool exactly as listIdentityTenants does.

Auth adapters at the edge ​

An auth adapter is anything that turns a request into a principal:

ts
interface AuthAdapter {
  resolve(headers: Headers): Promise<AuthResult | null>; // null = "not mine"
}

The server tries its mounted adapters in order; the first to recognise the request wins, and the resolved principal is handed to getScope. Which adapters a vertical mounts is the vertical's decision, and the two shapes in the repo make it differently:

text
# most verticals — one provider, picked in code
authProviderFor(env)  →  oidcRpAuthProvider({ issuer, clientId, … })

# demos/shop — the same OIDC session, else an anonymous browse-only fallback:
# a storefront must answer "what may someone who has not signed in see"
oidcRpAuthProvider(…), then the public adapter, last

An OIDC-only vertical has no auth switch at all: the relying party from @substrat-run/vertical-auth is its only way to resolve a caller, and the thing that varies is OIDC_ISSUER — a configuration value, not a code path.

"Log in with …" belongs at the issuer, not in the vertical. An issuer can federate upstream identity itself (Microsoft, Google, BankID, enterprise SSO — see the issuers below), so those buttons become issuer configuration while the vertical keeps exactly one adapter against the sameresolveIdentity. The kernel is untouched either way: doing the seam neutrally is what buys the choice.

Two real choices, made differently ​

The neutral seam is not hypothetical — the codebase exercises both ends of it deliberately:

  • The platform's own apps — the Dashboard and the control-plane Console — authenticate against AuthHero OIDC (Authorization-Code + PKCE) through the shared @substrat-run/oidc-rp relying party. One IdP, one session model, across every platform surface — including the substrat login CLI, which brokers the same flow. This is the "log in with SSO" corner, chosen because platform staff and tenant admins are one identity population the platform runs itself.
  • Every demo vertical is OIDC-only — none runs a credential store. Login, sign-up, password and reset all live at an OIDC issuer, and the vertical does exactly one thing with the result: bind the authenticated sub to a scope principal — hosted, in its per-tenant IdentityDO through the owner-claim and invite flows (@substrat-run/vertical-auth); locally, through the host's identity directory, which the seed fills from the same persona list the issuer shows. Hosted, that issuer is whatever the tenant configured; locally it is the dev issuer. The one deliberate wrinkle is the shop, which also keeps an anonymous browse principal — not a credential store, but the storefront's answer to "what may someone who has not signed in see". The design record is oidc-only-demos.md.

That the same kernel serves all of them, unchanged, is the seam paying out. Better Auth still runs in the repo — in exactly one place, as an issuer rather than an adapter: the auth server below.

The issuers: bring your own, or use ours ​

A vertical is a relying party, so any OIDC server works — Okta, Entra, Keycloak, AuthHero, your own. Pointing a deployment at it is a change of OIDC_ISSUER (or of the delivered substrat:auth connection), never a code change. Two issuers ship with the platform so you never have to bring one just to start:

The dev issuer (local) ​

@substrat-run/dev-issuer is what every demo's pnpm dev starts: a real OIDC provider — discovery, JWKS, Authorization Code + PKCE, a signed ID token — whose only shortcuts are that /authorize lists the vertical's personas instead of asking for a password, and that it registers no clients and checks no client secret (loopback-only, never deployed, so there is nothing to compare against). The protocol the vertical runs is unchanged: the dev login is the production round-trip, and a script impersonates someone at the issuer (POST {issuer}/dev/token {"sub": …}), never inside the vertical.

The auth server (a full OIDC provider you can run) ​

The auth-server is a complete OIDC provider built on Better Auth — accounts, passwords, verification and reset mail, discovery, JWKS, the whole authorize/token/userinfo surface — deployable standalone on its own hostname or installed per tenant on the platform (each install is its own issuer with its own store and signing keys). It exists so "I just need somewhere for my users to log in" has a stock answer; it stops being special the moment you swap OIDC_ISSUER for an issuer you already run. What it ships:

  • An admin dashboard. Users (roles, bans), the relying-party registry — register an application, rotate its secret, disable it, including clients that registered themselves — sign-in options, and the issuer's own discovery details. The issuer is its own first relying party; the dashboard is gated by its admin role.
  • Federated sign-in, enabled from the dashboard. Microsoft (optionally pinned to one Entra directory), Google, GitHub and Supabase, as a closed catalogue: enabling one is a credential plus two decisions — may it create accounts, and is its email trusted for linking to existing ones — rather than a form of URLs to get subtly wrong. Supabase asks for one thing more, because no one could guess it: a project's issuer is the project URL with /auth/v1 on the end, and the project URL alone serves no discovery document. (It also needs the project's own OAuth 2.1 server turned on, authorization UI included — work on the Supabase side that no setting here can stand in for.) One open door sits beside that catalogue: Custom (OIDC), for the directory it does not name — Keycloak, Okta, Auth0, another auth server like this one. The ask keeps its shape. A custom provider is a slug (which is its callback path segment), a button label, the upstream's issuer URL and a credential, then the same two decisions — never five endpoints typed by hand, because an issuer URL is the one address OIDC lets everything else be derived from. Discovery is resolved once, when the provider is saved rather than on every sign-in, so an issuer URL that serves no discovery document is refused while the operator is still in the form. One issuer-wide setting sits above the per-provider ones: whether an upstream sign-in may join a local account that already holds the same email address, or must refuse and let the person connect the provider deliberately from inside a session. Keeping two separate accounts on one address is not offered — an email resolves to exactly one user in password sign-in, reset and recovery, so a second row at that address would make each of those pick one arbitrarily.
  • A Supabase project on the legacy JWT secret. Such a project cannot be a redirect upstream — Supabase will not mint an OIDC id_token under HS256 — so instead the issuer can accept an access token that project already issued, and turn it into a session here. The same person lands in the same account they would have had via the redirect flow, so migrating the project's signing keys later costs nothing. Off unless configured, and it refuses the project's own anon and service_role keys, which are signed with that very secret and are not people.
  • Swedish BankID. Not an OAuth redirect but the real relying-party flow: an animated QR code or same-device start, approval in the BankID app, and the verified personal number as the account key. With Require a verified email on, which is the default, a first sign-in proves an email address with an emailed code, and joins the account already holding it, and the address is emailed a notice that it happened. It refuses an account with an SMS factor, an address nobody has verified, one already holding another BankID, and a banned account; so does the issuer-wide ACCOUNT_LINKING=block, which never joins implicitly. The person is told to sign in to the existing account first and connect BankID from /account — a refusal there is the rule working, not linking broken. The mTLS client certificate is pasted in the dashboard; the test environment works with BankID's published test certificate, so you can try it before your bank issues a production one.
  • Merging two accounts. One person sometimes ends up with two accounts — a BankID sign-in and a Microsoft one — and cannot fix it from /account, because each method already belongs to an account. An administrator opens the account that should stay, goes to its Identities tab and chooses Merge another account into this one. The other account's sign-in methods move to the selected one, its sessions and issued tokens end, and the account is removed: its sub retires, so the direction matters. Merging refuses rather than lose something: a retired account an app has bound (merge the other way, so that sub survives), a retired account holding the admin role (remove the role first), a banned account on either side, and two accounts that both hold a password or both a BankID. It is one transaction, so a refusal leaves both accounts as they were, and it cannot be undone.
  • Client registration for machines. Dynamic registration (RFC 7591) and Client ID Metadata Documents (CIMD, under the MCP profile) — the mechanism MCP clients use: a client identifies itself by an HTTPS URL that is its metadata document, so nothing is registered, stored or rotated per client until one actually arrives.
  • Machine applications and their scope ceiling. An unattended client that signs in with client_credentials — nobody authenticates into it — is registered as a machine application and holds a subset of one issuer-wide list, MACHINE_SCOPES: the ceiling on what any machine client may be granted. It starts empty, and an empty ceiling is a decision rather than a gap: no machine application can be registered and none can get a token, until an administrator names the scopes. An administrator sets it under APIs → Machine access in the dashboard, or from the scope picker on a machine application's own form when the ceiling is still empty. Both write through PATCH /api/admin/settings with machineScopes: string[], which replaces the whole list and is gated, like the rest of the admin API, to a signed-in account holding the admin role. It writes the same delivered config key the platform's Env setting does (MACHINE_SCOPES, space- or comma-separated), so there is one answer whichever set it last. The issuer judges the list before storing anything: an entry that is not a valid scope token, or one of the sign-in scopes (openid, profile, email, offline_access), is refused with the reason, because a machine token has no person behind it. The ceiling is enforced on every token request, not only at registration: a scope asked for outside it is refused (invalid_scope), a request that names none gets what the client holds and the ceiling still lists, and an empty result is refused. So removing a scope stops it being minted from the next token request — for every machine application that held it — but does not revoke a token already issued, which stays valid until it expires.
  • Your places. Every signed-in account, administrator or not, has a Your account page on the issuer that lists the apps it is a member of, across every team whose apps sign in here, each with a link into it. No app can answer "where else am I": a login is a different principal in every scope, and no vertical sees another tenant. So the issuer keeps the list, keyed on the sub it minted, and shows it only to the account it belongs to. It never names a tenant the account is not in, and it has no parameter through which one account could ask about another. Which apps are places, and under what name and hostname, is the platform's to say: the dashboard registers each app that signs in with a team auth server. The app itself only reports who is bound in its scope, as the client the platform registered for it, and the issuer keeps an addition only for an account it has itself signed in to that app. Removing someone from an app removes the entry, and a platform reconcile sends each app's whole membership, so a report that went missing is repaired. It is not available for external issuers (Supabase, Auth0, AuthHero, any OIDC provider the platform does not host): the list lives with a pool the platform hosts, so an app signing in elsewhere reports nothing and its users have no places page. A tenant your manager app creates with provision-tenant and instance.signIn is listed: the platform registers its client and its place at your auth server (building a platform). Other apps of another team that sign in at your auth server are not listed yet.

Bearer tokens: whose token it is ​

A browser signs in once and holds a session cookie. An API client or an MCP client presents the issuer's token as Authorization: Bearer instead, and the vertical verifies its signature and issuer. What else it checks depends on whose issuer it is.

  • One of your team's auth servers. Every app on the team signs in there, and so can any client that registers itself. So a token that verifies says who signed it, not which app it is for. A vertical bound to a team auth server accepts only its own tokens: its own id_token (aud is its client id), a token issued to its client (azp or client_id is its client id), or an access token for its own MCP endpoint (aud is https://<host>/api/mcp, whichever client requested it). Another app's id_token, or a token minted for another vertical's MCP endpoint, is a 401, even when the app's own client is the one it was issued to. A token carrying act (another app acting for the user) is a 401 too, unless the app has opted in to delegated calls, and the token exchange's intermediate assertion is a 401 on every issuer. A plugin also takes one on a peer call from the app it takes its people from, and nowhere else (below). The dashboard tells the app its issuer is shared (the substrat:auth:shared-issuer delivery) at install and on every Identity change. Apps installed earlier are told the next time anyone on the team opens the Apps list.
  • An issuer you configured by hand (Supabase, Auth0, Keycloak, …). It is yours, so the vertical keeps checking what it always checked: the signature and the issuer. To hold bearers to one audience, set the connection's audience, for example authenticated for a Supabase access token or your API identifier at Auth0. A set audience always wins, on either kind of issuer.

Locally, devLogin applies the team rule, so a script that works against pnpm dev works hosted. /dev/token mints for the harness's client (substrat-dev) unless you pass an audience.

Identity sync on first login ​

The first time an adapter resolves an external user it hasn't seen, it provisions them — the plan's §4.3 flow — then binds the identity:

  1. mint a PrincipalId;
  2. assign the role(s) that user should hold;
  3. create the domain records they own (e.g. a customer);
  4. issue any entity-narrowed grants (e.g. read-your-own-orders);
  5. linkIdentity((tenantId, provider, externalId) → principal).

From then on resolveIdentity short-circuits to the same principal — a stable identity with real, enforced permissions.

In the demo ​

The Kallkälla Kaffe shop signs people in through the dev issuer — pnpm dev starts it, and /authorize lists the cast below — plus a browse-only anonymous fallback. Picking a persona lets you feel the permission model; there are no passwords, because the vertical holds no credentials.

Sign in asRoleSees
Astrid Kallkällashop-admineverything — catalogue, stock, orders, invoicing
Gustav (lager)warehouseorders + stock; invoicing is denied
Elin – Café Pascalcustomerthe shop + only her own orders
Otto – Kontoretcustomerthe shop + only his own orders
Ny Kundcustomera fresh principal, provisioned on first login
(not signed in)publicbrowse the catalogue only

Signing in as Gustav and watching Invoice basis disappear from the nav — and 403 if you ask for it directly — is the whole thesis in one click: the issuer authenticated you, the kernel authorized you.

The caller's verified address ​

An operation reads the address the issuer verified as ctx.verifiedEmail, and never takes the caller's own address as input. Anything keyed on an address trusts it, so a typed one would let a person claim someone else's. A declaration whose join or sign-up takes email does not load.

The door passes it to getScope, beside the principal:

ts
const caller = await login.caller(headers);
const stub = await host.getScope(caller.principal, caller.tenantId, caller.scopeId, {
  verifiedEmail: caller.verifiedEmail,
});

A door using @substrat-run/vertical-auth directly gets the value from verifiedEmailOf(subject). Leaving it out is safe: ctx.verifiedEmail is then null, so a person joins nothing. It is also null for a schedule, a consumer, a connection, a peer, a capability, someone acting as a person, and a delegated token, because none of those is the person proving the address. OIDC_ALLOW_UNVERIFIED_EMAIL keeps a person signed in, and does not reach this field.

People owned by another app ​

A vertical normally owns who is in its scope. A plugin of another app does not: the other app decides who exists and what they hold, and the plugin asks it. Both run in the same tenant, on the same issuer, as separate verticals with separate databases.

The question and its answer are the person contract, identity.person@1, in @substrat-run/contracts. The app that owns the people implements one operation with those shapes and names the plugin as a peer for it:

ts
// the app that owns the people
'workspace/resolve-person': {
  summary: 'Who a login is here, for a plugin',
  permission: 'people:resolve',
  input: personResolveInput,    // { issuer, sub, verifiedEmail }
  output: personResolveOutput,  // { person: { id, status, roles } | null }
},

Declare that key with holder: 'system', so no person's role can carry it, and list the plugin with peersDeclaredBy. The answer has an id, a status and role keys. It has no name and no address.

The plugin's door is admitPerson from @substrat-run/vertical-auth/people (devPeople in @substrat-run/dev-issuer wraps it for a dev server). When a login it has not seen makes a request, it asks, then:

  • lets the person in as the id the other app gave, which becomes their principal here;
  • seats the roles your mapping turns the other app's role keys into, and removes the ones it no longer maps to;
  • keeps the answer for five minutes (PEOPLE_TTL_SECONDS).

Within that time a request costs no call. After it the door asks again. So a person blocked in the other app, or whose roles changed there, is refused or re-seated in the plugin within five minutes, and that number is the bound to plan around. If the answer has expired and the other app cannot be reached, nobody is admitted.

The other app answersThe plugin
a person, activeserves them, with the mapped roles
a person, active, no rolesserves them; every operation is 403
a person, invited or blocked403, and removes their roles
nobody403
nothing (unreachable, answer expired)503

ctx.check is unchanged and makes no network call. Hosted, the plugin names the other app in workerDoor({ people: { master, resolveOperation, roles } }), and the answers are kept in the tenant's identity directory. A plugin owns no people, so it names neither invites nor join, and has no owner seat. demos/notes beside demos/todo is the runnable pair.

Calling a plugin as the person ​

The app that owns the people can also call its plugin as the person signed in to it: Todo writes a note in Notes as Ada, and Notes records Ada as its author. The person's sign-in is proven, not claimed. The calling app trades the refresh token of the person's session at the issuer for a token addressed to the plugin, and the peer call carries it. The plugin checks that token itself before it lets the call in.

Each side wires one thing more:

  • The plugin declares who may act for its people, and with which of its keys, in its manifest:

    ts
    delegations: [{ actor: 'todo', permissions: ['note:read', 'note:write'], channels: ['peer'] }],

    PERMISSIONS.md renders it, so letting another app act for people is in the reviewed permission diff. The dashboard delivers it to the team's auth server, which exchanges no token it was not given a grant for. The dashboard manages that grant from the declarations alone: see the MCP page if you delivered one by hand. Hosted, the plugin's door takes such a call from its people.master only. Locally, devLogin({ clientId, delegation: { actors: ['todo'], channels: ['peer'] } }) and devPeople({ master: 'todo', … }) do the same, and the dev issuer takes the grant with --delegations.

  • The calling app keeps refresh tokens and makes the call. Hosted, workerDoor({ refreshTokens: true }), then door.peerAs(c, 'notes', 'notes/add-note', { text }), with the plugin in substrat.calls as for any peer call. Locally, devLogin({ refreshStore: devRefreshStore(db) }) and devDelegate({ login, store, peer }). Sign-in then asks for offline_access. A session started before that has no refresh token, and the call is 401 until the person signs in again.

What a call made this way can do:

  • It runs as the person. ctx.principal is them, their roles in the plugin decide every check, and rows and events are theirs.
  • The plugin's keys are a ceiling, never a grant. A key the delegation does not list is refused even when the person holds it; a key the person lacks stays refused whatever the delegation lists. Keep out any operation that relies on the door having checked something first: Notes' item notes trust the door to have asked Todo whether the person may see the item, and a call made for a person does not pass that door, so they have keys of their own that Notes does not delegate.
  • The person is let in as their own sign-in would be. Their kept answer must be fresh, or the other app asked again, and active. So the bound is unchanged: a member whose plugin access is taken away is refused within five minutes. The token the call carries lives five minutes too.
  • It is not a peer call with a person attached. It does not pass the plugin's peer door, and holds none of the keys the calling app holds there as a peer.

What it cannot do: act for someone who never signed in to the calling app, or act from a schedule with no session behind it. How long it can act for someone who did:

  • While the calling app's own session for them lives, up to that session's lifetime, and while the auth server keeps honouring the refresh token.
  • A ban at the auth server stops it at the next exchange, so within five minutes.
  • Blocking them in the calling app stops it within the plugin's kept-answer lifetime, five minutes.
  • Signing out of the calling app stops it: the sign-out deletes the refresh token it kept.
  • Signing out at the auth server alone does not. The refresh token outlives that session, and the calling app's own session still acts for them there anyway.

Nothing proves the person is behind each request. Nothing yet records in the plugin which app made a call. Its history shows the person.