Why this matters
Small businesses lose control of their ad accounts in two everyday ways: handing a Meta or Google password to an agency in a chat thread, or letting a stolen browser session spend money and add an attacker's login method before the owner notices. This product eliminates passwords across sign-in, marketer delegation, and ad-account connections, then puts strict cookie rules, fresh step-up checks, and time-bound grants behind every workspace route. Understanding this flow lets an owner trace a request from an e-mail link all the way to an encrypted ad-account connection and know exactly what a stolen cookie can and cannot do.
In plain words
The ideas
Authentication versus authorization, and why there are no passwords
Two words sound alike yet answer completely different questions:
- Authentication asks who is calling? If a request carries no valid token, or its session expired or was revoked, the server answers HTTP
401 Unauthorized. - Authorization asks what may this identified caller do in this workspace? If Selin is signed in as a
viewerand tries to approve a budget change, the server knows who she is and refuses with HTTP403 Forbidden.
This product enforces zero-password access across all three surfaces: user sign-in, marketer access, and connected ad platforms. Under ADR-0010 (OD-14), human users authenticate solely through passwordless sign-in — a single-use e-mail link or a passkey. There is no password column on public.users, no password reset flow to hijack, no SMS one-time code to SIM-swap, and no social sign-in in Release 1. Early design records had penciled in the Better Auth library, but OD-14 chose to persist the repository's own session and MFA manager inside PostgreSQL's auth schema to avoid external dependencies and fit our FORCE RLS model — on the hard condition of an external security review before the first outside user signs in.
The e-mail sign-in link step by step
A careless e-mail sign-in link leaks who is a customer, exposes its secret in server logs, and signs in whoever opens a forwarded message. This repository's sign-in link flow closes each of those holes step by step:
1. Browser POSTs e-mail --> POST /v1/auth/login/start
- Rejects non-ASCII addresses (blocks Turkish İ/ı casing mismatches)
- Always answers 202 with identical timing, body, headers, and store work
for known and unknown addresses (defeats account enumeration)
- Sets HttpOnly __Host-gd_login_nonce cookie (10 min) on this browser
- Stores ONLY SHA-256(email), SHA-256(token), SHA-256(nonce), plus e-mail
sealed under an HKDF key derived from the raw token (never stored)
2. Mail arrives with link: https://<origin>/auth/complete#t=<256-bit token>
- Token lives in the URL fragment (#t=), never in ?query= or HTTP logs
3. Browser opens /auth/complete, reads #t= client-side, strips the hash,
and POSTs { token } + __Host-gd_login_nonce --> POST /v1/auth/login/complete
- Single atomic UPDATE ... WHERE consumed_at IS NULL AND attempts < 5
AND expires_at > GREATEST(p_now, now()) RETURNING email_sealed, locale
- First verified e-mail auto-creates the user (ON CONFLICT DO NOTHING)
- Issues server-side session + sets __Host-gd_session & __Host-gd_signed_in=1Putting the token in the URL fragment (#t=...) keeps it out of web server access logs, proxy logs, and outgoing Referer headers because browsers never transmit fragments over HTTP. Pairing the link with the sign-in nonce cookie (__Host-gd_login_nonce) means forwarding the e-mail to another browser fails instead of signing the wrong person in; after five failed nonce attempts the link dies permanently.
Passkeys in plain words
Right after first sign-in and workspace onboarding, the product offers a passkey built on the WebAuthn standard. A passkey is a cryptographic key pair: the private key stays locked inside the owner's phone, laptop, or hardware security key and never leaves it, while PostgreSQL stores only the public key and credential metadata in auth.passkey_credentials.
Four pieces make passkeys immune to look-alike phishing sites and database leaks:
- Fresh challenge: for every sign-in or step-up ceremony, the server generates a single-use 32-byte random nonce (5-minute TTL for sign-in) and consumes it atomically on first use so captured signatures cannot be replayed.
- Origin and relying party ID (
rpId): the browser checks the real domain name in the address bar and passesrpIdinto the authenticator's signed data. A fake phishing domain cannot trigger the real passkey, and the server verifies bothexpectedOriginandexpectedRpId. - Discoverable user handle and user verification (
UV): a discoverable passkey identifies the account without typing an e-mail address, and sign-in requires both User Presence (UP, a physical touch) and User Verification (UV, a PIN, fingerprint, or face scan) so a stolen unlocked USB key cannot sign in alone. - Signature counter (
signCount): hardware authenticators increment an internal counter on each signature. Whenever either the stored or observed counter is non-zero, the verifier insists the counter strictly increases and aborts onPASSKEY_SIGN_COUNT_REGRESSION, exposing cloned keys.
Server-stored sessions, cookie attributes, and the origin guard
Every browser sign-in creates a durable server-side session in auth.sessions (described in Lesson 03 under the same zero-table-privilege SECURITY DEFINER model as the vault). Only SHA-256(token) is stored alongside actor_kind, mfa_level, 12-hour sliding idle expiry, 30-day hard absolute expiry, revoked_at, and HMAC fingerprints of user agent and IP prefix. Keeping sessions on the server means signing out, clicking sign-out-everywhere, or suspending an account kills the session immediately on the very next request — unlike stateless JWTs that stay valid until expiry.
The browser carries that opaque 256-bit secret in the session cookie (__Host-gd_session). Every single attribute stops a distinct attack:
| Attribute | Rule enforced by browser | Attack it stops |
|---|---|---|
__Host- prefix | Requires Secure, Path=/, and no Domain | Subdomain cookie fixation and cross-host leaking |
Secure | Sent over encrypted HTTPS connections only | Plaintext network eavesdropping |
HttpOnly | Hidden from JavaScript (document.cookie) | Session theft if injected script (XSS) runs on a page |
SameSite=Lax | Withheld on cross-site POSTs; kept on top-level GET links | Cross-site request forgery (CSRF) while keeping OAuth redirects working |
Because HttpOnly hides __Host-gd_session from page scripts, the web app also receives a companion signed-in hint cookie (__Host-gd_signed_in=1, not HttpOnly, carrying zero user or token data). The web reads it solely to know a live cookie session exists; the API never reads it for authorization.
Browsers attach cookies automatically on requests, so SameSite=Lax is backed by a server-side CSRF origin guard on every state-changing route (POST, PUT, PATCH, DELETE): any request authenticated by a cookie (rather than an API client's Authorization: Bearer header) must carry an Origin header matching an allowed web origin and the custom header X-GD-Request: 1 (which a cross-site HTML form cannot set without triggering a CORS preflight). Otherwise the server responds 403 ORIGIN_REJECTED. After MFA enrolment or step-up, the server performs session rotation on cookie sessions so any earlier copy of the cookie stops working immediately.
Warning
Step-up MFA for binding actions
What can a thief do if they somehow steal a live session cookie? They can view read-only pages until idle expiry or rotation, but they cannot connect an ad account, delete the workspace, release a safeguarded payment, approve an above-threshold budget or tracking change, or silently replace the owner's MFA device.
Every high-stakes operation requires step-up MFA: a fresh verification within the last 10 minutes using either a passkey or an authenticator app TOTP code (RFC 6238, 6 digits, 30-second window). Passing step-up mints a single-use HMAC-signed step-up token (X-Step-Up-MFA-Token) bound strictly to userId, sessionId, workspaceId, operation, verifiedAt (rejecting timestamps older than 10 minutes or more than 30 seconds in the future), and a single-use nonce.
Two extra defenses protect TOTP specifically:
- Replay prevention (
last_used_step): verifying a code advancesauth.totp_enrolments.last_used_stepatomically so a 6-digit code accepted once can never be replayed inside the same 30-second window. - Shared lockout: after 5 consecutive bad, malformed, or replayed TOTP attempts,
auth.mfa_throttlelocks verification with429 MFA_LOCKEDand aRetry-Afterheader — 5 minutes at first, doubling on further lockouts up to 1 hour, resetting only after a valid code succeeds.
Once a user has any active MFA factor, enrolling a new TOTP secret or adding another passkey itself requires fresh step-up from an existing factor (403 MFA_REENROLL_REQUIRES_STEPUP), and a replacement TOTP secret waits in a pending slot until confirmed so abandoning setup never breaks the active factor.
Roles, time-bound marketer grants, and one-click revoke
Inside each workspace (/w/:workspaceId/...), dual-role role-based access control separates permanent team members from external hired specialists:
- Permanent team (workspace roles in
workspace_memberships):owner: full custody — billing, members, marketer grants, OAuth connect and revoke, approval decisions and execution, safeguarded payment release, and workspace deletion.admin: daily operations — workspace updates, OAuth connect, CRM writes, SEO audits, and proposing changes; cannot manage billing, members, grants, OAuth revocation, or workspace deletion.analyst: metrics, CRM deals, SEO audits, and proposing ad changes; cannot decide approvals or connect accounts.viewer: read-only inspection across reports, approvals, and diagnostics.
- Outside specialists (marketer grants in
marketer_grants): time-bound (starts_attoexpires_at), tied to afundedoractiveengagement, carrying only a subset of six grantable scopes (ads:read,ads:propose_change,tracking:read_diagnostics,seo:run_audit,crm:read_funnel_metrics, and opt-incrm:read_contacts). Rawcrm_contactsPII is denied by default at both TypeScript and PostgreSQL RLS unlesscrm:read_contactsis explicitly granted.
Eight forbidden scopes can never appear on a marketer grant — enforced identically in TypeScript and PostgreSQL CHECK: oauth:connect, oauth:connect_or_export, oauth:export_token, crm:export_pii, billing:manage, members:manage, ads:execute_without_approval, and workspace:delete. Three of those (oauth:export_token, oauth:connect_or_export, ads:execute_without_approval) are universally forbidden even to workspace owners.
Ending a marketer's access uses one-click grant revocation: stamping revoked_at closes PostgreSQL RLS immediately, cancels every pending approval authored by that grant, and leaves every ad account, pixel, and CRM record untouched in the SMB's workspace. To prevent side-door leaks (where a record hidden in the UI still leaks through search, CSV export, direct URL, or AI retrieval), every read and write passes through one unified ACL covering all eight channels (ui, direct_link, report, association, search, export, api, ai_retrieval), where vault.* is unconditionally denied and ai_retrieval is strictly read-only with zero raw PII.
OAuth 2.0 for ad accounts, pending selections, and account ownership
OAuth 2.0 connects a workspace's Meta Ads or Google Ads account without passwords and without transferring account ownership (R1, N1). Only an owner or admin carrying a fresh oauth_connect step-up token can start the authorization code flow:
1. Owner/Admin + fresh step-up --> POST /v1/w/:ws/connections/oauth/:provider/start
- Stores SHA-256(state) + sealed PKCE verifier (10-min TTL) in vault.oauth_authorization_states
- Returns official authorize URL (https://www.facebook.com or https://accounts.google.com)
2. Owner approves scopes directly on Meta / Google
- Provider redirects browser to GET /v1/oauth/:provider/callback?code=...&state=...
3. Callback consumes state atomically (single use, same signed-in user, unexpired),
re-checks owner/admin role, and exchanges code server-to-server:
- Google Ads sends PKCE code_verifier (S256) + requires adwords + datamanager scopes
- Meta Ads uses confidential client_secret + appsecret_proof + state
(Meta offers PKCE only on its OIDC variant, not standard Marketing API OAuth)
- Lists ad accounts:
* 1 account --> encrypts tokens directly into vault.oauth_connections
* 2+ accounts --> seals tokens into vault.oauth_pending_selections for <= 10 min (OD-21)
- Redirects browser (302) to /settings/connections with status flag only (never tokens/codes)Two safeguards keep connected accounts safe over time. First, the pending selection table (OD-21) is the sole documented exception to tokens living only in vault.oauth_connections: it holds sealed tokens for at most 10 minutes, deletes the row atomically the moment the owner picks an account, and is purged hourly by auth.oauth_purge_expired_flows(). Second, tokens are refreshed in the background by the separate least-privilege dispatch process (never the general worker, which holds zero vault credentials), and disconnecting an account (oauth:revoke, owner-only) calls the provider's revoke endpoint and overwrites all four encrypted columns in vault.oauth_connections regardless of what the provider answers.
Note
How this repository does it
Every rule in this lesson maps to concrete modules in this checkout:
- Decision record and migrations:
ADR-0010recordsOD-14. Migrations0006_auth_durable_sessions_and_mfa.sql(sessions, TOTP slots, passkey credentials, step-up challenges, shared TOTP throttle),0007_auth_login_challenges.sql(e-mail link challenges, passkey login challenges,find_or_create_user_by_email,create_first_workspace),0008_oauth_authorization_states.sql(vault.oauth_authorization_statesandvault.oauth_pending_selections),0010_auth_kek_rotation_and_user_erasure.sql, and0011_oauth_flow_purge.sqlkeep all auth and OAuth-flow tables inaccessible to{product}_appdirectly (42501), exposing onlySECURITY DEFINERfunctions with pinnedsearch_path. - Sign-in, cookies, and origin guard:
routes.tsservesPOST /v1/auth/login/start,POST /v1/auth/login/complete, passkey sign-in, onboarding, and sign-out-everywhere;cookies.tsserializes__Host-gd_session,__Host-gd_login_nonce, and__Host-gd_signed_in;origin-guard.tsenforces exactOriginplusX-GD-Request: 1on cookie mutations;session-token.tsis the API's single token extractor (Bearer, then__Host-gd_session, then legacygd_session). - Passkeys, TOTP, and step-up:
passkey-verifier.tscheckswebauthn.get, origin,rpIdHash,UP,UV, signature, and monotonicsignCount;session-and-mfa.tsimplements TOTP verification,last_used_step, the 5-failure lockout, stagedpendingre-enrolment, and cookie session rotation behind theAuthStoreport (auth-store-pg.ts);mfa-stepup.tsdefines step-up operations, 10-minute freshness, and HMAC step-up tokens. - Dual-role RBAC and unified ACL:
grants-rbac.tsmirrors PostgreSQL'sapp_has_workspace_access,app_has_workspace_scope, four member roles, six grantable scopes, and eight banned marketer scopes;unified-acl.tsapplies one gate across all eight channels (ACCESS_CHANNELS). - OAuth connect and revoke:
routes.tsandrevoke.tsdrive the connect, 10-minute selection, and crypto-shredding revoke flows viameta.ts,google.ts, andpkce.ts.
Not built yet
What went wrong once
Restart amnesia and unthrottled 6-digit TOTP codes
Before Wave 45 and Wave 46, every session, TOTP secret, passkey credential, and challenge lived in JavaScript Map objects inside one API process, and TOTP had zero failed-attempt lockout (findings P-4, P-6, and C-1 in INDEPENDENT-REVIEW-2026-12-02.md). With 3 valid 6-digit codes per 30-second window, a fast client could brute-force TOTP — and worse, restarting the API wiped every MFA enrolment, letting a session thief re-enrol without proof. Wave 45 added the 5-failure doubling lockout (5m to 60m), and Wave 46 moved all state behind an AuthStore port into PostgreSQL's auth schema (0006 + 0007), proving with a 14-case shared contract suite and a 15-check real-browser test that sessions and MFA survive an API restart and that 8 concurrent bad TOTP guesses produce exactly one lockout.
A stolen session replacing MFA, and an async refusal silently swallowed
Originally, any signed-in session could overwrite an enrolled TOTP secret or add a new passkey without fresh step-up proof (finding P-11). Wave 45 closed that with 403 MFA_REENROLL_REQUIRES_STEPUP and staged pending TOTP promotion. One wave later, while making refuseFactorChangeWithoutProof async for PostgreSQL storage, the helper returned Fastify's reply object from an async function. Because Fastify's reply is thenable (has a .then method), await unwrapped it to undefined, causing the caller to carry on and register a passkey despite the 403. Seven regression tests written in Wave 45 caught the silent failure immediately; changing the guard to return a plain boolean fixed it permanently.
Warning
Real signed-in users landing on sample data and fabricated revoke receipts
When Wave 46 introduced the HttpOnly __Host-gd_session cookie, dozens of web helpers still checked sessionToken === null to decide whether someone was signed in. Because scripts cannot read an HttpOnly cookie, real signed-in users saw stamped sample data, and worse, some error paths — including revokeMarketerGrantLiveOrFallback — returned a fabricated "revoked" receipt when the API was unreachable or refused. Introducing the non-secret __Host-gd_signed_in=1 hint cookie and unifying all 11 screen families around hasLiveWorkspaceSession in Wave 47 guaranteed that real signed-in users always see live data and honest failure states.
Try it yourself
These read-only checks inspect live authentication, RBAC, and OAuth files directly without touching running servers, database ports, or external providers.
Step 1: Verify cookie hardening and CSRF origin rules
Read cookies.ts and origin-guard.ts. Confirm that serializeHostCookie always emits Path=/, SameSite=Lax, Secure (by default), and HttpOnly (except for __Host-gd_signed_in=1), and that isCookieMutationAllowed requires both an allowed Origin and x-gd-request equal to '1' on every non-GET/HEAD/OPTIONS cookie request.
Step 2: Trace the single session-token extractor
Open session-token.ts and trace extractSessionToken: verify it reads Authorization: Bearer first, __Host-gd_session second, and legacy gd_session last, rejecting empty values or control characters.
Step 3: Verify 1:1 parity between TypeScript and PostgreSQL banned marketer scopes
Run this read-only Node snippet from the repository root to compare BANNED_MARKETER_SCOPES in grants-rbac.ts against the marketer_grants CHECK constraint in schema.sql:
node -e "const fs=require('fs'); const ts=fs.readFileSync('packages/auth/src/grants-rbac.ts','utf8').match(/BANNED_MARKETER_SCOPES = \[([\s\S]*?)\]/)[1].match(/'([^']+)'/g); const sql=fs.readFileSync('docs/schema.sql','utf8').match(/allowed_scopes && ARRAY\[([\s\S]*?)\]/)[1].match(/'([^']+)'/g); console.log({tsCount:ts.length,sqlCount:sql.length,exactMatch:JSON.stringify(ts)===JSON.stringify(sql),scopes:ts});"You should see tsCount: 8, sqlCount: 8, and exactMatch: true.
Step 4: Inspect auth schema privileges and 10-minute OAuth bounds
Read 0007_auth_login_challenges.sql, 0008_oauth_authorization_states.sql, and 0011_oauth_flow_purge.sql. Confirm that direct table access is revoked from PUBLIC and {product}_app, that login links, OAuth states, and pending selections all carry a database CHECK (expires_at <= created_at + interval '10 minutes'), and that auth.oauth_consume_pending_selection deletes the row atomically on use.
Check yourself
0 / 6Why does the e-mail sign-in link put its 256-bit token in #t=... and also require the __Host-gd_login_nonce cookie?
Why can a passkey created for this product not be stolen by tricking the owner into visiting a convincing look-alike phishing domain?
What can an attacker do — and NOT do — if they obtain a user's live __Host-gd_session cookie without the user's authenticator device?
Why does the web app receive __Host-gd_signed_in=1 in addition to __Host-gd_session?
An SMB owner clicks Yetkiyi kaldır (Revoke access) on a hired marketer's grant. What happens immediately?
Why did owner decision OD-21 add vault.oauth_pending_selections with a hard 10-minute lifetime and hourly purge?
Words to know
35Go deeper
- Architecture and decisions:
ADR-0010,ADR-0004,AGENTS.md(rules 6, 7, 10),OWNER-DECISIONS.md(OD-14,OD-21), andINDEPENDENT-REVIEW-2026-12-02.md(findings C-1, C-2, P-4, P-6, P-11). - Implementation files:
sign-in routes,cookies.ts,origin-guard.ts,passkey-verifier.ts,session-and-mfa.ts,grants-rbac.ts,unified-acl.ts,mfa-stepup.ts, andOAuth routes. - Archived lesson absorbed here:
archived lesson 26 on audit retention and agency delegation. - Official specifications: W3C WebAuthn Level 2, RFC 6749 OAuth 2.0, RFC 7636 PKCE, RFC 6238 TOTP, and MDN: Using HTTP Cookies.