ADR-WEB-3. Auth data model, Better Auth configuration and invite-only sign-up
Source:
docs/decisions/ADR-WEB-3-auth-and-link-data-model.md. Generated at build time; edit the source file.
Date: 2026-11-21. Status: accepted. Implements M4 Task 17, which also took over Task 2’s auth schema (controller ruling). Builds on ADR 0005 (Better Auth), ADR 0033 (SQL migrations own the schema) and ADR 0041 (private beta; docs/decisions/0041-private-beta-owner-and-friends.md, on r1/base).
Context
Section titled “Context”The web app needs users, sessions, OAuth accounts and magic-link tokens. The plan put these in a Drizzle-generated migration (Task 2). Since then, ADR 0033 made db/migrations/ (plain SQL, applied by sqlx) the only source of the schema. The web app’s Drizzle schema is now generated from it. Task 2 was never built, so Task 17 adds the auth tables itself.
Decision
Section titled “Decision”Tables
Section titled “Tables”- One SQL migration,
db/migrations/20261121010000_web_auth.sql. The web range starts after R1’s reserved20261121000000–20261121009999. It creates the Better Auth 1.7 core tablesuser,session,accountandverification, plusinvitesandmagic_link_sends(the per-address throttle). Column names are the snake_case form of Better Auth’s field names. The generated Drizzle schema maps them back to the camelCase keys the drizzle adapter writes. - uuid ids everywhere (
gen_random_uuid()defaults,advanced.database.generateId: "uuid"), becauselinked_accounts.user_idis already a uuid. sessionandaccountcascade on user delete. The under-13 deletion in Task 20 relies on this.usercarries the age and privacy columns. These arebirth_month(YYYY-MM, with a CHECK on the format),age_checked_at, andmarketing_emailandpublic_share_default, both default false. They are Better AuthadditionalFieldswithinput: false, so no client can set them through the auth API.user.emailis lower-case (CHECK), like Better Auth writes it.account (provider_id, account_id)is unique and has an index onuser_id.verification.identifieris indexed.- Out of this migration: the
account_linksandchesscom_verificationstables from Task 2’s plan. They belong to Task 19, which adds them as its own migration. - The schema is regenerated with
scripts/db/generate-drizzle-schema.sh, so the drift check stays clean.@ci/dbre-exportsuser,session,account,verificationandinvitesfrom the generated schema. Task 27 later moves the whole main export over to it.
Migrations for the web test database
Section titled “Migrations for the web test database”runMigrations(db, dir?) (in @ci/db) applies db/migrations/*.sql in version order, all in one transaction, under an advisory lock.
- It uses sqlx’s own bookkeeping: the same
_sqlx_migrationsDDL, a SHA-384 checksum of the file, and the description with_turned into spaces. A database migrated by it is therefore accepted bydb::MIGRATOR, and the other way round. - A file that changed after it was applied is an error, as in sqlx.
- Known differences from sqlx (acceptable for a test-database tool):
- all pending migrations run in one transaction, where sqlx uses one per migration;
- there is no support for
-- no-transactionmigrations or for reversible (down) migrations; - it takes its own advisory lock, not sqlx’s, so a concurrent sqlx run against the same database is not excluded;
execution_timeis measured around the statement only.
- The web tests use it on
chess_web_test(WEB_DATABASE_URL_TEST, guarded byassertSafeTestDatabase). Dev and production databases are still migrated by the backend.
Better Auth (1.7.24, the repo’s existing pin)
Section titled “Better Auth (1.7.24, the repo’s existing pin)”The auth instance is built lazily by getAuth(), so importing the module during next build needs no environment. It is configured as follows:
| Setting | Value |
|---|---|
| Adapter | drizzle, provider pg |
advanced.cookiePrefix |
ci: the cookie is ci.session_token over http and __Secure-ci.session_token over https |
advanced.useSecureCookies |
follows BETTER_AUTH_URL; in production an http base URL is refused unless the host is local |
advanced.disableOriginCheck, disableCSRFCheck |
explicitly false: Better Auth skips both under NODE_ENV=test, so the tests would otherwise not exercise them |
account.encryptOAuthTokens |
true (the option exists in 1.7, so no hand-rolled AES) |
account.accountLinking |
{ enabled: true, trustedProviders: ["google"] } |
| Plugins | magicLink({ expiresIn: 600, storeToken: "hashed" }), genericOAuth (Lichess and chess.com OAuth stubs until Tasks 18 and 19) |
configured only when both GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET are set |
- Rate limiting is on in every environment, with the custom rule
/sign-in/magic-linkat 3 per 600 s per client IP.- The client IP comes only from trusted proxies. Next route handlers do not expose the socket address. So
advanced.ipAddressreadsIP_ADDRESS_HEADERS(defaultx-forwarded-for) only whenTRUSTED_PROXIES(CIDRs) is set, walking the header from the right past the trusted hops. With no proxy configured, no header is read and all clients share one bucket per path (127.0.0.1 in dev and test), so a forgedX-Forwarded-Fornever buys a fresh bucket. - A per-email throttle sits on top: at most 3 links sent per address per 600 s, whatever the IP.
- Sends are recorded in
magic_link_sends. Counting, pruning old rows and recording happen in one transaction under a per-address advisory lock (pg_advisory_xact_lock(7262013, hashtext(email))). - So a burst of N concurrent requests sends exactly min(N, 3) links.
- A throttled request records nothing, so it never extends the lockout.
- A recorded send whose SMTP delivery then fails still counts.
- Sends are recorded in
- The header shape behind a proxy is
<whatever the client sent>, <address the proxy saw>. Better Auth walks it from the right, skippingTRUSTED_PROXIES, so forged left-hand entries are ignored. - Blocker on friend access: the app may be reachable only through a trusted reverse proxy or tunnel that sets
X-Forwarded-For.TRUSTED_PROXIESis the compose network CIDR.- web’s port is not published (the opt-in
docker-compose.ports.ymlmapping is for local use only). - Without that, a client that can reach web directly can write its own
X-Forwarded-For. - Until then, local-only use with no proxy is accepted: the shared bucket (review ruling).
- It uses the in-memory store, which is enough for the single-process private beta.
- A multi-instance deployment needs Redis
secondaryStorage(deferred with the rest of launch hardening).
- The client IP comes only from trusted proxies. Next route handlers do not expose the socket address. So
/api/auth/*error redirects are mapped to the sign-in messages that Task 21 renders.- A used, expired or unknown magic link goes to
/sign-in?error=link_expired. - An uninvited address goes to
/sign-in?error=not_invited, from any sign-in method. - The mapping lives in
mapAuthResponse, not inhooks.ts, which belongs to Task 20.
- A used, expired or unknown magic link goes to
- The schema check replaces the CLI.
@better-auth/clistops at 1.4.x, sopnpm dlx @better-auth/cli@1.7.27 generatecannot run (and 1.7.27 is also under 7 days old). Instead,test/auth/schema.test.tscompares Better Auth’s owngetSchema(auth.options)with the generated tables: every field must be present and required fields must be NOT NULL. The same check runs on every test run rather than once.
Addendum: invite-only sign-up for the private beta (ADR 0041)
Section titled “Addendum: invite-only sign-up for the private beta (ADR 0041)”INVITE_ONLYis on by default. It is off only when set to exactly"0", the opposite of the other flags, so a missing setting fails closed.- With it on, an address may sign in or sign up only when it appears in
INVITE_ALLOWLIST(comma-separated, case-insensitive) or in theinvitestable (emails stored lower-cased; CHECK enforced). - With it off, sign-up is open again with no other change.
- With it on, an address may sign in or sign up only when it appears in
- Magic link.
sendMagicLinkonly queues the delivery (runAfterResponse: at most 100 queued or running, extras dropped with a logged warning and a counter, at most 4 running at once; under test,flushBackgroundTasks()rethrows task errors). The invite check, the per-email throttle and the SMTP send all run after the response. The endpoint answers200 { status: true }on the same code path for every address, so neither the body nor the timing reveals invites or accounts. Mail goes to the normalised address. The person who isn’t invited simply gets no mail. - Addresses are normalised with NFKC, trimmed and lower-cased. Anything that is not printable ASCII afterwards never matches an invite, so look-alike characters cannot.
- New accounts from any method (magic link, Google, generic OAuth) are gated by
user.validateUserInfooncreate-user. A rejection redirects witherror=not_invited. - OAuth needs a provider-verified email. For email-asserting providers (Google),
validateUserInforejects anything butemailVerified === true(error=email_not_verified). This applies tocreate-userand to implicitlink-account, where a sign-in is linked to the account with the same email.- Why: Google is a trusted linking provider, and that skips Better Auth’s own verified-email check. Without this rule, a Google account that merely claims an invited address could link itself to that account.
- Exempt:
link-accountstarted from a live session of the same user (linkOAuthAccount), where the session, not the email, grants trust. - Exempt: providers that do not assert email (
lichess,chesscom;NON_EMAIL_PROVIDERS). Their linking is not gated on email. UnderINVITE_ONLYtheir email cannot prove an invite, so they cannot create accounts. Task 18 revisits this for Lichess sign-in.
- Returning users are gated by a
session.create.beforeguard (composed arounddb-hooks.ts, which stays Task 18’s file). A user whose invite was withdrawn gets no new session.- Linking a provider to an already signed-in user is not invite-gated, because the user is already admitted (it still needs a verified email).
- Withdrawing an invite signs the person out. Deleting an
invitesrow, or changing its email, deletes the sessions of the old address (triggerinvites_revoke_sessions). The guard then refuses new ones.- TRUNCATE is not covered: row triggers do not fire on it.
INVITE_ONLYandINVITE_ALLOWLISTare read at start-up, so changing them needs a restart.- Removing an address from
INVITE_ALLOWLISTdoes not delete its sessions; delete them by hand.
- The message is neutral.
not_invitedsays only that this address cannot sign in yet, never whether an account exists. Suggested copy for Task 21: “This email can’t sign in yet. chess-improver is invite-only for now.” - Inviting someone, for now:
- add the address to
INVITE_ALLOWLISTin.env, or - run
insert into invites (email, note) values ('friend@example.com', 'beta').
- add the address to
- Invite codes are not built. They need a sign-in field (Task 21) and only matter for public growth.
Left out (public launch, deferred by ADR 0041)
Section titled “Left out (public launch, deferred by ADR 0041)”Public sign-up flows (codes, waitlist, invite emails), a shared rate-limit store, a durable mail queue (today a send lost to a crash is not retried), and production domain hardening.
Consequences
Section titled “Consequences”- Turning
INVITE_ONLYoff restores open sign-up with no code change, and both modes are tested. - Adding a web table means writing a new SQL migration with a version after
20261121010000, then rerunning the generator. createTestSession(db, overrides?)(inapps/web/test/helpers/session.ts) inserts a user and a session directly and returns a signedci.session_tokencookie.- It defaults to an adult who has answered the age screen. Pass
{ birthMonth: null }for a fresh account. webTestDb()points the app’sDATABASE_URLatchess_web_test, so routes under test use it.
- It defaults to an adult who has answered the age screen. Pass