Customer Authentication, Registration Guard & Session Security
Strict separation between customer Better Auth and staff_accounts, disposable email and DoH MX registration guards, Turnstile verification, and CSRF/session protection.
Slloy enforces a strict cryptographic and schema boundary between public customers (users, user_password_credentials, user_oauth_identities, managed via Better Auth + slloy-public JWTs) and internal staff (staff_accounts, staff_audit_log, managed via slloy-admin JWTs).
1. Customer Auth vs. Staff Identity Separation
Introduced in migration 0004_identity_auth_separation.sql (server/src/betterAuth.ts, server/src/authTokens.ts, and server/POSTGRES.md):
| Dimension | Public Customers (slloy-public) | Internal Staff (slloy-admin) |
|---|---|---|
| Database Tables | users, user_password_credentials, user_oauth_identities | staff_accounts, staff_login_attempts, staff_audit_log |
| Authentication Methods | Better Auth Email OTP (6-digit verification code via Resend), Password credentials (user_password_credentials), and Google OAuth (user_oauth_identities) | Dedicated username + bcrypt password (>= 12 chars) via POST /api/admin/login (plus Cloudflare Access edge gate) |
| Signing Secret | BETTER_AUTH_SECRET (>= 32 chars) | ADMIN_JWT_SECRET (independent secret) |
JWT aud Claim | "slloy-public" | "slloy-admin" |
| Revocation Mechanism | Session deletion / user status = 'banned' | Incrementing staff_accounts.token_version immediately invalidates all active tokens for that staff member |
Key Identity Invariants
- Zero Cross-Domain Login: A public user token (
slloy-public) is rejected by/api/admin/*, and a staff account instaff_accountshas no credit balance, orders, or public login credentials. - Google OAuth Matching by
(provider, provider_subject)Only:- Google OAuth identities match strictly on
(provider = 'google', provider_subject = google_sub). - Contact email is never used to auto-merge an unverified password account with a Google login (preventing account takeover via pre-registered email addresses).
- Historical Google-only users were never backfilled into
user_password_credentials, preventing placeholder hashes from locking users out if OAuth is unlinked.
- Google OAuth identities match strictly on
- Referential Integrity (
ON DELETE RESTRICT):- All foreign keys referencing
users.id(orders,generations,credit_buckets,credit_ledger,subscriptions,payment_disputes) useON DELETE RESTRICTso financial, generation, and audit histories can never be cascade-deleted. - Pre-deploy verification script
server/scripts/audit-user-integrity.tschecks for credentialless users, negative credit balances, and orphaned references (emitting only aggregate counts, zero PII).
- All foreign keys referencing
2. Registration Defense Pipeline (server/src/registrationGuard.ts)
Because every new account receives a 100-credit signup bonus, registration and email OTP issuance are protected by a 3-layer defense pipeline wired into Better Auth's before and user.create.after hooks:
flowchart LR
A["Signup / Send OTP Request"] --> B["1. Cloudflare Turnstile (Fail-Closed)"]
B --> C["2. Static + Dynamic Domain Blocklist (Exact & Subdomain)"]
C --> D["3. Cloudflare DoH DNS MX Check (Fail-Open on DNS Timeout)"]
D --> E["Issue OTP / Create Account (+100 Credits)"]Layer 1: Cloudflare Turnstile (verifyTurnstile — Fail-Closed)
- Verifies the client token against
https://challenges.cloudflare.com/turnstile/v0/siteverify(5,000 mstimeout) passingremoteipextracted fromcf-connecting-ip(or firstx-forwarded-forentry). - Fail-Closed Policy: When
TURNSTILE_SECRET_KEYis configured, any missing token, invalid response, or network timeout to the Turnstile verify endpoint returnsfalseand blocks registration. (WhenTURNSTILE_SECRET_KEYis empty in local dev, verification passes through).
Layer 2: Disposable & Abusive Email Domain Blocklist (isBlockedEmailDomain)
- Checks the lowercase domain after the last
@(emailDomain(email)) against two sources:- Built-in Static Blocklist (
config.blockedEmailDomains): Known disposable/temp-mail providers. - Operator Dynamic Blocklist (
blocked_email_domainstable): Domains manually blocked by operators in/admin(POST /api/admin/blocked-domains).
- Built-in Static Blocklist (
- Subdomain Matching: Blocking
proxyvpn.cnautomatically blocks bothuser@proxyvpn.cnanduser@a.proxyvpn.cn(domain === key || domain.endsWith("." + key)). - Cross-Isolate Synchronization: In Cloudflare Workers,
loadDynamicBlockedDomains(repo)queriesblocked_email_domainson demand during OTP/signup and refreshes the in-memorySetevery5minutes viaSWEEP_CRON. Matches throwHTTP 400 EMAIL_DOMAIN_BLOCKED.
Layer 3: DNS-over-HTTPS MX Record Verification (assertReceivableEmail — Fail-Open)
- Because Cloudflare Workers do not provide
node:dns,consultMxViaDoh(domain)queries Cloudflare's RFC 8484 JSON DoH endpoint (https://cloudflare-dns.com/dns-query?name=<domain>&type=MXwithAccept: application/dns-json,5,000 mstimeout). - Rejection Criteria:
Status === 3(NXDOMAIN), or- No
Answerrecord withtype === 15(MX), or - Null MX (
RFC 7505, where exchange data ends with.). - Confirmed non-receivable domains are cached for
1hour (MX_TTL_MS = 3,600,000) and rejected withHTTP 400 EMAIL_DOMAIN_UNREACHABLE.
- Fail-Open on Network/DoH Errors: If the DoH HTTP request times out or returns non-200 (
consulted === null), the result is not cached andhasReceivableMailboxreturnstrueso transient DNS hiccups never block legitimate users.
3. CSRF, Headers & Session Security
Implemented across server/src/http/middleware/csrf.ts, headers.ts, csp.ts, bodyLimit.ts, and jsonGuard.ts:
- Origin / Sec-Fetch-Site CSRF Guard (
csrf.ts): State-changing requests (POST,PUT,PATCH,DELETE) carrying cookie sessions must match the configured site origin (config.publicUrl) viaOrigin/Referer/Sec-Fetch-Sitechecks. - Strict Security Headers (
headers.ts&csp.ts):- Sends
Strict-Transport-Security: max-age=31536000onslloy.com(omitted on staging/local so staging subdomain certs are not pinned by HSTS). - Enforces
X-Content-Type-Options: nosniff,X-Frame-Options: DENY,Referrer-Policy: strict-origin-when-cross-origin, and Content-Security-Policy (csp.ts).
- Sends
- Body Size & JSON Guards (
bodyLimit.ts&jsonGuard.ts): Caps request payload sizes before buffering to protect Worker isolate memory (128 MB).
URL Migration & 301 Redirect Policy
Engineering governance for Slloy's 882 table-driven legacy 301 redirects, 8 mandatory URL rules, 90-day shape cooldown, and post-deploy verification.
Admin SPA, 3-Tier RBAC, Cost Accounting & Moderation
Architecture of the /admin SPA, 3-tier staff RBAC, DB-backed login rate limiting, paidCny vs. estimateCny financial reporting, prompt batch ops, and share privacy.