GetClaps
Ücretsiz DenetimFiyatlandırmaSözlükAkademi
  1. Ana sayfa
  2. /Akademi
  3. /L04 · Identity and access: sign-in, sessions, passkeys, step-up, OAuth, roles

Ana sayfa / Akademi / L04 · Identity and access: sign-in, sessions, passkeys, step-up, OAuth, roles

L04Bölüm B · GüvenlikOrtaKod doğrulama tarihi: 2026-12-04

Identity and access: sign-in, sessions, passkeys, step-up, OAuth, roles

How passwordless sign-in, server-stored sessions, passkeys, step-up MFA, dual-role RBAC, and OAuth 2.0 protect accounts while keeping ownership with the business.

21 dk·4050 kelime·6 soru·35 terim·docs/lessons/04-identity-and-access.md
Ön koşul:L03 · Data: PostgreSQL, tenants, exact money, and doing things exactly once
Tüm derslere dön
●

Ders içerikleri İngilizce yayınlanır (OD-23)

Sayfa çerçevesi Türkçe ve İngilizce olarak sunulur. Teknik ders metinleri, kod örnekleri ve kendini sına soruları doğrudan ortak kaynak dosyalarından İngilizce okunur; hukuk ve ürün terimlerinde Türkçe karşılıklar yer alır.

0%
▲Yanıtlanan sorular
0 / 6
—
○Doğruluk oranı
Henüz yanıt yok

Bu dersteki bölümler

  1. 1.Why this matters
  2. 2.The ideas
  3. 3.How this repository does it
  4. 4.What went wrong once
  5. 5.Try it yourself
  6. 6.Check yourself
  7. 7.Words to know
  8. 8.Go deeper

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

prove who you are without passwords, verify a second device right before irreversible actions, and grant outside marketers narrow time-limited keys instead of handing over the shop.

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 viewer and tries to approve a budget change, the server knows who she is and refuses with HTTP 403 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:

text
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=1

Putting 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 passes rpId into the authenticator's signed data. A fake phishing domain cannot trigger the real passkey, and the server verifies both expectedOrigin and expectedRpId.
  • 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 on PASSKEY_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:

AttributeRule enforced by browserAttack it stops
__Host- prefixRequires Secure, Path=/, and no DomainSubdomain cookie fixation and cross-host leaking
SecureSent over encrypted HTTPS connections onlyPlaintext network eavesdropping
HttpOnlyHidden from JavaScript (document.cookie)Session theft if injected script (XSS) runs on a page
SameSite=LaxWithheld on cross-site POSTs; kept on top-level GET linksCross-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

because browsers never send a __Host- cookie across different origins, production must serve the web app and the API behind one shared origin (and set OAUTH_REDIRECT_BASE to match). A split web/API host signs nobody in.

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:

  1. Replay prevention (last_used_step): verifying a code advances auth.totp_enrolments.last_used_step atomically so a 6-digit code accepted once can never be replayed inside the same 30-second window.
  2. Shared lockout: after 5 consecutive bad, malformed, or replayed TOTP attempts, auth.mfa_throttle locks verification with 429 MFA_LOCKED and a Retry-After header — 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_at to expires_at), tied to a funded or active engagement, 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-in crm:read_contacts). Raw crm_contacts PII is denied by default at both TypeScript and PostgreSQL RLS unless crm:read_contacts is 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:

text
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 OAuth tokens and TOTP secrets are envelope-encrypted at rest (AES-256-GCM, DEKs, KEKs, and AAD binding) belongs to Lesson 05; broader web attack classes belong to Lesson 06.

How this repository does it

Every rule in this lesson maps to concrete modules in this checkout:

  • Decision record and migrations: ADR-0010 records OD-14. Migrations 0006_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_states and vault.oauth_pending_selections), 0010_auth_kek_rotation_and_user_erasure.sql, and 0011_oauth_flow_purge.sql keep all auth and OAuth-flow tables inaccessible to {product}_app directly (42501), exposing only SECURITY DEFINER functions with pinned search_path.
  • Sign-in, cookies, and origin guard: routes.ts serves POST /v1/auth/login/start, POST /v1/auth/login/complete, passkey sign-in, onboarding, and sign-out-everywhere; cookies.ts serializes __Host-gd_session, __Host-gd_login_nonce, and __Host-gd_signed_in; origin-guard.ts enforces exact Origin plus X-GD-Request: 1 on cookie mutations; session-token.ts is the API's single token extractor (Bearer, then __Host-gd_session, then legacy gd_session).
  • Passkeys, TOTP, and step-up: passkey-verifier.ts checks webauthn.get, origin, rpIdHash, UP, UV, signature, and monotonic signCount; session-and-mfa.ts implements TOTP verification, last_used_step, the 5-failure lockout, staged pending re-enrolment, and cookie session rotation behind the AuthStore port (auth-store-pg.ts); mfa-stepup.ts defines step-up operations, 10-minute freshness, and HMAC step-up tokens.
  • Dual-role RBAC and unified ACL: grants-rbac.ts mirrors PostgreSQL's app_has_workspace_access, app_has_workspace_scope, four member roles, six grantable scopes, and eight banned marketer scopes; unified-acl.ts applies one gate across all eight channels (ACCESS_CHANNELS).
  • OAuth connect and revoke: routes.ts and revoke.ts drive the connect, 10-minute selection, and crypto-shredding revoke flows via meta.ts, google.ts, and pkce.ts.
◆

Not built yet

five honest boundaries apply on this branch as of 2026-12-04. First, OD-14 (ADR-0010 section 6) requires an external security review of apps/api/src/auth/ (issue 96 / issue 97) before the first outside user signs in. Second, an account-recovery flow for a person who loses their only MFA device is not built yet (review finding P-6). Third, same-origin reverse-proxy wiring in production (required for __Host- cookies across web and API) is still an open deploy task. Fourth, the OAuth connect journey has been verified end-to-end in Chromium against a loopback fake provider that production refuses; a manual connect against real Meta and Google credentials is still owed. Fifth, sign-in rate-limit counters in apps/api/src/auth/sign-in/routes.ts are still per API process rather than shared in PostgreSQL.

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

never let a security refusal travel as an implicit side effect or thenable reply object; return an explicit boolean or typed refusal and keep regression tests running across every refactor.

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:

bash
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 / 6

Q1.Why does the e-mail sign-in link put its 256-bit token in #t=... and also require the __Host-gd_login_nonce cookie?

Q2.Why can a passkey created for this product not be stolen by tricking the owner into visiting a convincing look-alike phishing domain?

Q3.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?

Q4.Why does the web app receive __Host-gd_signed_in=1 in addition to __Host-gd_session?

Q5.An SMB owner clicks Yetkiyi kaldır (Revoke access) on a hired marketer's grant. What happens immediately?

Q6.Why did owner decision OD-21 add vault.oauth_pending_selections with a hard 10-minute lifetime and hourly purge?

Words to know

35
authenticationTR: kimlik doğrulama

Proving who a caller is — establishing their global user identity before deciding what they may touch.

Kimlik ve erişimSözlükte incele
authorizationTR: yetkilendirme

Deciding whether an already authenticated caller is allowed to perform a specific action in a specific workspace.

Kimlik ve erişimSözlükte incele
authorization code flow

The server-side OAuth 2.0 flow where the owner approves access on Meta or Google, returns with a one-time code, and the server exchanges it directly for tokens.

Kimlik ve erişimSözlükte incele
challenge

A fresh single-use 32-byte random nonce issued by the server that a passkey must sign so old assertions cannot be replayed.

Kimlik ve erişimSözlükte incele
forbidden scopeTR: hiçbir zaman verilmeyen yetkiler

A capability that can never be granted to a marketer (or to any API caller), blocked identically in TypeScript and PostgreSQL CHECK constraints.

Kimlik ve erişimSözlükte incele
grant revocationTR: yetkiyi kaldır

Immediately closing a marketer's workspace grant with one owner action and cancelling every pending proposal authored under that grant.

Kimlik ve erişimSözlükte incele
__Host- prefix

A browser-enforced cookie name prefix requiring Secure, Path=/, and no Domain attribute so only the exact host can set or receive it.

Kimlik ve erişimSözlükte incele
HttpOnly

A cookie flag that hides the cookie from JavaScript (document.cookie), stopping injected scripts from reading the session token.

Kimlik ve erişimSözlükte incele
lockout

Temporarily blocking TOTP verification (429 MFA_LOCKED with Retry-After) after 5 wrong codes in a row, starting at 5 minutes and doubling up to 1 hour.

Kimlik ve erişimSözlükte incele
marketer grantTR: kapsamlı yetki

Time-bound, revocable, least-privilege workspace access issued to an outside specialist tied to a funded or active engagement.

Kimlik ve erişimSözlükte incele
OAuth

The open authorization framework (RFC 6749) letting a business owner connect Meta Ads or Google Ads to the product without ever sharing their password.

Kimlik ve erişimSözlükte incele
OAuth state

A single-use 256-bit random parameter sent to the OAuth provider and matched on callback to stop login-CSRF account mix-ups.

Kimlik ve erişimSözlükte incele
passkeyTR: passkey

A phishing-resistant public-key sign-in credential kept on the user's phone, computer, or security key that works only on the exact site it was created for.

Kimlik ve erişimSözlükte incele
passwordless sign-inTR: şifresiz oturum açma

Signing in strictly through a single-use browser-bound e-mail link or a passkey, with zero passwords ever created, stored, or reset.

Kimlik ve erişimSözlükte incele
pending selection

A single-use sealed token set held in vault.oauth_pending_selections for at most 10 minutes while an owner chooses one ad account from several returned by OAuth.

Kimlik ve erişimSözlükte incele
PKCEPKCE

An OAuth 2.0 extension (RFC 7636) that binds an authorization code to a server-held random verifier via its SHA-256 challenge (S256).

Kimlik ve erişimSözlükte incele
relying party IDrpId

The exact domain name (rpId) a passkey is cryptographically bound to, checked by both browser and server to defeat phishing.

Kimlik ve erişimSözlükte incele
role-based access controlRBAC

Authorizing actions based on structured roles (owner, admin, analyst, viewer) for staff paired with time-bound scoped grants for outside marketers.

Kimlik ve erişimSözlükte incele
SameSite

A cookie attribute (SameSite=Lax) instructing browsers not to attach the cookie to cross-site POSTs or background requests while still sending it on top-level link clicks.

Kimlik ve erişimSözlükte incele
sessionTR: oturum

A server-stored record in auth.sessions representing one signed-in device with sliding idle expiry, absolute expiry, and instant revocation.

Kimlik ve erişimSözlükte incele
session cookie

The browser's secret session cookie (__Host-gd_session), hardened with __Host-, HttpOnly, Secure, Path=/, and SameSite=Lax.

Kimlik ve erişimSözlükte incele
session rotation

Atomically swapping a cookie session's token hash for a brand-new random token after security-elevating events so any old copy stops working.

Kimlik ve erişimSözlükte incele
sign-in linkTR: oturum açma bağlantısı

A single-use, 10-minute e-mail link carrying its 256-bit token in the URL fragment (#t=...) and bound to the requesting browser's nonce cookie.

Kimlik ve erişimSözlükte incele
sign-in nonce cookie

A 10-minute HttpOnly __Host-gd_login_nonce cookie tying an e-mail sign-in link strictly to the exact browser that requested it.

Kimlik ve erişimSözlükte incele
signature counter

A monotonic counter inside WebAuthn authenticatorData that increases on every use so a cloned hardware passkey reveals itself.

Kimlik ve erişimSözlükte incele
signed-in hint cookie

A non-secret, script-readable cookie (__Host-gd_signed_in=1) that tells the web UI a session exists without exposing the HttpOnly session token.

Kimlik ve erişimSözlükte incele
step-up MFATR: iki adımlı onay

Requiring a fresh TOTP or passkey verification within the last 10 minutes right before a binding, high-impact action.

Kimlik ve erişimSözlükte incele
step-up token

A short-lived, single-use HMAC-signed proof (X-Step-Up-MFA-Token, max 10 minutes) bound to one user, session, workspace, and operation.

Kimlik ve erişimSözlükte incele
TOTPTOTP

Time-Based One-Time Password (RFC 6238), the 6-digit code an authenticator app derives every 30 seconds from a shared secret.

Kimlik ve erişimSözlükte incele
unified ACL

One shared authorization gate applied identically across all eight access channels (ui, direct_link, report, association, search, export, api, ai_retrieval).

Kimlik ve erişimSözlükte incele
URL fragment

The #... tail of a URL, which browsers keep strictly client-side and never send in HTTP requests, proxy logs, or Referer headers.

Kimlik ve erişimSözlükte incele
user verification

Bit 2 (UV) in WebAuthn authenticatorData, proving the device locally verified the user via PIN, fingerprint, or face scan.

Kimlik ve erişimSözlükte incele
WebAuthn

The W3C and FIDO2 browser standard for passwordless, origin-bound public-key authentication using passkeys.

Kimlik ve erişimSözlükte incele
workspace roleTR: rol

One of the four permanent team levels inside a workspace (owner, admin, analyst, viewer), strictly separate from outside marketer grants.

Kimlik ve erişimSözlükte incele
zero-password access

The foundational architecture rule that nobody ever creates, stores, or shares a password — for user sign-in, marketer delegation, or ad accounts.

Kimlik ve erişimSözlükte incele

Go deeper

  • Architecture and decisions: ADR-0010, ADR-0004, AGENTS.md (rules 6, 7, 10), OWNER-DECISIONS.md (OD-14, OD-21), and INDEPENDENT-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, and OAuth 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.
◆

NOT LEGAL OR TAX ADVICE · Açık karar kapıları dürüstlüğü

Bu müfredat öğrenme amaçlıdır; hukuk veya vergi danışmanlığı değildir. #3 hukuk ve mali müşavir onayı, #21 keşif görüşmeleri, OD-01 marka tescil kontrolü ve canlı dağıtım henüz tamamlanmamıştır. ISO-27001 / SOC 2: UNOBTAINED. Sıfır canlı müşteri veya canlı reklam harcaması iddia edilmez.

Önceki ders: L03Sonraki ders: L05

L04 · Part B · intermediate · Verified 2026-12-04 · 21 min

Identity and access: sign-in, sessions, passkeys, step-up, OAuth, roles

How passwordless sign-in, server-stored sessions, passkeys, step-up MFA, dual-role RBAC, and OAuth 2.0 protect accounts while keeping ownership with the business.

Bu müfredat öğrenme amaçlıdır; hukuk veya vergi danışmanlığı değildir. #3 hukuk ve mali müşavir onayı, #21 keşif görüşmeleri, OD-01 marka tescil kontrolü ve canlı dağıtım henüz tamamlanmamıştır. ISO-27001 / SOC 2: UNOBTAINED. Sıfır canlı müşteri veya canlı reklam harcaması iddia edilmez.

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

prove who you are without passwords, verify a second device right before irreversible actions, and grant outside marketers narrow time-limited keys instead of handing over the shop.

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 viewer and tries to approve a budget change, the server knows who she is and refuses with HTTP 403 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=1

Putting 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 passes rpId into the authenticator's signed data. A fake phishing domain cannot trigger the real passkey, and the server verifies both expectedOrigin and expectedRpId.
  • 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 on PASSKEY_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:

AttributeRule enforced by browserAttack it stops
__Host- prefixRequires Secure, Path=/, and no DomainSubdomain cookie fixation and cross-host leaking
SecureSent over encrypted HTTPS connections onlyPlaintext network eavesdropping
HttpOnlyHidden from JavaScript (document.cookie)Session theft if injected script (XSS) runs on a page
SameSite=LaxWithheld on cross-site POSTs; kept on top-level GET linksCross-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

because browsers never send a __Host- cookie across different origins, production must serve the web app and the API behind one shared origin (and set OAUTH_REDIRECT_BASE to match). A split web/API host signs nobody in.

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:

  1. Replay prevention (last_used_step): verifying a code advances auth.totp_enrolments.last_used_step atomically so a 6-digit code accepted once can never be replayed inside the same 30-second window.
  2. Shared lockout: after 5 consecutive bad, malformed, or replayed TOTP attempts, auth.mfa_throttle locks verification with 429 MFA_LOCKED and a Retry-After header — 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_at to expires_at), tied to a funded or active engagement, 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-in crm:read_contacts). Raw crm_contacts PII is denied by default at both TypeScript and PostgreSQL RLS unless crm:read_contacts is 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 OAuth tokens and TOTP secrets are envelope-encrypted at rest (AES-256-GCM, DEKs, KEKs, and AAD binding) belongs to Lesson 05; broader web attack classes belong to Lesson 06.

How this repository does it

Every rule in this lesson maps to concrete modules in this checkout:

  • Decision record and migrations: ADR-0010 records OD-14. Migrations 0006_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_states and vault.oauth_pending_selections), 0010_auth_kek_rotation_and_user_erasure.sql, and 0011_oauth_flow_purge.sql keep all auth and OAuth-flow tables inaccessible to {product}_app directly (42501), exposing only SECURITY DEFINER functions with pinned search_path.
  • Sign-in, cookies, and origin guard: routes.ts serves POST /v1/auth/login/start, POST /v1/auth/login/complete, passkey sign-in, onboarding, and sign-out-everywhere; cookies.ts serializes __Host-gd_session, __Host-gd_login_nonce, and __Host-gd_signed_in; origin-guard.ts enforces exact Origin plus X-GD-Request: 1 on cookie mutations; session-token.ts is the API's single token extractor (Bearer, then __Host-gd_session, then legacy gd_session).
  • Passkeys, TOTP, and step-up: passkey-verifier.ts checks webauthn.get, origin, rpIdHash, UP, UV, signature, and monotonic signCount; session-and-mfa.ts implements TOTP verification, last_used_step, the 5-failure lockout, staged pending re-enrolment, and cookie session rotation behind the AuthStore port (auth-store-pg.ts); mfa-stepup.ts defines step-up operations, 10-minute freshness, and HMAC step-up tokens.
  • Dual-role RBAC and unified ACL: grants-rbac.ts mirrors PostgreSQL's app_has_workspace_access, app_has_workspace_scope, four member roles, six grantable scopes, and eight banned marketer scopes; unified-acl.ts applies one gate across all eight channels (ACCESS_CHANNELS).
  • OAuth connect and revoke: routes.ts and revoke.ts drive the connect, 10-minute selection, and crypto-shredding revoke flows via meta.ts, google.ts, and pkce.ts.
◆

Not built yet

five honest boundaries apply on this branch as of 2026-12-04. First, OD-14 (ADR-0010 section 6) requires an external security review of apps/api/src/auth/ (issue 96 / issue 97) before the first outside user signs in. Second, an account-recovery flow for a person who loses their only MFA device is not built yet (review finding P-6). Third, same-origin reverse-proxy wiring in production (required for __Host- cookies across web and API) is still an open deploy task. Fourth, the OAuth connect journey has been verified end-to-end in Chromium against a loopback fake provider that production refuses; a manual connect against real Meta and Google credentials is still owed. Fifth, sign-in rate-limit counters in apps/api/src/auth/sign-in/routes.ts are still per API process rather than shared in PostgreSQL.

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

never let a security refusal travel as an implicit side effect or thenable reply object; return an explicit boolean or typed refusal and keep regression tests running across every refactor.

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.

Words to know

  • Authentication
  • Authorization
  • Authorization code flow
  • Challenge
  • Forbidden scope
  • Grant revocation
  • __Host- prefix
  • HttpOnly
  • Lockout
  • Marketer grant
  • OAuth
  • OAuth state
  • Passkey
  • Passwordless sign-in
  • Pending selection
  • PKCE
  • Relying party ID
  • Role-based access control
  • SameSite
  • Session
  • Session cookie
  • Session rotation
  • Sign-in link
  • Sign-in nonce cookie
  • Signature counter
  • Signed-in hint cookie
  • Step-up MFA
  • Step-up token
  • TOTP
  • Unified ACL
  • URL fragment
  • User verification
  • WebAuthn
  • Workspace role
  • Zero-password access

Go deeper

  • Architecture and decisions: ADR-0010, ADR-0004, AGENTS.md (rules 6, 7, 10), OWNER-DECISIONS.md (OD-14, OD-21), and INDEPENDENT-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, and OAuth 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.

Kendini sına soru özeti ve yanıt anahtarı

Q1. Why does the e-mail sign-in link put its 256-bit token in #t=... and also require the __Host-gd_login_nonce cookie?

Answer: B

Browsers never send the #... fragment in HTTP requests, keeping the token out of proxy and access logs, and requiring __Host-gd_login_nonce ensures a forwarded link cannot sign in a different browser. E-mail clients do not encrypt fragments (C), and query strings are not limited to 16 characters (A).

Q2. Why can a passkey created for this product not be stolen by tricking the owner into visiting a convincing look-alike phishing domain?

Answer: B

WebAuthn embeds the actual page origin and SHA-256(rpId) inside the signed assertion; the browser will not invoke the real site's passkey on an attacker's domain, and the server checks both values. Passkeys do not rotate every 30 seconds (A) and involve no password (C).

Q3. 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?

Answer: B

Step-up MFA (fresh TOTP or passkey within 10 minutes) blocks OAuth connect, binding approvals, milestone release, workspace deletion, and MFA factor replacement (403 MFA_REENROLL_REQUIRES_STEPUP), while sessions expire after 12 hours idle or 30 days absolute (ruling out A and D) and vault.* is never exposed to the UI or {product}_app (ruling out C).

Q4. Why does the web app receive __Host-gd_signed_in=1 in addition to __Host-gd_session?

Answer: A

Keeping the real session token HttpOnly blocks XSS token theft, so the UI needs a harmless 1 hint to switch from sample preview mode to live credentialed requests while the API authorizes strictly from __Host-gd_session. The hint carries no role or user data (ruling out B).

Q5. An SMB owner clicks Yetkiyi kaldır (Revoke access) on a hired marketer's grant. What happens immediately?

Answer: C

app_has_workspace_access checks g.revoked_at IS NULL on every query, unified ACL enforces the same rule across all eight channels, pending proposals authored by that grant are cancelled, and zero passwords or ad-account ownership ever belonged to the marketer (ruling out A, B, and D).

Q6. Why did owner decision OD-21 add vault.oauth_pending_selections with a hard 10-minute lifetime and hourly purge?

Answer: B

When OAuth returns several ad accounts, vault.oauth_pending_selections holds the AES-256-GCM-sealed tokens bound to (selection_id, workspace, user, provider) for at most 10 minutes (OD-21), deletes the row atomically when the owner selects one account, and purges abandoned rows hourly via migration 0011. Tokens never enter sessionStorage (A) and marketers are blocked from OAuth connect and export (D).

GetClaps Kurucu Akademisi · Tarayıcı açılışında ağ çağrısı yapılmaz; ilerleme yalnızca cihazındaki yerel depolamada tutulur.