Skip to Content
Slloy Docs
Auth, Admin & Security

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):

DimensionPublic Customers (slloy-public)Internal Staff (slloy-admin)
Database Tablesusers, user_password_credentials, user_oauth_identitiesstaff_accounts, staff_login_attempts, staff_audit_log
Authentication MethodsBetter 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 SecretBETTER_AUTH_SECRET (>= 32 chars)ADMIN_JWT_SECRET (independent secret)
JWT aud Claim"slloy-public""slloy-admin"
Revocation MechanismSession deletion / user status = 'banned'Incrementing staff_accounts.token_version immediately invalidates all active tokens for that staff member

Key Identity Invariants

  1. Zero Cross-Domain Login: A public user token (slloy-public) is rejected by /api/admin/*, and a staff account in staff_accounts has no credit balance, orders, or public login credentials.
  2. 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.
  3. Referential Integrity (ON DELETE RESTRICT):
    • All foreign keys referencing users.id (orders, generations, credit_buckets, credit_ledger, subscriptions, payment_disputes) use ON DELETE RESTRICT so financial, generation, and audit histories can never be cascade-deleted.
    • Pre-deploy verification script server/scripts/audit-user-integrity.ts checks for credentialless users, negative credit balances, and orphaned references (emitting only aggregate counts, zero PII).

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 ms timeout) passing remoteip extracted from cf-connecting-ip (or first x-forwarded-for entry).
  • Fail-Closed Policy: When TURNSTILE_SECRET_KEY is configured, any missing token, invalid response, or network timeout to the Turnstile verify endpoint returns false and blocks registration. (When TURNSTILE_SECRET_KEY is 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:
    1. Built-in Static Blocklist (config.blockedEmailDomains): Known disposable/temp-mail providers.
    2. Operator Dynamic Blocklist (blocked_email_domains table): Domains manually blocked by operators in /admin (POST /api/admin/blocked-domains).
  • Subdomain Matching: Blocking proxyvpn.cn automatically blocks both user@proxyvpn.cn and user@a.proxyvpn.cn (domain === key || domain.endsWith("." + key)).
  • Cross-Isolate Synchronization: In Cloudflare Workers, loadDynamicBlockedDomains(repo) queries blocked_email_domains on demand during OTP/signup and refreshes the in-memory Set every 5 minutes via SWEEP_CRON. Matches throw HTTP 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=MX with Accept: application/dns-json, 5,000 ms timeout).
  • Rejection Criteria:
    • Status === 3 (NXDOMAIN), or
    • No Answer record with type === 15 (MX), or
    • Null MX (RFC 7505, where exchange data ends with .).
    • Confirmed non-receivable domains are cached for 1 hour (MX_TTL_MS = 3,600,000) and rejected with HTTP 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 and hasReceivableMailbox returns true so 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) via Origin / Referer / Sec-Fetch-Site checks.
  • Strict Security Headers (headers.ts & csp.ts):
    • Sends Strict-Transport-Security: max-age=31536000 on slloy.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).
  • Body Size & JSON Guards (bodyLimit.ts & jsonGuard.ts): Caps request payload sizes before buffering to protect Worker isolate memory (128 MB).

On this page