Why the account system is built the way it is — sessions in Postgres and minted by the api, opaque link tokens, removal as a state change — is recorded in
ACCOUNTS-DESIGN.md(MAG-2729), the design it was built from.
The dashboard has two auth modes, selected by the AUTH_MODE env var
(same value on the api and the web):
| Mode | What it means |
|---|---|
disabled (default) |
Today's behaviour — no login, no database, every route open. The zero-dependency self-hosted posture. The api registers none of the account routes, and the web follows: no Team entry in the sidebar, /team redirects, and Account shows only the build details. |
enabled |
Auth.js v5 sign-in (email+password, plus OAuth), Postgres-backed users, HS256 JWT shared between web and api. /api/* requires a Bearer token. |
The implementation is a trimmed port of lava-connect's auth stack — same
JWT codec, same plugin layout, same seed semantics.
Ticket coverage:
MAG-2729-REQUIREMENTS.mdmaps every line of MAG-2729 to what implements it, with what is outstanding and who owns it.
Browser ── credentials ──▶ Next.js (Auth.js v5)
│ authorize(creds, request)
│ → POST api /auth/sign-in (bcrypt verify)
│ + the browser's own IP / User-Agent
│ signIn() → POST api /auth/oauth/:p
│ ← { user, sessionId }
▼
HS256 session JWT (jose, AUTH_SECRET,
sid = sessionId,
iss=smart-router-dashboard-web,
aud=smart-router-dashboard-api)
│
Browser ── Authorization: Bearer <same JWT> ──▶ Fastify api (@fastify/jwt)
├─ verify signature + iss/aud
├─ resolve sid → sessions ⨝ users
│ revoked? expired? status? cutoff?
└─ global gate: /api/* → 401 without it
- Web (
apps/web/src/auth.config.ts) — Auth.js v5 with a custom JWT codec: plain HS256 signing viajoseinstead of Auth.js's default JWE, so the api can validate the same token with@fastify/jwt. The session exposesaccessToken;ApiTokenBridgemirrors it into a module store andlib/api-client.tsattaches it to every fetch (and waits for the bridge on first load so nothing races a 401). - Edge gate (
apps/web/src/proxy.ts) — redirects unauthenticated page loads to/login; signed-in users hitting/loginbounce to/metrics(HOME_PATH,apps/web/src/lib/home-path.ts). A no-op in disabled mode. - Api (
apps/api/src/plugins/auth.ts) — validates HS256 + iss/aud, then resolves the token'ssidto a live session and the live user row, and puts both onrequest.authUser. 401s any non-public route without one. Public:/health*,/version,/auth/*,/docs*.requireRole(request, reply, minimum)gates by role, comparing the row's role rather than the token's. - Database (
packages/db) — Drizzle + Postgres:usersandsessions. The api's db plugin connects lazily with retries (no composedepends_on), runs migrations, then seeds the admin. While it is settling,/auth/*and every authenticated route answer 503 — the gate fails closed, because a signature check alone cannot tell whether a session was revoked or an account removed.
DEPLOYMENT_MODE (managed | onprem, default onprem) forks every
credential-delivery path, because on-prem has no mail server and never
will. Defaulting to onprem is the safe way to be wrong: the failure mode
is "an admin copies a link", not "an invitation silently never arrives".
| Managed | On-prem | |
|---|---|---|
| First admin | a Magma operator runs the first-run page, then invites the customer's named admin | first-run page + the installer's setup token |
| Magma Devs account | the first-run account is ours, stays, and is labelled | never — the first-run account is the customer's own |
| Invite / reset delivery | emailed — see Email | link shown to an admin, handed over |
| Password-changed notice | emailed to the owner — see the notice | none; the audit row is the record |
| Invite TTL | 7 days | 24 hours |
| Reset TTL | 1 hour | 24 hours |
The web needs this at runtime, not build time — NEXT_PUBLIC_* is baked
into the bundle and one published image has to serve both shapes — so it
comes through GET /api/config alongside DASHBOARD_API_URL.
The Helm chart renders AUTH_MODE and DEPLOYMENT_MODE on both pods from
its dashboard.auth block (mode, deploymentMode). The fleet's tenant template turns accounts on for
every new managed deployment (mode: enabled, deploymentMode: managed),
and with accounts on 2FA is required of everyone
(Two-factor).
A fresh install has no accounts, so there is nobody to sign in as. The first-run page creates the first admin, and nothing else opens until it is done.
Two properties matter more than the rest:
- The gate is "no active users", never a flag. A one-time marker is the
obvious implementation and it is wrong: a deployment restored from a
backup taken before its first account would carry the marker and refuse
to open, permanently. Deriving the state from the table means the answer
is always about the install in front of you. (
GET /auth/bootstrapreports it; it never reveals the token.) - A setup token is required. Without one, whoever reaches the URL first
between
helm installand the operator sitting down becomes the admin — and that gap can be overnight. The same protection covers the restored backup above, where the window reopens on a deployment that is already reachable.
api boot, AUTH_MODE=enabled, database up, no active users
├─ SETUP_TOKEN set, ≥ 16 chars? → use it (helm: value lives in a Secret)
└─ else → generate 32 bytes, log once at warn,
write to SETUP_TOKEN_FILE when set
This happens at boot, not on the first request, and that is the whole
point: an operator with no SETUP_TOKEN configured has nothing to type
until something has generated the value. It is gated on "no active users",
so a deployment that is already claimed never mints or logs a token.
Generating rather than disabling setup is deliberate: an operator who
forgot to configure a token should still be able to finish the install,
from a value only log or filesystem access reveals. A SETUP_TOKEN shorter
than 16 characters is refused the same way and a generated one used in its
place — /auth/setup is public, and 10 attempts a minute bounds guessing
without stopping it.
The window reopens whenever there are no active accounts, not only on a
fresh install: suspend or remove every member and the deployment is
claimable again by whoever holds the token. That is deliberate — it is what
makes a restored backup and a locked-out install recoverable — but it means
the token stays security-relevant for the life of the deployment, and it
sits in the pod log. Rotate SETUP_TOKEN if that log is widely readable.
POST /auth/setup re-checks the zero-user condition inside the
transaction, behind an advisory lock — the check outside it is only
advice, and two people opening the page at the same moment would otherwise
both become admin.
It does not open a session. The web signs the new admin in immediately afterwards through the ordinary credentials path, so the operator is not left staring at a login page holding a password they just set — but the session that carries them there is that one, minted the same way as every other. An api-side session would be a second row nobody ever presents.
The page is not gated on the mode — something has to create the very first account whoever hosts the deployment. On managed that first account is therefore ours: a Magma operator runs the page, then invites the customer's named admin, who sets their own password from the invitation link. Nobody at Magma ever knows the customer's password, and the operator account stays after handover.
The rule that governs it (MAG-2729, decided 26 Aug 2026) is "no hidden Magma
account, and none the customer can't see in their member list" — visibility,
not absence. So POST /auth/setup stamps users.is_magma_account when
DEPLOYMENT_MODE=managed, and:
- the member list shows the row with a Magma Devs tag, and
members.csvcarries amagma_accountcolumn; - it is full admin, on by default;
- it is logged like any other account — nothing filters it out of the member list, the export or the audit log;
- a customer admin removes it like any other member. No guard, no special case. If you find yourself adding one, that is the requirement inverted;
- on-prem no account ever carries it, because nothing else writes the column.
An invitation never sets it, including one sent by the operator: the label means this account is Magma's, not Magma created it. The distinction is what keeps it useful after the customer's admin has invited their own team.
After first-run setup, the only way an account comes into existence. Two properties carry the security of the flow:
- The account is created with the invitation's address, never the submitted one. That makes "redeemable only by the address it was sent to" structural rather than a check someone can forget to write. The Google path compares the verified claim to the invited address and refuses a mismatch by name, so an honest person who used the wrong account knows which one to use.
- The raw token exists only inside the link. The row stores its SHA-256, so a backup, a log line or a support screenshot can't be turned back into a working invitation.
Single-use is a conditional UPDATE … WHERE redeemed_at IS NULL AND revoked_at IS NULL AND expires_at > now(), run in the same transaction as the account
insert. Zero rows affected means somebody else got there first and the whole
transaction unwinds — a race can't produce two accounts from one invite, and a
crash can't leave a redeemed invite with no account. The invite.redeemed
audit row is written in that transaction too (with, for a Google or GitHub
redemption, the session it opens and its signin.succeeded), so an account
the log cannot record is not created.
| Managed | On-prem | |
|---|---|---|
| Delivery | emailed; the link comes back to the admin only when the send did not happen (Email) | link returned to the admin, once, and handed over |
| TTL | 7 days | 24 hours |
Resending mints a new token and kills the old link, so it replaces the
attack surface rather than widening it. Expiry needs no sweeper: the first
read that observes it stamps expired_noted_at conditionally, which is what
lets invite.expired fire exactly once. The row's time is the invitation's
expiry, not the read that noticed it.
Invitations an admin sent die with that admin's access: removing them, or
changing them to any other role, revokes every one still unredeemed, expired
ones included (a resend would revive those), with an invite.revoked row each.
Every dead-link reason — used, revoked, expired, never issued — returns the same message and the same 410. The holder can't act on the difference, and distinguishing them would tell a stranger which of those a guessed token hit; a 404 for "never issued" beside a 410 for the rest would have said it in the status line while the message withheld it.
OAuth is link-only from here on.
upsertOAuthUserused to fall through to an insert, which was correct while accounts came only from a seed. With invitations that is a hole big enough to walk through: anyone with a Google account could reachPOST /auth/oauth/googleand provision themselves. Account creation now lives in exactly two places — first-run setup, and invite redemption.
Because OAuth sign-in links and never creates, a bare signIn(provider) on an
invitation can only ever answer 403 — the account does not exist yet. The two
facts also arrive at different moments: the browser has the invitation token
from the start, and a verified identity exists only after the provider
redirects back.
Every provider the deployment offers goes through this, not just Google.
Redemption is the only way a social account comes to exist, so a provider the
invitation page fails to offer is one nobody can ever sign in with — the
sign-in and invitation screens share a single provider list
(components/auth/oauth-providers.tsx) so they cannot drift.
/invite/<token> ──POST /api/invite/handoff──▶ sr_invite cookie (httpOnly, lax, 10 min)
│
└─ signIn("google") ──▶ Google ──▶ Auth.js `signIn` callback
│ reads sr_invite
▼
POST /auth/invite/accept
{ token, oauthProvider, oauthToken }
│
201 { user, sessionId } ──▶ JWT `sid`
The token rides in a cookie rather than the OAuth state, which Auth.js owns
and signs for its own CSRF purposes. httpOnly keeps it away from page scripts;
lax is required, because strict drops the cookie on exactly the top-level
redirect back from Google that it exists to survive. It is burned the moment it
is spent, successfully or not, so a failed attempt can't be replayed.
A redemption that bounces because the person picked the wrong account (403)
returns them to /invite/<token>?error=email_mismatch with something they can
act on, rather than Auth.js's generic error screen.
A dead invitation falls through to an ordinary sign-in instead. The handoff cookie outlives an abandoned attempt by up to its max-age, so a plain sign-in started inside that window would otherwise be dragged through a redemption that cannot succeed; falling through gives that person what they actually asked for.
This is the one redemption path that opens a session server-side, and the
asymmetry is deliberate: the OAuth caller holds a one-shot token and cannot
start the round-trip again, so the session has to come from the redemption. The password path lets the ordinary credentials sign-in mint it a
moment later, exactly as /auth/setup does.
Aligned to NIST 800-63B, which is what auditors reference and is mostly a
list of things not to do. Enforced by services/password.ts on every
path that writes a password — first-run setup, invite redemption, reset,
and change — because the weakest password on a deployment is usually the
first one anyone set.
- 8 to 64 characters, counted in code points. Everything allowed, including spaces.
- No composition rules. No "must contain a symbol".
- No forced expiry. Scheduled rotation makes people choose worse passwords; rotate on evidence of compromise.
- A 72-byte guard. bcrypt truncates there and says nothing about it, so 64 emoji would have a decorative tail. Refused rather than silently cut.
- Checked against known-breached passwords via HaveIBeenPwned's range
API using k-anonymity: only the first five characters of the SHA-1 leave
the process, and
Add-Paddingkeeps response size from leaking the prefix's hit count.
Every screen that sets a password (Join, Setup, Reset and the Account page's
Change password) states the rule in one sentence, PASSWORD_RULE in
@sr/shared: "8 to 64 characters, spaces allowed. Passwords found in known data
breaches are refused." The two lengths sit beside it and the api enforces those
same constants. The forms check the length themselves, counted in code points
as the api counts, and say so under the field before anything is sent; the
byte guard and the breach check stay the api's.
The breach check fails open, with a logged reason, for a
reason a hosted product doesn't have: an on-prem deployment may have no
egress at all, and failing closed would make the first admin account
uncreatable — locking an operator out of their own install to enforce a
defence-in-depth check. PASSWORD_BREACH_CHECK=off disables it explicitly,
which is the honest thing for an air-gapped site to do rather than relying
on a silent timeout every time.
An admin never chooses someone else's password. They generate a link,
and the holder chooses the value. That makes a takeover visible, not
impossible: the admin holds the link and could use it themselves. What they
cannot do is set a password silently — password_resets.created_by records
who generated each link, the link and its password.reset_link_generated row
commit together, and password.reset_completed names that admin when their
link is used (used a reset link from Dana). (lava-connect's equivalent takes
a password in the body, which leaves nothing to see.)
| Managed | On-prem | |
|---|---|---|
| Started by | the holder, from Forgot password? on the sign-in page | an admin |
| Endpoint | POST /auth/password/forgot |
POST /api/team/members/:id/reset-link |
| Delivery | emailed | link returned once, handed over |
| TTL | 1 hour | 24 hours |
created_by |
null | the admin's id |
Self-serve reset is managed-only. POST /auth/password/forgot answers
202 for every address on a managed deployment, and emails a link only when the
address belongs to an account with a password — anything else would say who is a
member. It answers before looking the address up, so the time it takes says
nothing either. And it issues one link per account per five minutes: each new
link kills the last, so without a wait anybody who knows an address could keep
the inbox full and every link in it dead. Inside the window the link already
sent stays live, and the request is still recorded (not re-sent, a recent link is still unused), so a flood shows up in the log. So is every request that
sends nothing for another reason, on the same password.reset_requested row:
not sent, no account with this address, not sent, account removed, or not sent, the account has no password. The row is written after the 202, so it
changes nothing the caller can see.
On-prem it answers 404: there is nowhere to send a link. So does a managed
deployment with no mail transport (AWS_REGION unset), for every address and
writing nothing, because a link nobody receives would still kill any live one
the member holds.
In both modes an admin can also start one from the member's row on the Team page
(POST /api/team/members/:id/reset-link). That link is never emailed: the page
shows it once for the admin to hand over, and created_by names the admin. The
dialog says so, and on managed it points at Forgot your password? as the
emailed way. Either link lands on /reset/<token>. A new link kills any
earlier one, and so does the admin's own removal or demotion below admin: their
unused links die with a password.reset_link_revoked row each.
A dead link (used, replaced by a newer one, expired, or never issued) answers
410 with one message, "This link no longer works. It may have been used,
replaced or expired.", and the page says the same, whether the preview found it
dead or the link was spent while its form was open.
POST /auth/password/reset, in one transaction, claims the token with a
conditional update, writes the hash, revokes every session for the account
— per-device rows and the signed_out_all_at cutoff — clears the
account's lockout, and writes password.reset_completed with a
session.revoked per session it ended. A row that cannot be written undoes
the reset. A reset is what someone does when they think they are
compromised; the transaction is what stops a failure part-way from leaving an
attacker's session alive under the new password. Clearing the lockout lets the
owner use the new password at once; it does not stop anyone re-tripping it.
It does not sign anyone in. A reset link that logs you in is a reset link worth stealing.
Changing your own password (POST /api/account/password) requires the
current one and signs out your other devices, keeping the tab you are in.
Checking the current password is a credential guess, so it carries sign-in's
per-IP limit and spends from the account's budget below.
Either way a password changes — here, or by a reset link — a managed deployment then emails the owner that it changed; see the password-changed notice.
For an account with no password — one that signs in through a linked provider — both this and the admin's reset link say which provider it uses.
Four transactional emails: the invitation and the password reset, which
MAG-2870 specifies; the notice that a password changed, which MAG-2868 adds; and
the notice that somebody's two-factor authentication was reset, which is
MAG-2869's — see TWO-FACTOR.md → "Lost phone". All four
follow lava-connect's approach — SES v2 behind a single send function,
table-based HTML with inline styles because that is what renders the same in
Gmail, Outlook and Apple Mail.
On-prem sends nothing, ever. That is the design, not a limitation: the
invitation and the reset produce a link the admin hands over, the audit rows
stand in for the two notices, and no customer deployment needs a mail server.
The copy still matters there, because the same link lands in a chat message
instead. A two-factor reset there is recorded by its 2fa.reset row, which
names both people.
| Setting | Effect |
|---|---|
AWS_REGION |
The switch. Unset ⇒ nothing is sent and the caller is told. A warn line names the recipient and subject; the body, which carries a live link, is logged only under NODE_ENV=development |
AWS_ACCESS_KEY_ID / SECRET |
Optional. Both set ⇒ the send is signed with this pair; the fleet's managed deployments get one per tenant, scoped to sending as the no-reply address through that tenant's configuration set. Absent ⇒ resolved from the environment (IRSA, instance role) |
EMAIL_FROM |
Sender; an unmonitored no-reply |
EMAIL_REPLY_TO |
A monitored inbox, so a reply to a reset reaches somebody |
EMAIL_CONFIGURATION_SET |
Keeps each environment's bounce reputation separate on a shared SES identity |
SES_ENDPOINT |
Points at a local SES mock for development |
CUSTOMER_NAME |
Names the dashboard in every email, and in the invitation's subject ("{inviter} invited you to the Smart Router dashboard for {customer}"): an invite lands somewhere that has never heard of us, and the customer's own name is what stops it reading as spam. The fleet sets it to the tenant's name |
make accounts-managed # inbox at http://localhost:8005Mail goes to a local SES mock (dasprid/aws-ses-v2-local, the image
lava-connect uses) rather than to Amazon. It implements the SES v2 API, so
SES_ENDPOINT is the only thing that differs from a real send — the SDK cannot
tell, and neither can our transport. Nothing leaves the machine and no AWS
account is involved.
Two reasons this beats pointing at real SES in development. A new SES account is
sandboxed, and silently drops mail to any address you have not verified with
Amazon, so a test invitation to a made-up address looks accepted and never
arrives. And the mock keeps every message in a browsable inbox, so the
invitation and the redemption that follows it are one continuous flow: open the
inbox, click Set up your account, land on /invite/<token>.
To send for real, drop SES_ENDPOINT and supply real credentials. The demo path
and the production path differ by that one variable.
sendEmail never throws. An invitation row is committed before the send is
attempted, so failing the request would report failure for something that half
happened — and returning 201 with no link would leave an admin believing an
invitation is on its way to somebody who will never receive it.
So the three outcomes collapse into two shapes, and the response says which:
- sent — the link is in the recipient's inbox and nowhere else. The response carries no url.
- not sent (no transport, or SES refused) — the response carries the url and
deliveryFallback: true, and the invite dialog says the email could not be sent rather than reusing the on-prem wording, which would blame a deployment shape for an operational fault.
Password reset has no such fallback: there is no admin in that flow to hand a
link to, and returning one would let anybody mint a reset for any address. With
no transport configured it fails closed instead (404, nothing issued); when SES
refuses a send, the audit note is the only record it went nowhere.
A password change the owner did not make is the earliest visible sign that
someone else is in the account, so the owner is told whenever it changes,
whichever way: Change password on the Account page
(POST /api/account/password), or a reset link being used
(POST /auth/password/reset). Every reset link ends there — a self-serve one,
an admin's, and the one make recover CMD="reset-password …" prints — so all of
them are covered. Creating an account sets a password too (first-run setup,
invite redemption), but there is no earlier owner to warn.
It says that the password changed, when (in UTC, Nov 11, 2026, 14:05 UTC,
from the password_updated_at the change wrote), and what to do if it wasn't them: open the dashboard the way
they usually do, choose Forgot your password? on the sign-in page to set a
new one, which signs out every device, and tell their administrator. It carries
no link — see the rules below.
| Sent | Recorded in the audit log | |
|---|---|---|
| On-prem | never, whatever the transport | nothing; the change's row is the record |
Managed, AWS_REGION unset |
not attempted | owner not notified, no mail transport |
| Managed, SES took it | yes | owner notified by email |
| Managed, SES refused it or did not answer | no | owner not notified, email failed |
The send happens after the change has committed, so it can neither undo
the change nor fail the request: a refused send comes back as a value, and the
response is the same 200. For Change password the outcome is the note on
password.changed. For a reset link it is a password.reset_notice row of its
own, written after password.reset_completed: that row commits with the reset,
before anything is sent. The request does wait for it, to know what to
record — SES answers in well under a second, and the transport's timeouts bound
one that never answers.
lava-connect has user_emails because it has sixteen types, an admin console
answering "did this person already get X", CSV export, and SES bounce
correlation to build on. None of that is in scope here, and a table nothing
reads is schema to migrate around later.
The one fact worth keeping — did it go, or is the admin holding the link — goes
on the audit row that already describes the event. member.invited and
invite.resent record emailed, link shown to the admin, or email failed, link shown to the admin in their note — on member.invited, after the role
and expiry the row already carries (as Approver, expires …; emailed).
password.reset_requested has no admin to hold a link, so it records emailed
or email failed, no link delivered. The password-changed notice is the note
on password.changed. The notices that follow a change committed in its own
transaction cannot ride on that change's row, so each is a row of its own:
password.reset_notice after password.reset_completed (owner notified by email), and 2fa.reset_notice after 2fa.reset (emailed, not sent, no mail transport or email failed, not delivered).
The body is never persisted, in either design — not in a table, and outside development not in a log line either. A rendered invitation contains a live token.
From the ticket, and each has a test:
- The link appears as text as well as a button, in the two emails that have one. Mail clients strip buttons and people forward these.
- The expiry is in the message, and is passed in rather than written into the copy — lava-connect's template hardcodes 30 minutes and ours is an hour.
- No marketing footer, no tracking, no unsubscribe. The shell has no footer
and no
<img>at all: a remote image in a security email reports when it was opened and from where, whether or not anybody meant it as a tracking pixel. The wordmark is set in text. - The invitation names who sent it: by name in the subject, and with their address and the role it grants, by its label, in the body ("Invited by Victoria Admin (victoria@example.com) as Read-only."). A resend names the admin who resent it. Its last line says the link sets up the account for the one address it names, so it is not forwarded.
- The reset says what to do if it wasn't you, as the last line.
- The password-changed notice carries no link at all — no button, no reset link, no sign-in link. A takeover notice with a button is one an attacker can copy and bait somebody into pressing. It says what to do in words, and its last line is "We never put a link in this notice. If a copy has one, don't click it.", so a copy that has one gives itself away.
- A time reads one way in every email:
Nov 11, 2026, 14:05 UTC— the dashboard's date and 24-hour clock, with the zone written out. The dashboard shows the reader's own zone, which the browser reports; an email has no browser and an account stores no zone, so it gives UTC, the zone of the audit log.emailTime(services/email-time.ts) writes every one. - US English, "2FA" as the feature's name, and no long dash (an em or en
dash) in any subject, plain text or HTML part: a pause is " - " or two
sentences.
email-copy.test.tsrenders every email and checks all three.
make accounts-reset && make accounts # or accounts-managed
node scripts/sanity-accounts.mjsThe eleven acceptance checks on MAG-2729, run against a live deployment over
HTTP with the audit log read straight out of Postgres. To do the same by hand,
through the screen, follow
MAG-2729-MANUAL-CHECKS.md. Several
of them only mean something at runtime — "a lower role is refused the action
when it's attempted directly, not just when the button is hidden" is a claim
about the api holding a real token, and the runner makes exactly that call.
It refuses to start against an install that already has accounts, because the first check is about a fresh one.
Each address has a budget of 5 attempts per 15 minutes, counted whether or
not an account exists, case-insensitively — so a lockout says nothing about
membership. Past it, sign-in and the current-password check both answer 423
with Retry-After, and the login form says "Too many failed attempts. Try again
in 15 minutes, or reset your password." rather than that the password is wrong.
15 minutes is the window, so it is the longest a lock lasts: the lock lifts 15
minutes after the window's first attempt.
The attempt is counted before the credential is checked: the upsert hands each request its own count, so a parallel burst gets exactly the budget, not one guess per request that passed a read before any count moved. A correct credential refunds the window.
The budget is per identity, which is why it holds where a per-IP limit does
not: with the api reachable directly and TRUST_PROXY at its default, a caller
chooses its own X-Forwarded-For, and the per-IP limit follows.
The trade-off. Anyone who knows an address can keep that account locked by spending its budget every window, and the correct password is refused while it is. A reset clears the lock, but it can be re-tripped. The way back in for a locked admin is the database:
DELETE FROM login_attempts WHERE email = lower('admin@example.com');
signin.blocked names the account (when there is one), the address and how
many attempts this window, and is written in the transaction that counted the
attempt. Sign-in costs one bcrypt whether or not the address
has an account — a decoy hash stands in — so timing does not answer the
question the identical 401 refuses to.
A refused sign-in's row (signin.failed, or signin.blocked with the note
account removed when the address belongs to a removed account rather than to
nobody) is written in a transaction of its own after the check, and a write
that fails answers 500 instead of the 401. Not in the counter's
transaction: the attempt commits before bcrypt runs and is never given back
because the log failed.
Rows whose window has lapsed are pruned on every attempt, a bounded batch
over an index on window_start, so the table is sized by attempts per window
rather than attempts ever.
Failed two-factor codes land in the same row, at the same five-in-fifteen. One counter, keyed on the address — a second one would quietly hand an attacker five password attempts and then five code attempts. The corollary is that the counter clears when a sign-in completes, not when a password is accepted: with two factors those are different moments, and clearing on a correct password lets whoever holds one reset the wall on every attempt.
Everyone who uses the dashboard sets one up. The full reference — the two-step
sign-in, the grace period for the first admin, the encrypted secret, the
lost-phone reset and the host recovery commands — is
TWO-FACTOR.md.
Three things to know here, because they change what AUTH_MODE=enabled means:
TOTP_ENCRYPTION_KEYis required and the api refuses to boot without it. The gate shuts the dashboard to anyone without an authenticator, enrolment is the only way through it, and enrolment needs that key — so a missing one locks out every account at once.openssl rand -base64 32.POST /auth/sign-inno longer always opens a session. For an enrolled account it returns{ twoFactorRequired: true, challenge }and nothing else;POST /auth/2fa/verifyis what opens one. Anything driving the api directly — a script, a test, a runbook — has to do both steps.- An unenrolled session reaches three routes only (
/api/account/2fa/begin,/api/account/2fa/confirm,/api/account/me) and gets403 TWO_FACTOR_REQUIREDeverywhere else.
-
Email + password — always available in enabled mode. Verified api-side (
POST /auth/sign-in, bcrypt cost 12, enumeration-proof responses), which also opens the session row and returns its id. Accounts come from first-run setup or an invitation — there is no self-serve sign-up. -
Google / GitHub — each provider's button appears on the login page only when its
*_CLIENT_ID+*_CLIENT_SECRETpair is set. The web forwards the provider token to the api (POST /auth/oauth/:provider), which re-verifies it against the provider's own API (Google tokeninfo withaudpinning; GitHub/user+/user/emails) and resolves an existing account — by provider id, then by email, linking the provider. It never creates one; a new person redeems an invitation. Avatars are captured backfill-only — the first provider that supplies one wins. A refusal is recorded as a refused password sign-in is, with the reason:signin.failedfor an address with no account, a provider account with no verified address or a token the provider would not verify, andsignin.blockedfor a removed account. The Account page's Connected accounts card lists each provider the deployment offers as Linked or Not linked for the signed-in account (linkedProvidersonGET /api/account/me), and is absent when none is offered. Nothing there links or unlinks one.MAG-2729 puts social sign-in out of scope, on revocation grounds: a personal account outlives someone leaving the customer's company. Google and GitHub are offered by decision (2026-09-24) — removing a person from Team still ends every session they have, whatever they signed in with. Discord is not offered; its
discord_idcolumn is unwritten.
A provider's client lists the redirect URIs it will send a browser back to.
Google lists each one in full and takes no wildcard, so a dashboard that is
its own callback is a console edit at Google for every new hostname. Auth.js
has a built-in answer, the redirect proxy, and apps/auth-proxy is one:
a Cloudflare Worker running @auth/core at the version next-auth pins here,
at https://auth.magmadevs.com/api/auth.
Browser ── Continue with Google ──▶ dashboard.<t> (AUTH_REDIRECT_PROXY_URL set)
│ authorize URL with
│ redirect_uri = https://auth.magmadevs.com/api/auth/callback/google
│ state = signed(JWE, AUTH_SECRET) { origin: dashboard.<t>'s own callback, random }
▼
Google ── code + state ──▶ auth.magmadevs.com/api/auth/callback/google
│ decodes state with the SAME AUTH_SECRET
│ origin on dashboard.*.magmadevs.com? same provider? else 400
▼ 302
dashboard.<t>/api/auth/callback/google?code&state
│ state cookie + PKCE checked as always, code exchanged,
│ ID token to the api — unchanged from here on
- Nothing changes in the web.
next-authreadsAUTH_REDIRECT_PROXY_URLitself (setEnvDefaults), names the proxy's callback asredirect_uriand puts the dashboard's own callback instate. The chart renders the env fromdashboard.auth.oauth.redirectProxyUrl. - The proxy holds the shared
AUTH_SECRETand the providers' client ids, no client secret: it never exchanges a code. Beyond Auth.js's own behaviour it forwards only tohttps://dashboard.<tenant>.magmadevs.com/api/auth/callback/<the same provider>(CALLBACK_HOST_PATTERNin itswrangler.jsonc); anything else is a 400. - What it costs. Every dashboard behind the proxy signs with the same
AUTH_SECRET, and each holds the one client's id and secret. The api's session check is what keeps tenants apart: a token is asidthe api looks up in its ownsessionstable, so a cookie from one dashboard opens nothing on another whatever signed it.INTERNAL_AUTH_SECRETandTOTP_ENCRYPTION_KEYstay per deployment. - Built here, deployed by the fleet. Each release publishes the bundle,
auth-proxy-<VERSION>.jswith its sha256, on thev<VERSION>GitHub release (thepublish-auth-proxyjob ofbuild-and-push.yml). devops-magmadevs pins the pair in its tfvars, deploys the Worker through the Workers API, and owns the hostname, the route and the three secrets (AUTH_SECRET,GOOGLE_CLIENT_ID,GITHUB_CLIENT_ID): itsmake deploy-auth-proxyandmake set-auth-proxy-secret. Nothing in this repo deploys it, and this repo holds no Cloudflare credential. The fleet's tooling (smart-router-infrastructure,make set-dashboard-oauth PROXY=yes) puts a tenant behind it. - Tests (
apps/auth-proxy/src/__tests__/proxy.test.ts) run a dashboard's Auth.js sign-in start and this proxy's callback against each other with no mocks: the forward with the query intact, a state signed with another secret, a dashboard off the pattern, no state, a provider with no client id, and what the proxy logs (never the code or the state).
Sign-in, setup, forgot password, join (/invite/<token>) and reset
(/reset/<token>) are drawn without the dashboard's frame, inside
AuthScreen (components/auth/auth-screen.tsx). It applies the theme the top
bar's toggle saved (sr:theme in local storage) on mount, as the dashboard
does, so these pages are light or dark with it; with nothing saved they are
dark, the dashboard's default.
Their forms, and the Account page's Change password card, set noValidate and
check their own fields, so the browser draws no tooltip of its own. There is one
error style, red text: a field's error sits directly under that field, and an
error no field owns (the api refused, or could not be reached) sits directly
above the submit button, next to the action that produced it. Every field has a
visible label, and no password field has a placeholder.
On Join, the "Accept with Google" and "Accept with GitHub" buttons sit above the password form, divided from it by "or set a password".
With ADMIN_EMAIL + ADMIN_PASSWORD set and NODE_ENV not
production, seedAdmin runs at boot, idempotently: existing user with
that email → promoted to admin; empty users table → admin created;
populated table without that email → no-op.
In production it is refused, and a warning names the variables. It predates first-run setup and fails three lines of the ticket at once — it creates the first admin with no setup token, it sets a password for somebody, and it leaves a standing admin account in a customer's deployment for as long as the variables stay set. Both paths open on the same condition, no active users, so leaving it enabled gives the room two doors with a lock on one.
It stays for development because make dev-auth would otherwise need
somebody to walk through /setup after every down -v. make accounts
is the target that deliberately doesn't seed, and is the one to use for
exercising the real flow.
| Variable | Used by | Notes |
|---|---|---|
AUTH_MODE |
api + web | disabled (default) / enabled — must match on both |
AUTH_SECRET |
api + web | HS256 signing secret, must match. openssl rand -base64 32. The api refuses to boot on one under 32 characters or still a __NAME__ placeholder |
DATABASE_URL |
api | Empty in both compose files. make up-auth / make dev-auth supply postgres://sr:dev@postgres:5432/sr_dashboard; only read when AUTH_MODE=enabled |
DB_POOL_MAX |
api | Connections each api process holds to Postgres (default 20). Every authenticated request takes one for the session join, so it bounds a backend's concurrency and, summed over a deployment's backends, what the instance must admit. Refused unless a whole number ≥ 1 |
DB_IDLE_TIMEOUT_S |
api | Seconds an idle pooled connection is kept before it is closed (default 30); the next request pays for a new one. 0 keeps idle connections for the life of the process. Refused unless a whole number ≥ 0 |
DB_TLS_SERVERNAME |
api | The name the server's TLS certificate must carry when DATABASE_URL names a local proxy instead of the database (the fleet's cloudflared sidecar on 127.0.0.1, the TLS session ending on RDS). Set, TLS is on and the certificate must match this name whatever the URL's sslmode says; unset, the URL decides. Refused unless a DNS name — no scheme, port or IP address |
ADMIN_EMAIL / ADMIN_PASSWORD |
api | development-only admin seed; ignored (with a warning) when NODE_ENV=production |
INTERNAL_AUTH_SECRET |
api + web | Proves a caller is our own web tier, so the forwarded browser IP / User-Agent are honoured and the per-IP limit keys on the person. Required under AUTH_MODE=enabled — the api refuses to boot without it, because unset it fails silently: every session and access event records the api's own address |
TRUST_PROXY |
api | How far to believe X-Forwarded-For. Hop count (default 1), a comma list of proxy IPs/CIDRs, or false |
TRUST_PROXY_HOPS |
web | How many proxies sit in front of the web (default 1; the compose files, which publish the web directly, set 0). Picks the browser's entry out of X-Forwarded-For, counting from the right. 0 forwards no address at all |
DEPLOYMENT_MODE |
api + web | onprem (default) / managed — forks invite and reset delivery |
SETUP_TOKEN |
api | First-run token. Unset ⇒ generated once at boot and logged |
SETUP_TOKEN_FILE |
api | Where to write a generated token (mode 0600) so an init container can surface it |
PASSWORD_BREACH_CHECK |
api | hibp (default) / off — turn the breach check off deliberately on an air-gapped site |
PUBLIC_WEB_ORIGIN |
api | Browser-facing origin of the web app; invitation and reset links are built from it. No default in the api — guessing a host would produce links that look right and go nowhere, so POST /api/team/invites answers 500 without it. The compose files default it to the web's AUTH_URL, which is the same origin by definition |
AUTH_URL |
web | Auth.js base URL (default http://localhost:3000) |
INTERNAL_API_BASE_URL |
web | server-side api URL for Auth.js callbacks (http://api:8000 in compose) |
GOOGLE_CLIENT_ID / GOOGLE_CLIENT_SECRET |
web (+ id on api) | unset = no Google button. The api needs the id to pin the token audience |
AUTH_REDIRECT_PROXY_URL |
web | Auth.js's redirect proxy, the base URL of an Auth.js instance holding the same AUTH_SECRET (the fleet's: https://auth.magmadevs.com/api/auth, apps/auth-proxy). Set, every provider's redirect_uri is <it>/callback/<provider> and the dashboard's own callback rides in state; the provider's client lists the proxy's callback once for every dashboard. Unset = this dashboard is its own callback |
GITHUB_CLIENT_ID / GITHUB_CLIENT_SECRET |
web | unset = no GitHub button |
# dev stack with auth — supplies the dev secret, database URL and seed admin:
make dev-auth
# sign in at http://localhost:3000/login as admin@example.com / admin1234
# (override any of them: ADMIN_EMAIL=you@example.com make dev-auth)
# prod-style — no seeded admin (the seed is refused under NODE_ENV=production);
# the api refuses to boot without the last two:
export AUTH_SECRET=$(openssl rand -base64 32) \
TOTP_ENCRYPTION_KEY=$(openssl rand -base64 32) \
INTERNAL_AUTH_SECRET=$(openssl rand -base64 32)
make up-auth
# open /login → it redirects to /setup; the setup token is in
# `docker compose logs api` (or set SETUP_TOKEN, 16+ characters)
# a fresh install with NO accounts, for exercising the account system:
make accounts # on http://localhost:3000
make accounts-reset # wipe the database and start from first-run again
# EVERYTHING from scratch — router, metrics, logs, accounts and email, hot reload:
make e2e # managed mode, inbox at http://localhost:8005
make e2e MODE=onprem # on-prem mode, no email
make e2e-downmake e2e wipes the dev volumes on every run (the same ones make dev-auth
uses), then starts from first run like make accounts, with the router,
Prometheus (on :9091) and Loki/Grafana added so the metrics pages have data.
make accounts is the stack for exercising the account system. It differs from
make dev-auth in the one way that matters: dev-auth seeds
ADMIN_EMAIL/ADMIN_PASSWORD, so the deployment already has an account
and the first-run page can never appear. make accounts clears them,
supplies a setup token, and points invitation and reset links at
localhost:3000.
Dev credentials are deliberately guessable. The setup token is
installer-printed-this-token; in a real install it is printed by the
installer or read from SETUP_TOKEN_FILE.
AUTH_MODE=disabled is the default in both compose files, and every auth
and database variable beside it is empty — no DATABASE_URL, no
AUTH_SECRET, no seed admin. That is deliberate rather than tidy:
migrate()is reachable from exactly one place,plugins/db.ts, and that plugin is registered only inside theauthMode === "enabled"branch ofapp.ts. No plugin, no connection, and no migrations applied at all.- The
postgresservice sits behind theauthprofile, so a defaultdocker compose updoes not create it. - Nothing is left pointing at a database the stack is not using, and the dev stack no longer carries an administrator password for an account it is never going to create.
apps/api/src/__tests__/auth.test.ts pins this: with AUTH_MODE=disabled
and a DATABASE_URL deliberately set, the app has neither the db nor the
dbReady decorator. The values live in make up-auth / make dev-auth,
which is what turns the whole thing on.
Roughly ten minutes end to end. Each step below is a thing the ticket promises, in the order a real deployment meets them.
1. First run. Open http://localhost:3000. It redirects to /login,
which redirects to /setup — a deployment with no accounts has nobody to
sign in as. Create the first admin.
- Enter the wrong setup token first: refused. Without it, whoever reaches the URL between install and the operator sitting down becomes the admin.
- Try
correct horse battery stapleas the password: refused as breached (52,372,427 sightings). That is a live HaveIBeenPwned lookup, and the password never leaves the process — only the first five characters of its SHA-1 do. The check fails open, so on a machine with no egress it silently accepts everything; the honest setting there isPASSWORD_BREACH_CHECK=off, not a mystery timeout. - Then a real one. You land signed in, on the dashboard.
Note the header: "Set up 2FA - 30 days left". The first admin on a fresh install is the one account that may defer, and the countdown is not dismissible, because what it counts down to is the dashboard closing.
2. 2FA. Try Team → Invite first: refused, with "Set up 2FA before inviting anyone". The grace period ends the moment you hand somebody else access, and that refusal is the ending — there is no flag to write.
Account → 2FA → Set up. Scan the QR with Google Authenticator, or copy the key beside it into a password manager, then type the code back. The QR's tile shows a spinner until the api's answer lands, and Copy key turns to a tick and "Copied" once the key is on the clipboard (on a page served over plain http too, where the browser has no Clipboard API). The countdown disappears and the invite goes through.
Sign out and back in: the password now gets you a second screen asking for a code. Type a wrong one — it says "Invalid email or password", the same words as a wrong password, and sends you back to the start. It is not being coy: the challenge is spent before the code is checked, so there is genuinely nothing left to retry against, and that is what stops somebody grinding codes against one password.
3. Invite someone. Team → Invite. Pick a role; the description under each says what it can do today (a requester and an approver have read-only's access: see Roles).
- On-prem has no mail server, so the link is shown once and you copy it. Open it in a private window: the invited address is fixed text, not a field — the account is created with the invitation's address, so there is nothing there that could disagree with it.
- Accept it. They land on "2FA is required" — an invited person gets no grace period, and the only thing their session opens is enrolment. Set it up and the dashboard appears underneath, without another sign-in.
- That person is now in the members table, with Yes under 2FA. Not set up there is someone the dashboard is shut to until they set one up (they joined and have not enrolled, or an admin reset theirs), or the first admin inside their grace period. One that stays "Not set up" is the thing to stop on.
- Open the same link again: dead. Single-use.
4. Change a role. Team → ... on their row → Change role. The row shows the new role as soon as the api confirms it, with a confirmation above the table. It takes effect on whatever that person has open right now, not at their next sign-in — the api reads the role from the row on every request.
To watch that: sign in as them in a private window, leave the Team page open, demote them to Read-only from your window, and have them act. The admin-only controls stop working immediately.
5. Remove someone. Team → ... on their row → Remove. The dialog says what will happen, because "remove" reads like a deletion and this deliberately is not one. Their sessions die within one request, their name stays in the audit log, and their address can be invited again as a new account — try it.
6. Your own account. Account → Change password signs out your other
devices and keeps the one you are using. Active sessions lists every
device with what it is and where from; sign one out and watch it go.
About this deployment, at the bottom, is the build: its version, its commit
when the image recorded one (GIT_COMMIT), its runtime mode (the api's
NODE_ENV) only when that is not production, which every published image
runs as, and when the api started and its uptime.
Sign in from a second browser to see two sessions, then use "Sign out everywhere" — which signs out the tab you are in too, deliberately.
7. Password reset, on-prem. An admin never sets someone else's password — they generate a link, and only the holder chooses the value. Team → ... on a member's row → Reset link. It asks first — a new link also kills any the member already holds — then shows the link once, with a copy button.
Twenty-four hours on-prem against a managed deployment's one, because the link travels over a channel we don't control. Open it, set a password — and note that it does not sign you in, and that it kills every session that account had.
Two refusals worth seeing: a Google-only account answers 409 naming why there is no password to reset, and a removed member answers 404.
8. Lockout. Five wrong passwords for the same address and the sixth
attempt is refused — 423, even when that sixth one is right. The window
closes fifteen minutes after the first wrong password, not the fifth,
so hammering it doesn't extend the ban. A successful sign-in clears the
slate, or somebody who mistyped four times would spend the rest of the
window one slip from a lockout.
Failed codes land in the same counter, at the same five in fifteen — so four wrong passwords and one wrong code is a lockout. One wall in front of the account, not one per factor.
The count is keyed on the address whether or not an account exists, so a
lockout reveals nothing about who is a member — and a sign-in attempt
against an unknown address answers the same 401 a wrong password does.
9. Export. Team → Export CSV. This is the artifact an auditor asks for
first, and it is the whole member list, not the page you are looking at.
The 2FA column reads Not set up in the table when someone has no
authenticator yet, and the CSV's two_factor column reads yes or no. The
dashboard is shut to someone without one until they set it up
(TWO-FACTOR.md).
10. The audit log. Every step above wrote a row. Open Audit log in
the sidebar: newest first, a detail sheet per row, and Export CSV
(AUDIT.md). Or read the table itself:
docker exec smart-router-dashboard-dev-postgres-1 \
psql -U sr -d sr_dashboard -c \
"select occurred_at, action, actor_name, target_name, ip, client
from audit_events order by occurred_at desc limit 20"Note what is and isn't there: sign-ins carry an address and a device,
people-events don't — except invite.redeemed, which the ticket asks to
carry the address it was redeemed from — and no token, link or password
appears anywhere.
11. Lost phone. Team → ... on that member's row → Reset 2FA. Their sessions end
immediately and their key is destroyed rather than disabled — there is
nothing to restore and nothing you could have read. They sign in with
their password and meet the enrolment screen again. The log carries a
2fa.reset row naming both of you.
12. When nobody can get in. From the host, not the browser:
make recover CMD="reset-2fa --email you@example.com"
make recover CMD="reset-password --email you@example.com"
make recover CMD="promote-admin --email you@example.com"Shell access is the authorisation and these hand out nothing new — what
they add is a host.recovery row per run, naming the command and the
operator, so a recovery shows up in the log afterwards: on the Audit log
page, filtered to the recovery group, or in the table:
select occurred_at, actor_name, note from audit_events
where action = 'host.recovery' order by occurred_at;reset-password prints a link and never sets a password. Full reference:
TWO-FACTOR.md.
Four cumulative roles, defined once in
packages/shared/src/constants/roles.ts and shared by the web and the api
so they can't drift into disagreeing about who may do what:
| Role | See dashboard and audit | Propose changes | Approve others' | Manage people |
|---|---|---|---|---|
read_only |
yes | no | no | no |
requester |
yes | yes | no | no |
approver |
yes | yes | yes | no |
admin |
yes | yes | yes | yes |
roleAtLeast(role, minimum) is the only comparison; an unrecognised
role is unprivileged, so a row written by a newer build during a rolling
deploy fails safe rather than open. No config-change flow uses the
proposing and approving columns yet (MAG-2731), so a requester or an
approver has read-only's access, and the invite, change-role and join
screens describe both as "Same access as Read-only for now." This layer
defines the vocabulary and gates people-management.
The web uses the same helper to decide which controls to render. That is cosmetic only: hiding a button is not a permission check, and the api re-reads the live row on every request regardless.
The Team page lists everyone with access and exports it as CSV — the artifact an access review asks for first. Every role can read it, because a review only some people can see is not one; only an admin changes it.
- A role change ends no session. The gate reads the role from the row on every request, so a demotion lands on whatever the person has open. The Team page takes the caller's own admin controls from that row too (through the member list, polled every 30 seconds), not from the role in their token. Changing an admin to any other role revokes what they handed out as one (unredeemed invitations, unused reset links and audit tokens), with a row each, in the same transaction as the change.
- Removal is a state change, in one transaction. Status becomes
removed, the provider ids are cleared,signed_out_all_atis stamped, every live session is revoked, any pending invitation to their address is revoked, and so is everything they handed out as an admin: invitations they sent, reset links they generated and audit tokens they created. The row stays, so the audit log keeps their name. The partial unique index on email and the cleared provider ids let the same person be invited back as a new account, Google login included. Each change writes its audit row in the same transaction, so a change the log can't record doesn't happen. - There is always an admin. An admin can't demote or remove themselves. Each write locks the caller's and the target's rows and re-checks that the caller is still an admin, so two admins acting on each other at once can't both succeed. A sole admin sees a prompt to add a second one — a prompt, never a refusal, because admin has to stay transferable.
- The export neutralises formula leads. A field starting with
=,+,-,@, a tab, CR or LF gets a leading apostrophe: display names are chosen by the people in the list, and the file opens in a spreadsheet. It starts with a UTF-8 byte-order mark, without which Excel reads it in the system code page, and line endings are CRLF (RFC 4180). - 2FA reads Yes or Not set up. "Not set up" is amber, not red: it asks for attention and is not an error. Its tooltip says "Can't use the dashboard until they set it up", because they joined and have not enrolled, or an admin reset theirs. The exception is the first admin inside their grace period: inviting needs 2FA, so nobody has joined yet to read their row, and on their own row the tooltip counts the days left instead. One that stays "Not set up" is the thing a reviewer should stop on.
- Each row's actions are one "..." menu: Change role, Reset link, Reset 2FA and Remove, the same four on every row, so a row is as wide at 1024 px as at full width. Reset 2FA is disabled, with the reason, for someone with nothing to clear. The menu follows the ARIA menu pattern: arrows, Home and End move, Escape closes it and returns focus to the button, a click outside closes it. It stays with its button when the page scrolls, and closes once the button is off screen.
- A change shows at once. After Change role, Reset 2FA or Remove, the row takes the api's confirmed answer straight away and the list is read again; a confirmation above the table says what happened, and for a 2FA reset on managed, that the member was emailed.
- The Invites tab counts pending invitations, and lists only those until "Show revoked and expired" is ticked. States read Pending, Expired and Revoked, in an outlined chip that no role uses. A pending or expired invitation offers Resend (a new link and a new expiry; the old link stops working) and Revoke, which asks first.
- Each role has one colour,
ROLE_COLORSinpackages/shared/src/constants/roles.ts, drawn byRoleBadgeon the Team page, in the invite and change-role dialogs and on the join page. None is red, which is for errors and destructive actions.
{ sub: userId, email, role, sid, iat, exp }HS256, 30-day TTL, iss: smart-router-dashboard-web,
aud: smart-router-dashboard-api (enforced on both sides so no other
HS256 token signed with the same secret can pose as a session).
role is advisory — it is what the role was at issue time, kept so
the web can render affordances without a round-trip. Authorisation always
reads the live row.
sid is the load-bearing claim: it names a row in sessions, and a token
without one is refused outright, since nothing about it could be checked
or revoked.
Drizzle decides what to apply from one number, and it is worth knowing exactly which, because both failure modes report success.
packages/db migrations run on api boot. The migrator reads the single
highest created_at from __drizzle_migrations once, before the loop,
then applies every entry whose when is strictly greater. It writes a
hash column and never compares it.
Two consequences:
- An edited migration is never re-applied. The hash is recorded but unused, so changing an already-applied file is a no-op on any database that ran it. A change to the schema is always a new migration.
- A migration inserted below the high-water mark is skipped, on any
database that is already migrated. This is the one that bites, because
parallel branches produce it naturally: two tickets each add a migration,
and the one that ends up with the lower
whenis invisible to anybody who already ran the other.
The account and audit work met it on the way to main. The audit migration
is 0004_audit (when 1787126400000), after main's
0003_password_lifecycle (1787040000000) and before 0005_magma_account
(1788048000000). On the stack branches it was 0002_audit, with the same
when as the invitations migration — so a database built from those
branches holds a history main's journal does not describe. Depending on how
far it got, 0004_audit either re-runs there (CREATE TYPE against a type
that exists, and boot fails) or is silently skipped.
# The fix, and the only one — re-migrate from empty:
docker compose -f docker-compose.dev.yml --profile auth down -vOnly a database that ran a build from those branches is affected. CI is not: every suite builds its database from empty, where the high-water mark does not exist and entries apply in array order regardless of their timestamps.
Never change the
whenof a migration a database may already hold. It is the obvious repair and it trades a silent skip for a hard failure: on a database that ran the migration, a raised stamp is greater than the mark again, so it re-runs —CREATE TYPEagainst a type that already exists, and boot fails. Tested, not reasoned: applying0000–0002, bumping the entry, and re-migrating throws.A stamp is safe to set only before anything outside a branch has run it — which is why the audit migration could be renumbered while it existed on the stack branches alone, and why, once a migration is on
main, the answer is always a new migration and never a new timestamp.
The general form, worth asking of anything before calling it verified: what does this look like on a machine that already has state? Every suite here builds from empty, so a green run says nothing about an existing database — and this is the third failure in this work that was invisible exactly where it would be looked for. The audit log dropped rows for most real browsers while every test passed, because a Mac Chrome User-Agent fits in 128 characters and an iPhone's does not. The audit cursor's ordering hazard passes every single-writer test because it needs two overlapping transactions to appear. And this one passes every fresh-database migration.
Every authenticated request resolves sid to a session joined to its
account, and refuses the request if any of these hold:
| Condition, in the order checked | Response |
|---|---|
| No session row | 401 · SESSION_INVALID |
Account status is suspended or removed |
403 · ACCOUNT_INACTIVE |
revoked_at set, or past expires_at |
401 · SESSION_INVALID |
Token iat at or before users.signed_out_all_at |
401 · SESSION_INVALID |
| Database not reachable yet | 503 · AUTH_UNAVAILABLE |
The account comes before the session because removal revokes every session: the other way round, a removed person would only ever be told to sign in again.
The codes are machine-readable so the web can tell "sign in again" from
"you are not allowed" and stop rather than looping through the edge gate.
The web acts on exactly three of them — 401 SESSION_INVALID, 401 AUTH_REQUIRED on a request that carried a token, and 403 ACCOUNT_INACTIVE —
by signing the browser out and going to /login, so a device revoked or
removed from somewhere else stops looking signed in. A route's own 401 (a wrong
current password), a role 403 FORBIDDEN, and a 503 never sign anyone out.
When an admin's act ended the session, the refusal also carries endedBy: "admin": every ACCOUNT_INACTIVE (a removal), and a SESSION_INVALID whose
row was revoked as member_removed or admin (a two-factor reset, or the host's
recovery command). The web then goes to /login?reason=access_changed, and the
sign-in page says "Your session ended. An admin changed your access." The page
reads only the reasons lib/sign-in-notice.ts lists, each fixed text, and a
sign-in failure itself stays generic. The holder's own sign-out, a password
change or reset, and an expiry carry no endedBy. A role change ends no
session: the role is read from the row on every request, so a demotion lands on
the session in flight and its next refused action answers 403 FORBIDDEN.
Two revocation mechanisms, both needed. They do different jobs:
-
users.signed_out_all_at— a cutoff compared to the token'siat. Kills every outstanding token in one write without enumerating anything. Stamped on a password reset, sign-out-everywhere, and removal. Not on your own password change, which revokes your other devices one by one so the tab you changed it in stays signed in. The comparison is<=, not<: both sides have one-second resolution, so a token minted in the same second as the revocation must lose, or an attacker racing the sign-out keeps a live session.iatis the sign-in time and never moves. The web re-signs the token on every session read, so stamping "now" each time would let any tab that reloads carry itself past the cutoff — and this is the lever that reaches tokens no session row is held for, which is exactly the case where nothing else would catch it.decodecarriesiatthrough and both encode paths re-stamp the same value. -
sessions.revoked_at— kills one device. What makes the sessions list and "sign out this device" possible.
Signing out closes the api session too. Auth.js only clears its cookie,
so its events.signOut calls POST /auth/sign-out with a Bearer for the
session that cookie addressed. The device leaves the sessions list, and the
log gets its signout row. It is best effort, with a 3-second timeout: the
cookie is cleared regardless, so an api that is down cannot keep anybody
signed in.
Every session that ends gets a row. The holder signing out is signout.
Anything else is one session.revoked per session, naming why: revoked
from the sessions list, signing out everywhere (the other devices; the one it
was done from is signout), a removal, a password reset, a two-factor reset,
or a password change (for the other devices).
Session rows are never deleted on revoke — a revoked session is evidence, and the audit log's access events reference it. Nor are they pruned: there is no ageing job. How long to keep a session row is the same question as how long to keep an access event, which MAG-2770 owns and has deliberately left open; a team's sign-ins are a few rows a month, so growth is not what forces the answer.
There is deliberately no cache on the lookup. A cache is precisely what would turn "revoked" into "revoked eventually", and the same request already makes multi-second Prometheus round-trips, so one indexed join is not the expensive part of anything.
Session rows carry the IP, the raw User-Agent, and a parsed client
string ("Chrome 141 / macOS"). Getting these right needs care, because
the api never sees the browser on the sign-in path: Auth.js calls
/auth/sign-in from the web container, so request.ip there is the web
pod and the User-Agent is undici's.
So authorize(credentials, request) reads the browser's own address and
User-Agent from its request and forwards them as X-Forwarded-Client-Ip
and X-Forwarded-Client-Ua — and the api believes them only when the
caller also presents INTERNAL_AUTH_SECRET. The route is public, so
without that check anyone could pin any address to their own sign-in
attempts and write a false trail. Unset ⇒ forwarded context is always
ignored and the api records what it observes. The same holds on the other
routes Auth.js calls to open a session: /auth/2fa/verify,
/auth/oauth/:provider, and /auth/invite/accept when an invitation is
redeemed with Google or GitHub — which also writes a signin.succeeded
row for the session it opens.
Headers, not a body field. The api's per-IP limiter on /auth/* runs
in onRequest, before a body exists, and it keys on this same address.
Read it any later and every sign-in in the deployment shares one bucket of
ten a minute, which two-factor roughly doubles the cost of — a team
signing in together would lock each other out of the code screen.
Which entry of X-Forwarded-For is the browser. Counted from the
right, TRUST_PROXY_HOPS places back (default 1). Never the left-most:
most ingresses append rather than replace, so the left of that header is
whatever the caller sent, and reading it hands the choice of recorded
address to the person being recorded. Set it to the number of proxies in
front of the web, and keep it consistent with the api's TRUST_PROXY. A
chain shorter than the hop count reports nothing, and the api falls back
to what it observes.
0 when nothing sits in front of the web — the compose files publish
it directly and set 0. Next writes X-Forwarded-For from the socket only
when the request did not carry one, so with no proxy every entry is the
browser's own, and 0 forwards no address at all rather than one the
browser chose. The device is still forwarded: the api records the web's
address beside the browser's own device. Behind an ingress, set it to the
number of proxies.
The server-rendered previews (/invite/<token>, /reset/<token>) forward
the same headers, so their per-IP limit counts visitors rather than the web
pod.
The (app) and standalone layouts' read of /api/account/me, which decides
the two-factor gate before the page is drawn, is vouched for too. On routes
without a limit of their own, the api's per-minute limits (RATE_LIMIT_MAX
and, with accounts on, a second one of 100) key a vouched call on the
session it carries, then on the forwarded address, and only then on the
connection (clientRateLimitKey in services/forwarded-client.ts). The
session comes first because the api resolved it from its own table on this
request, while the forwarded address depends on TRUST_PROXY_HOPS: 0
forwards none, and a count set too low names a proxy for everybody. Without a
vouched key that read put every signed-in person in the web pod's bucket, one
read per page load. A caller that cannot present the secret keys on its
connection whatever it forwards.
Both values are the caller's to write, so both are cut to what their
columns take before any insert: a browser version longer than four
digits is dropped from the device string, and an address inet would
refuse is not recorded. A value the column refused would otherwise fail
the insert — and a standalone audit write swallows its failure, so the
row would vanish without a trace. The audit writer applies the same rule
again, for any caller that skips it.
Routes the browser calls directly never accept forwarded context;
they read request.ip themselves. The rule is that whichever party
terminated the browser's connection is the one that reports it.
Related: TRUST_PROXY decides how far X-Forwarded-For is believed when
deriving request.ip. It defaults to 1 (the immediate peer). It used to
be unconditionally "trust every hop", which on a publicly reachable api
lets any caller claim any address — and so walk straight past the per-IP
rate limit.
@sr/db/testing exposes createTestDb(): a real Postgres (pglite, WASM,
in-process) with every migration applied, no Docker and no service
container. Used by the DB-backed api tests.
Every instance loads from a snapshot of the migrated data dir that the helper
builds once and keeps under packages/db/node_modules/.cache/pglite-template/,
keyed by the migrations folder and the installed pglite — a new migration is a
cache miss, so the snapshot is never stale. Delete that directory to force a
rebuild.
Within a test file the instance is shared: the first call opens it, every
later call truncates every table (sequences restart) and hands it back, and
closeSharedTestDb() — called from each package's vitest setup file — frees
it once the file is done. A caller that passes onQuery gets a private
instance.
This matters because the behaviour the schema leans on hardest is exactly
what a hand-rolled fake cannot reproduce — the partial unique index on
lower(email), conditional single-use updates whose correctness depends
on a real rowcount, and cascade-on-delete.
Where pglite is not enough. It is a real Postgres, but it is reached through a different driver, and the drivers do not agree about parameter serialisation. A bare JS
Dateinterpolated into asqltemplate works under pglite and throws under postgres-js (ERR_INVALID_ARG_TYPE: Received an instance of Date) — so a green test suite is not proof the production driver is happy.Prefer computing values in SQL (
now(),make_interval(...)) over interpolating JS values into raw templates: it sidesteps the divergence, and for anything time-based it is more correct anyway, since the app and the database can disagree about the clock.






