@quickback-dev/cli 0.70.26 → 0.70.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/codex/AGENTS.md +290 -0
- package/dist/commands/build.test.d.ts.map +1 -0
- package/dist/commands/codex.d.ts +16 -0
- package/dist/commands/codex.d.ts.map +1 -0
- package/dist/commands/codex.js +159 -0
- package/dist/commands/codex.js.map +1 -0
- package/dist/commands/compile.d.ts +62 -0
- package/dist/commands/compile.d.ts.map +1 -0
- package/dist/commands/compile.js +830 -0
- package/dist/commands/compile.js.map +1 -0
- package/dist/commands/compile.test.d.ts.map +1 -0
- package/dist/commands/init.d.ts +6 -0
- package/dist/commands/init.d.ts.map +1 -0
- package/dist/commands/init.js +405 -0
- package/dist/commands/init.js.map +1 -0
- package/dist/commands/migrate.test.d.ts.map +1 -0
- package/dist/commands/migrations.test.d.ts.map +1 -0
- package/dist/commands/push.test.d.ts.map +1 -0
- package/dist/commands/schema.test.d.ts.map +1 -0
- package/dist/docs/content.d.ts +7 -0
- package/dist/docs/content.d.ts.map +1 -0
- package/dist/docs/content.js +672 -0
- package/dist/docs/content.js.map +1 -0
- package/dist/docs/index.test.d.ts.map +1 -0
- package/dist/index.js +1 -1
- package/dist/lib/action-harvest.test.d.ts.map +1 -0
- package/dist/lib/api-client.test.d.ts.map +1 -0
- package/dist/lib/artifact-routing.test.d.ts.map +1 -0
- package/dist/lib/auth.test.d.ts.map +1 -0
- package/dist/lib/compile-next-steps.test.d.ts.map +1 -0
- package/dist/lib/compiler-floor.test.d.ts.map +1 -0
- package/dist/lib/config-id-splice.test.d.ts.map +1 -0
- package/dist/lib/config-sync.test.d.ts.map +1 -0
- package/dist/lib/copy-public-assets.test.d.ts.map +1 -0
- package/dist/lib/copy-source-apps.test.d.ts.map +1 -0
- package/dist/lib/drizzle-meta-routing.test.d.ts.map +1 -0
- package/dist/lib/file-loader-typescript-fallback.test.d.ts.map +1 -0
- package/dist/lib/file-loader.test.d.ts.map +1 -0
- package/dist/lib/file-writer.test.d.ts.map +1 -0
- package/dist/lib/helpers.d.ts +39 -0
- package/dist/lib/helpers.d.ts.map +1 -0
- package/dist/lib/helpers.js +299 -0
- package/dist/lib/helpers.js.map +1 -0
- package/dist/lib/migrations/drizzle-prompts.test.d.ts.map +1 -0
- package/dist/lib/migrations/drizzle.test.d.ts.map +1 -0
- package/dist/lib/migrations/executor.test.d.ts.map +1 -0
- package/dist/lib/migrations/inventory.test.d.ts.map +1 -0
- package/dist/lib/migrations/lock.test.d.ts.map +1 -0
- package/dist/lib/migrations/paths.test.d.ts.map +1 -0
- package/dist/lib/migrations/plan.test.d.ts.map +1 -0
- package/dist/lib/migrations/postprocessors/index.test.d.ts.map +1 -0
- package/dist/lib/migrations/prompt-runner.test.d.ts.map +1 -0
- package/dist/lib/migrations/staging.test.d.ts.map +1 -0
- package/dist/lib/neon-canary.test.d.ts.map +1 -0
- package/dist/lib/neon-target.test.d.ts.map +1 -0
- package/dist/lib/neon.test.d.ts.map +1 -0
- package/dist/lib/prepare-output.test.d.ts.map +1 -0
- package/dist/lib/prepare-state-output.test.d.ts.map +1 -0
- package/dist/lib/schema-sync/index.test.d.ts.map +1 -0
- package/dist/lib/shell.test.d.ts.map +1 -0
- package/dist/lib/sweep-stale.d.ts +25 -0
- package/dist/lib/sweep-stale.d.ts.map +1 -0
- package/dist/lib/sweep-stale.js +179 -0
- package/dist/lib/sweep-stale.js.map +1 -0
- package/dist/lib/sweep-stale.test.d.ts.map +1 -0
- package/dist/lib/wrangler-resources.test.d.ts.map +1 -0
- package/dist/skill/docs/configure/providers.md +3 -0
- package/dist/skill/docs/define/encryption.md +2 -2
- package/dist/skill/docs/define/read.md +6 -0
- package/dist/skill/docs/define/sealed-protocol.md +115 -10
- package/dist/skill/docs/platform/database/index.md +1 -0
- package/dist/skill/docs/platform/database/neon.md +86 -0
- package/dist/skill/docs/platform/database/planetscale-postgres.md +7 -0
- package/dist/skill/docs/platform/database/read-replication.md +122 -0
- package/dist/skill/docs/platform/database/using-d1.md +2 -1
- package/package.json +1 -1
- package/src/skill/docs/configure/providers.md +3 -0
- package/src/skill/docs/define/encryption.md +2 -2
- package/src/skill/docs/define/read.md +6 -0
- package/src/skill/docs/define/sealed-protocol.md +115 -10
- package/src/skill/docs/platform/database/index.md +1 -0
- package/src/skill/docs/platform/database/neon.md +86 -0
- package/src/skill/docs/platform/database/planetscale-postgres.md +7 -0
- package/src/skill/docs/platform/database/read-replication.md +122 -0
- package/src/skill/docs/platform/database/using-d1.md +2 -1
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# Read replication
|
|
2
|
+
|
|
3
|
+
Cloudflare D1 can keep read-only copies of a database in every region
|
|
4
|
+
(ENAM, WNAM, WEUR, EEUR, APAC, OC) at no extra cost. Replicas only serve
|
|
5
|
+
queries made through the [D1 Sessions
|
|
6
|
+
API](https://developers.cloudflare.com/d1/best-practices/read-replication/);
|
|
7
|
+
plain binding queries always go to the primary. `readReplication` makes the
|
|
8
|
+
generated API use that session for every request-scoped feature read.
|
|
9
|
+
|
|
10
|
+
```typescript
|
|
11
|
+
// quickback.config.ts
|
|
12
|
+
database: defineDatabase("cloudflare-d1", {
|
|
13
|
+
readReplication: true,
|
|
14
|
+
}),
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Then enable replication on the features database itself — **Settings →
|
|
18
|
+
Enable Read Replication** in the D1 dashboard, or `PUT` the database with
|
|
19
|
+
`{ "read_replication": { "mode": "auto" } }` through the REST API. The
|
|
20
|
+
compiler never flips that switch. The generated code is correct either way:
|
|
21
|
+
without replicas every session runs on the primary, so turning the flag on
|
|
22
|
+
first and replication on later is safe.
|
|
23
|
+
|
|
24
|
+
D1 only. Postgres providers reject the option; Neon's read replicas are a
|
|
25
|
+
connection-string concern.
|
|
26
|
+
|
|
27
|
+
## What the generated API does
|
|
28
|
+
|
|
29
|
+
Each request's `db` handle runs on a D1 session. The session constraint is
|
|
30
|
+
chosen by method:
|
|
31
|
+
|
|
32
|
+
| Request | Session starts | Why |
|
|
33
|
+
|---------|----------------|-----|
|
|
34
|
+
| `GET` / `HEAD` carrying the bookmark header | at that bookmark | The client continues its own session: monotonic reads, read-your-writes |
|
|
35
|
+
| `GET` / `HEAD` without the header | `first-unconstrained` | Nearest replica — the common case for a fresh page load |
|
|
36
|
+
| Everything else (`POST`, `PATCH`, `PUT`, `DELETE`, actions, batch) | `first-primary` | Writes go to the primary anyway; starting there keeps a handler's reads after its own write fresh |
|
|
37
|
+
|
|
38
|
+
Every response carries the session's bookmark:
|
|
39
|
+
|
|
40
|
+
```http
|
|
41
|
+
HTTP/1.1 200 OK
|
|
42
|
+
x-d1-bookmark: 00000085-0000000a-00004e6e-9d8f2c1b
|
|
43
|
+
x-d1-served-by: WEUR;primary=false
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
A client that sends the bookmark back on its next `GET` gets sequential
|
|
47
|
+
consistency across requests: it never reads an older version of the database
|
|
48
|
+
than the one it last saw, and it sees its own writes. A client that ignores
|
|
49
|
+
the header gets eventual consistency on reads only — the same thing any
|
|
50
|
+
replicated database gives an un-sessioned reader — and still gets fresh
|
|
51
|
+
reads inside every write. Both headers are CORS-exposed so browser code can
|
|
52
|
+
read them.
|
|
53
|
+
|
|
54
|
+
`x-d1-served-by` is for verifying a rollout: it is set only when D1 reports
|
|
55
|
+
where the session ran (`meta.served_by_region` / `served_by_primary`), which
|
|
56
|
+
is every remote request and never `wrangler dev`.
|
|
57
|
+
|
|
58
|
+
### Echo the bookmark from your client
|
|
59
|
+
|
|
60
|
+
{/* doc-compile: skip — client-side fetch wrapper; `API` is the app's base URL, not a compiler symbol. */}
|
|
61
|
+
```typescript
|
|
62
|
+
let bookmark: string | null = null;
|
|
63
|
+
|
|
64
|
+
async function api(path: string, init: RequestInit = {}) {
|
|
65
|
+
const headers = new Headers(init.headers);
|
|
66
|
+
if (bookmark) headers.set("x-d1-bookmark", bookmark);
|
|
67
|
+
const res = await fetch(`${API}${path}`, { ...init, headers, credentials: "include" });
|
|
68
|
+
bookmark = res.headers.get("x-d1-bookmark") ?? bookmark;
|
|
69
|
+
return res;
|
|
70
|
+
}
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
One variable per browser tab or app session is enough. Sending a bookmark
|
|
74
|
+
from a different session is harmless: D1 only guarantees the new session is
|
|
75
|
+
at least as fresh as the bookmark.
|
|
76
|
+
|
|
77
|
+
Only a well-formed bookmark (four 8-hex groups, as D1 issues them) continues
|
|
78
|
+
a session. Any other header value is ignored and the request starts
|
|
79
|
+
`first-unconstrained`, so a stale or hand-edited header can never fail a
|
|
80
|
+
query.
|
|
81
|
+
|
|
82
|
+
### Rename the header
|
|
83
|
+
|
|
84
|
+
```typescript
|
|
85
|
+
readReplication: { header: "x-bookmark" },
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
The name must be a valid HTTP header token. It is matched case-insensitively
|
|
89
|
+
on the way in and emitted lowercase.
|
|
90
|
+
|
|
91
|
+
## What stays on the primary
|
|
92
|
+
|
|
93
|
+
Only the per-request features `db` rides the session. These keep their own
|
|
94
|
+
primary handles, exactly as before:
|
|
95
|
+
|
|
96
|
+
- the auth database (Better Auth's adapter and `c.get('authDb')`) — session
|
|
97
|
+
and membership rows must never be read from a lagging replica
|
|
98
|
+
- the audit and webhooks databases
|
|
99
|
+
- [schedules](/platform/schedules), [queues](/platform/queues) and
|
|
100
|
+
[email handlers](/platform/email) — no request, no client, no bookmark
|
|
101
|
+
- Durable Objects and anything that builds its own `drizzle(env.DB)`
|
|
102
|
+
|
|
103
|
+
A read that must be fresh regardless of the client — polling a payment
|
|
104
|
+
status, an OTP flow — belongs in an action or a non-`GET` route, which starts
|
|
105
|
+
on the primary.
|
|
106
|
+
|
|
107
|
+
## Replica lag
|
|
108
|
+
|
|
109
|
+
Replication is asynchronous and a `first-unconstrained` read may be
|
|
110
|
+
arbitrarily old. D1 bounds it per session, not globally: the session waits
|
|
111
|
+
until a replica has caught up to the bookmark you passed. That is why writes
|
|
112
|
+
start `first-primary` and why the bookmark is worth echoing.
|
|
113
|
+
|
|
114
|
+
With [`queryTimeoutMs`](/platform/database/using-d1#backend-stalls) set, the
|
|
115
|
+
deadline wraps the session as well — a replica that takes too long to catch up
|
|
116
|
+
to a bookmark answers `503 DB_TIMEOUT` like any other slow read.
|
|
117
|
+
|
|
118
|
+
## Related
|
|
119
|
+
|
|
120
|
+
- [Using D1](/platform/database/using-d1) — queries, dual-DB mode, backend stalls
|
|
121
|
+
- [Database options](/configure/providers#database-options) — every `defineDatabase("cloudflare-d1")` option
|
|
122
|
+
- [Cloudflare: Global read replication](https://developers.cloudflare.com/d1/best-practices/read-replication/)
|
|
@@ -63,9 +63,10 @@ dashboard or `wrangler tail --format json` filter on `event = "DB_DEADLINE"`
|
|
|
63
63
|
and group by `binding` / `kind` to track stalls over time. The response the
|
|
64
64
|
client saw carries the same `binding` in `details`. Unset, nothing changes: no wrapper is emitted and queries are
|
|
65
65
|
unbounded, as before. The option is D1-only; Postgres drivers carry their own
|
|
66
|
-
statement timeouts. `
|
|
66
|
+
statement timeouts. With [`readReplication`](/platform/database/read-replication) on, the deadline wraps the request's D1 session too.
|
|
67
67
|
|
|
68
68
|
## Related
|
|
69
69
|
|
|
70
70
|
- [D1 Setup](/platform/database/d1) — Bindings and wrangler config
|
|
71
|
+
- [Read replication](/platform/database/read-replication) — Serve reads from regional replicas with the Sessions API
|
|
71
72
|
- [Schema](/define/schema) — Defining your database schema
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@quickback-dev/cli",
|
|
3
|
-
"version": "0.70.
|
|
3
|
+
"version": "0.70.31",
|
|
4
4
|
"description": "CLI for Quickback — define your backend in TypeScript, compile to a fully wired Cloudflare Worker (or Bun / Node) with auth, database, migrations, security, CMS, and Account UI.",
|
|
5
5
|
"author": "Kardoe Incorporated <paul@kardoe.com>",
|
|
6
6
|
"license": "MIT",
|
|
@@ -110,6 +110,7 @@ single Postgres database with no bindings or split mode (see
|
|
|
110
110
|
| `usePlurals` | `boolean` | `false` (`true` on Neon / PlanetScale Postgres) | Pluralize auth table names (e.g. `user` vs `users`). The default differs by provider — porting a D1 project to Postgres, set `usePlurals: false` explicitly to keep its table names |
|
|
111
111
|
| `splitDatabases` | `boolean` | `true` | Separate auth and features databases (D1 only) |
|
|
112
112
|
| `queryTimeoutMs` | `number` | — | Per-statement deadline for every D1 query the generated code runs (CRUD, actions, the auth adapter, cron/queue/email runners, files, audit). Unset = no deadline. D1 only — the Postgres drivers have their own timeout options. Past the deadline a read answers `503 DB_TIMEOUT` and a write `500 DB_WRITE_OUTCOME_UNKNOWN`; see [Backend stalls](/platform/database/using-d1#backend-stalls) and [Database errors](/api/errors#database-constraint-errors). The statement is **not** cancelled on the backend |
|
|
113
|
+
| `readReplication` | `boolean \| { header?: string }` | — | Run each request's feature `db` on a D1 session so regional read replicas can serve it. `GET`/`HEAD` continue the client's session from the bookmark header (default `x-d1-bookmark`) or start `first-unconstrained`; other methods start `first-primary`. The response echoes the bookmark. D1 only; auth/audit/webhooks and cron/queue/email runners stay on the primary. Enable replication on the database itself in the Cloudflare dashboard — see [Read replication](/platform/database/read-replication) |
|
|
113
114
|
| `authBinding` | `string` | `"AUTH_DB"` | Binding name for auth database |
|
|
114
115
|
| `featuresBinding` | `string` | `"DB"` | Binding name for features database |
|
|
115
116
|
| `databaseId` | `string` | — | D1 database ID for the features database (used in generated wrangler.toml) |
|
|
@@ -132,6 +133,8 @@ single Postgres database with no bindings or split mode (see
|
|
|
132
133
|
| `connectionMode` | `"auto" \| "http" \| "websocket" \| "hyperdrive"` | `"auto"` | How the generated runtime connects (`hyperdrive` enables interactive Postgres transactions on Workers) |
|
|
133
134
|
| `hyperdrive.id` | `string` | — | Required Cloudflare Hyperdrive configuration ID when `connectionMode: "hyperdrive"` |
|
|
134
135
|
| `hyperdrive.localConnectionString` | `string` | — | Optional local-only Postgres connection used by Wrangler dev |
|
|
136
|
+
| `hyperdrive.cached.id` | `string` | — | Second Hyperdrive config with query caching **on**, bound as `HYPERDRIVE_CACHED` and connecting as the read-only `quickback_reader` role. Required when any resource declares `read: { cache: "hyperdrive" }` — see [Cached public reads](/platform/database/neon#cached-public-reads-a-second-hyperdrive-binding) |
|
|
137
|
+
| `hyperdrive.cached.localConnectionString` | `string` | — | The reader role's local URL for Wrangler dev; required whenever `hyperdrive.localConnectionString` is set |
|
|
135
138
|
| `pooled` | `boolean` | `true` | Use the pooled Neon connection string (recommended for Workers) |
|
|
136
139
|
| `usePlurals` | `boolean` | `true` | Auth table names (`users`, `members`, …). **The D1 default is `false`** — a project moving from D1 must set `usePlurals: false` to keep `user`, `member`, … |
|
|
137
140
|
|
|
@@ -200,7 +200,7 @@ Behind that one call:
|
|
|
200
200
|
5. **`/seal/v1/key`** (bearer that capability) passes three fail-closed gates — tenant, capability, live-grant — and returns the still-wrapped content key.
|
|
201
201
|
6. The client unwraps the scope key, unwraps the content key, and decrypts. **None of this touches the server with a readable key.**
|
|
202
202
|
|
|
203
|
-
Passkey reveal is the same call as `revealWithPasskey({ ..., getAssertion })`, where `getAssertion(nonce)` runs the WebAuthn ceremony.
|
|
203
|
+
Passkey reveal is the same call as `revealWithPasskey({ ..., getAssertion })`, where `getAssertion(nonce)` runs the WebAuthn ceremony. A PRF-capable passkey can also **replace the passphrase prompt**: the client wraps the passphrase-derived user master under the passkey's PRF output once (`wrapMasterWithPrf`), and from then on a single ceremony both proves the step-up and unlocks the keys (`revealWithPasskey({ ..., prfUnwrap })`). Sign-in passkeys are emitted PRF-capable at creation; native-app origins go in `encryption.seal.extraOrigins`. The derivation and envelope are specified in [Multi-factor unlock (passkey PRF)](/define/sealed-protocol#multi-factor-unlock-passkey-prf).
|
|
204
204
|
|
|
205
205
|
## Rules the compiler enforces
|
|
206
206
|
|
|
@@ -218,7 +218,7 @@ Sealed values are opaque references at rest, so they're fenced off from every su
|
|
|
218
218
|
The sealed tier protects against **full Worker compromise** — leaked secrets, malicious or buggy server code, a coerced operator. All of them get ciphertext; the keys to read it never exist server-side. Its operating model is explicit:
|
|
219
219
|
|
|
220
220
|
- **A reveal needs a real second factor.** The vault passphrase (or passkey) is separate from login and never leaves the client.
|
|
221
|
-
- **Recovery is opt-in and zero-knowledge.** A key admin can enroll a scope key wrapped under a client-held recovery
|
|
221
|
+
- **Recovery is opt-in and zero-knowledge.** A key admin can enroll a scope key wrapped under a client-held recovery factor through `/seal/v1/recovery/enroll` — a recovery code, or (`wrapMethod: 'prf-aesgcm'`) a hardware security key or shared vault passkey, one live row per method; `/recovery/use` returns only those opaque wrapped blobs. If no recovery is enrolled and every reader loses their factor, the data is unrecoverable by design.
|
|
222
222
|
- **Rotation includes re-granting.** `/rotate` versions the scope key and returns the live-reader worklist and public keys so the key-admin client can wrap and grant the new private key without exposing it to the server.
|
|
223
223
|
- **No server-side processing.** Your actions can't read, mask, search, or index a sealed value — it's plaintext only in a client that just revealed it. If the server needs to process the field, you want the envelope tier instead.
|
|
224
224
|
- **Passkey rollout check.** The server verification path and nonce-bound
|
|
@@ -91,6 +91,12 @@ interface ReadConfig {
|
|
|
91
91
|
// `firewall` block is used (the common case).
|
|
92
92
|
firewall?: FirewallConfig;
|
|
93
93
|
|
|
94
|
+
// Serve reads through Cloudflare Hyperdrive's query cache (Postgres over
|
|
95
|
+
// Hyperdrive only). Public, tenant-free data: requires
|
|
96
|
+
// `firewall: { exception: true }`, a roles-only access admitting PUBLIC,
|
|
97
|
+
// and the HYPERDRIVE_CACHED binding. See Neon → Cached public reads.
|
|
98
|
+
cache?: "hyperdrive";
|
|
99
|
+
|
|
94
100
|
// Pagination defaults for collection reads.
|
|
95
101
|
pageSize?: number; // Default page size (default: 50)
|
|
96
102
|
maxPageSize?: number; // Hard cap (default: 100)
|
|
@@ -34,6 +34,7 @@ All standard; no hand-rolled constructions. A conforming port maps each to its p
|
|
|
34
34
|
| Step-up proof | **Ed25519** sign/verify | over the [step-up message](#step-up-message) |
|
|
35
35
|
| Sealed box (wrap a key to a pubkey) | **X25519 ECDH → HKDF-SHA256 → AES-256-GCM** | see below |
|
|
36
36
|
| Content / key encryption | **AES-256-GCM** | 12-byte IV, 16-byte tag appended to ciphertext |
|
|
37
|
+
| Passkey PRF unlock (wrap the user master) | **HKDF-SHA256 → AES-256-GCM** | see [Multi-factor unlock](#multi-factor-unlock-passkey-prf) |
|
|
37
38
|
|
|
38
39
|
### Argon2id floor
|
|
39
40
|
|
|
@@ -103,7 +104,10 @@ and on `.returning()` alike. That's the type-level face of "the server is
|
|
|
103
104
|
structurally unable to read it": at rest the column only ever holds a
|
|
104
105
|
`{ __vaultRef }` marker, and the brand keeps action code from string-processing
|
|
105
106
|
or hand-forwarding that marker. Sealed values leave the system exclusively
|
|
106
|
-
through the `/seal/v1` reveal rails below.
|
|
107
|
+
through the `/seal/v1` reveal rails below. On D1 the column is emitted as
|
|
108
|
+
Drizzle JSON-mode text (`text(name, { mode: 'json' })`), so the marker is
|
|
109
|
+
stored as JSON and reads back as the `{ __vaultRef, vaultItemId }` object; the
|
|
110
|
+
SQL type stays `TEXT`. (Envelope `.encrypted()` columns are
|
|
107
111
|
deliberately *not* branded — they type as `string` because the server can
|
|
108
112
|
decrypt that tier; an action reading one gets `qbenc:` ciphertext.)
|
|
109
113
|
|
|
@@ -240,22 +244,32 @@ A reader who has a role for a scope but no grant publishes their X25519 USER pub
|
|
|
240
244
|
```
|
|
241
245
|
The key-admin wraps the scope key to each `userPublicKey` and calls [`/grant`](#7-grant--enroll-a-reader--store-their-wrapped-scope-key-key-admin), which **auto-resolves** the matching pending request.
|
|
242
246
|
|
|
243
|
-
### 12. `/recovery/enroll` — escrow the scope key under a recovery
|
|
247
|
+
### 12. `/recovery/enroll` — escrow the scope key under a recovery factor (key-admin)
|
|
244
248
|
|
|
245
|
-
A key-admin (holding the scope private key) wraps it to a
|
|
249
|
+
A key-admin (holding the scope private key) wraps it to a client-held recovery factor and escrows the blob. The server stores only the opaque recovery-wrapped material — the factor, held by the client, is what makes it usable; the server can never unwrap it.
|
|
250
|
+
|
|
251
|
+
`wrapMethod` names the client-side wrap and defaults to `recovery-code`. One live recovery per **(scope key version, wrapMethod)**, so a passkey-wrapped recovery can sit next to the recovery code; re-enrolling the same method on the same key version is a 409 until it is revoked or the key rotates. `wrapMeta` is an optional JSON object the server stores verbatim and hands back at `/recovery/use` (public wrap material only — a credential id, salts, a label; capped at 4 KiB). The server never reads either field.
|
|
252
|
+
|
|
253
|
+
| `wrapMethod` | The blob is… |
|
|
254
|
+
|---|---|
|
|
255
|
+
| `recovery-code` (default) | the scope key wrapped to a key derived from a recovery code |
|
|
256
|
+
| `prf-aesgcm` | the scope key wrapped under a KEK derived from a WebAuthn PRF output (a hardware security key or a shared vault passkey); `wrapMeta` carries the credential id and salts the client needs to re-derive the KEK |
|
|
246
257
|
|
|
247
258
|
```jsonc
|
|
248
|
-
// → { scopeRef, wrappedPrivateKey: "<qbseal envelope,
|
|
249
|
-
// ← { enrolled: true, scopeRef, keyVersion: 1 }
|
|
259
|
+
// → { scopeRef, wrappedPrivateKey: "<qbseal envelope>", wrapMethod?: "recovery-code" | "prf-aesgcm", wrapMeta?: { … } }
|
|
260
|
+
// ← { enrolled: true, scopeRef, keyVersion: 1, wrapMethod: "recovery-code" }
|
|
250
261
|
```
|
|
251
262
|
|
|
252
|
-
### 13. `/recovery/use` — retrieve the recovery blob (key-admin)
|
|
263
|
+
### 13. `/recovery/use` — retrieve the recovery blob(s) (key-admin)
|
|
253
264
|
|
|
254
|
-
Returns the live recovery-wrapped scope key (and appends a `recovery` entry to the reveal log). The client unwraps it with
|
|
265
|
+
Returns the live recovery-wrapped scope key for the newest key version that has one (and appends a `recovery` entry to the reveal log). The client unwraps it with its recovery factor to recover the scope private key, then re-grants readers. The returned blobs are **useless without the factor** — the server gates *who* may fetch them, the factor gates whether one can be unwrapped.
|
|
266
|
+
|
|
267
|
+
Without `wrapMethod`, every live method for that key version rides along in `recoveries`, so a client can offer "use your security key or enter the recovery code" from one call; the top-level fields are the `recovery-code` row when one exists (wire-compatible with clients that predate `wrapMethod`). Pass `wrapMethod` to narrow to one method; 404 parity when none of that method is live.
|
|
255
268
|
|
|
256
269
|
```jsonc
|
|
257
|
-
// → { scopeRef }
|
|
258
|
-
// ← { scopeRef, keyVersion, wrappedPrivateKey: "<qbseal envelope>"
|
|
270
|
+
// → { scopeRef, wrapMethod?: "recovery-code" | "prf-aesgcm" }
|
|
271
|
+
// ← { scopeRef, keyVersion, wrappedPrivateKey: "<qbseal envelope>", wrapMethod, wrapMeta,
|
|
272
|
+
// recoveries: [{ wrapMethod, wrapMeta, wrappedPrivateKey }, …] } // 404 parity if none
|
|
259
273
|
```
|
|
260
274
|
|
|
261
275
|
#### role→grant: readers request, key-admins fulfil
|
|
@@ -271,10 +285,99 @@ When the passkey plugin is enabled, `/reveal` verifies a WebAuthn assertion whos
|
|
|
271
285
|
| `challenge` | the `/challenge` `nonce` **as the base64url string** (the client signs the b64url text, the server passes `expectedChallenge = nonce`) |
|
|
272
286
|
| `rpID` | the passkey plugin's `rpID` — i.e. `crossSubDomainCookies.domain` (leading dot stripped) when configured, else the registrable host of `env.ACCOUNT_URL`, else the compile-time account origin (both emissions share one resolution, so they cannot skew) |
|
|
273
287
|
| `userVerification` | **required** (`requireUserVerification: true` — a reveal is a deliberate re-auth) |
|
|
274
|
-
| origin | the resolved account origin (mirrors the `passkey({ rpID, origin })` plugin) |
|
|
288
|
+
| origin | any of: the resolved account origin (mirrors the `passkey({ rpID, origin })` plugin), `https://<rpID>` (what an Apple associated-domain app asserts), and every entry of `encryption.seal.extraOrigins` (e.g. `android:apk-key-hash:<sha256>`) |
|
|
275
289
|
|
|
276
290
|
The credential is looked up in the **auth** database (`passkey` table) and the signature counter is clone-checked. Conformance for passkey is **verify-based** at the server; the client's job is to bind `challenge = nonce` exactly.
|
|
277
291
|
|
|
292
|
+
## Multi-factor unlock (passkey PRF)
|
|
293
|
+
|
|
294
|
+
The passphrase is one way to reach the USER keys; a passkey with the WebAuthn **PRF extension** is the other. The two converge on one secret — the 32-byte **user master** (the raw Argon2id output, before the HKDF split) — so either factor yields byte-identical keys:
|
|
295
|
+
|
|
296
|
+
```
|
|
297
|
+
master = Argon2id(passphrase, salt, params) deriveUserMaster
|
|
298
|
+
keys = HKDF-split(master) userKeysFromMaster (ed25519 / x25519, as above)
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
A PRF-capable passkey evaluates a per-credential pseudo-random function inside the authenticator, released only after user verification. The client wraps the master under a key derived from that output and stores the wrapped blob next to the enrollment. At reveal time **one ceremony** both proves the step-up (the assertion) and unlocks the keys (the PRF output) — no passphrase prompt. The server stores the blob as opaque ciphertext: it never sees the PRF output, the KEK, or the master.
|
|
302
|
+
|
|
303
|
+
### Derivation
|
|
304
|
+
|
|
305
|
+
```
|
|
306
|
+
prfSalt = SHA-256( utf8("qbseal-prf-salt-v1") ‖ utf8(orgId) ) ← extensions.prf.eval.first
|
|
307
|
+
prf = PRF(credential, prfSalt) ← 32 bytes, from the authenticator
|
|
308
|
+
|
|
309
|
+
binding = utf8(userId) ‖ 0x00 ‖ utf8(orgId) ‖ 0x00 ‖ utf8(credentialId)
|
|
310
|
+
|
|
311
|
+
KEK = HKDF-SHA256( ikm = prf, salt = kekSalt,
|
|
312
|
+
info = utf8("qbseal-prf-kek-v1") ‖ binding, L = 32 )
|
|
313
|
+
ct = AES-256-GCM( KEK, iv, plaintext = master, AAD = binding )
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
- `prfSalt` is **per org**, so one user's PRF outputs across orgs are unrelated. Pass the same salt at registration and every assertion.
|
|
317
|
+
- `credentialId` is the passkey's **base64url credential id string exactly as WebAuthn returns it** (`PublicKeyCredential.id`); it is never re-encoded. The envelope carries it verbatim so a client can pick the matching passkey before the ceremony.
|
|
318
|
+
- `kekSalt` is 32 fresh random bytes and `iv` 12; both are stored in the envelope. The `(userId, orgId, credentialId)` binding is in **both** the KEK info and the AAD, so a blob lifted from another user, org, or credential fails on the GCM tag. Open fails closed on any mismatch.
|
|
319
|
+
|
|
320
|
+
### Envelope
|
|
321
|
+
|
|
322
|
+
A `qbseal:1` envelope with a new `alg` — the wire version is unchanged and every existing decoder keeps accepting it structurally:
|
|
323
|
+
|
|
324
|
+
```jsonc
|
|
325
|
+
{ "alg": "prf-aesgcm",
|
|
326
|
+
"cred": "<credentialId, verbatim>",
|
|
327
|
+
"salt": "<base64url kekSalt, 32 bytes>",
|
|
328
|
+
"iv": "<base64url, 12 bytes>",
|
|
329
|
+
"ct": "<base64url AES-GCM ciphertext ‖ tag of the 32-byte master>" }
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
### Client usage
|
|
333
|
+
|
|
334
|
+
```typescript
|
|
335
|
+
import { deriveUserMaster, prfSaltFor, wrapMasterWithPrf, SealClient } from './lib/seal-client';
|
|
336
|
+
|
|
337
|
+
// ENROLL the passkey as a second factor (once, with the passphrase in hand).
|
|
338
|
+
const master = deriveUserMaster(passphrase, salt, enrollment.argon2);
|
|
339
|
+
const reg = await startAuthentication({ optionsJSON: {
|
|
340
|
+
...options, extensions: { prf: { eval: { first: prfSaltFor(orgId) } } },
|
|
341
|
+
} });
|
|
342
|
+
const prf = new Uint8Array(reg.clientExtensionResults.prf!.results!.first);
|
|
343
|
+
const wrapped = await wrapMasterWithPrf({ master, prf, userId, orgId, credentialId: reg.id });
|
|
344
|
+
// store `wrapped` (opaque) alongside the user's enrollment
|
|
345
|
+
|
|
346
|
+
// REVEAL with the passkey only — no passphrase prompt.
|
|
347
|
+
const seal = new SealClient(transport);
|
|
348
|
+
const plaintext = await seal.revealWithPasskey({
|
|
349
|
+
scopeRef, vaultItemId,
|
|
350
|
+
getAssertion: async (nonce) => {
|
|
351
|
+
const a = await startAuthentication({ optionsJSON: {
|
|
352
|
+
challenge: nonce, rpId, userVerification: 'required',
|
|
353
|
+
extensions: { prf: { eval: { first: prfSaltFor(orgId) } } },
|
|
354
|
+
} });
|
|
355
|
+
return { assertion: a, prf: new Uint8Array(a.clientExtensionResults.prf!.results!.first) };
|
|
356
|
+
},
|
|
357
|
+
prfUnwrap: { wrapped, userId, orgId, credentialId, argon2: enrollment.argon2 },
|
|
358
|
+
});
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
`getAssertion` may still return the raw `AuthenticationResponseJSON` with a passphrase-derived `session` — the original signature is unchanged. When `prfUnwrap` is given and no `session`, the SDK opens the blob with the assertion's PRF output (`unwrapMasterWithPrf`), builds the session from the master (`sessionFromMaster`), and completes the unwrap; it fails closed if the assertion carried no PRF output. Only the assertion is sent to `/reveal` — the PRF output never leaves the client. The Swift (`KDF.deriveUserMaster`, `KDF.userKeysFromMaster`, `Prf`) and Kotlin (`Kdf.deriveUserMaster`, `Kdf.userKeysFromMaster`, `Prf`) SDKs expose the same primitives, vector-locked to the TS reference.
|
|
362
|
+
|
|
363
|
+
### Compiler support
|
|
364
|
+
|
|
365
|
+
- With **`encryption.seal.passkeyPrf: true`** the emitted `passkey({ rpID, origin })` plugin call adds `registration: { extensions: { prf: {} } }`, so sign-in passkeys are PRF-capable at creation and the same credential serves as the unlock factor — no second enrollment ceremony. It is off by default because it changes the registration ceremony for every passkey the project creates; authenticators without PRF ignore the flag. Creation-time PRF evaluation is optional in WebAuthn, so clients should still run one assertion with `prf.eval` after registration to obtain the output they wrap with.
|
|
366
|
+
- **Reveal-log honesty.** After a PRF unlock, follow-up reveals inside the client's unlock window present the Ed25519 `passphrase`-kind proof (the key came from the unwrapped master, not from a passphrase). The server records the proof kind it verified; it cannot see how the client obtained the key. A client may declare `stepUp.unlockedBy: 'passkey' | 'passphrase'` as an unverifiable hint, which the server records verbatim next to `reauthMethod` — treat it as telemetry, never as evidence.
|
|
367
|
+
- The reveal verify accepts assertions from native apps as well as the browser. `expectedOrigin` is the account origin, `https://<rpID>` (the origin Apple's `ASAuthorization` asserts for an associated-domain app), and anything listed in **`encryption.seal.extraOrigins`** — the home for Android's `android:apk-key-hash:<sha256>`:
|
|
368
|
+
|
|
369
|
+
```typescript
|
|
370
|
+
// quickback.config.ts (fragment)
|
|
371
|
+
encryption: {
|
|
372
|
+
seal: {
|
|
373
|
+
keyAdminRoles: ['owner', 'admin'],
|
|
374
|
+
extraOrigins: ['android:apk-key-hash:pNiP5iKyQ8JwgGOaKA1zGPUB3eTSh-f-5d7HsAwBGFQ'],
|
|
375
|
+
},
|
|
376
|
+
},
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
Entries must be non-empty strings without whitespace; duplicates are dropped. A browser origin other than the account origin cannot be smuggled in — the passkey plugin's own registration check already refuses credentials from it, so listing it here widens nothing.
|
|
380
|
+
|
|
278
381
|
## Conformance vectors
|
|
279
382
|
|
|
280
383
|
Canonical vectors live at **`packages/seal-client/vectors/qbseal-v1.json`**, generated from the reference TS SDK (`bun packages/seal-client/scripts/generate-vectors.ts`) and self-validated against it (`src/vectors.test.ts`). Every input (passphrase, salt, key seeds, IVs, ephemerals) is fixed, so the file is byte-stable and each vector reproduces from its inputs alone.
|
|
@@ -288,6 +391,8 @@ Canonical vectors live at **`packages/seal-client/vectors/qbseal-v1.json`**, gen
|
|
|
288
391
|
| `sealedBoxOpen` | recipient secret + box → plaintext | open-direction (canonical) |
|
|
289
392
|
| `reveal` | passphrase → keys; owner + scope unwrap paths → plaintext | open-direction (canonical) |
|
|
290
393
|
| `envelope` | `qbseal:1:` sealed-cell decodes structurally | full |
|
|
394
|
+
| `masterSplit` | passphrase → the 32-byte master; master → the `kdf` public keys | full |
|
|
395
|
+
| `prfWrap` | `prfSaltFor(orgId)`; pinned prf + kekSalt + iv + ids → the `prf-aesgcm` envelope; a `wrongCredentialId` that must NOT open it | full (wrap is pinned by fixed salt/iv) |
|
|
291
396
|
|
|
292
397
|
A port verifies the open-direction vectors exactly, and proves its *seal* direction by round-tripping through its own open. Vectors are the **cross-language byte-for-byte guarantee** — CI runs every client (TypeScript, Swift, and Kotlin) against this one file and fails on drift.
|
|
293
398
|
|
|
@@ -29,5 +29,6 @@ security definitions compile to either provider.
|
|
|
29
29
|
|
|
30
30
|
- **[D1 Setup](/platform/database/d1)** — Bindings, wrangler config, migrations
|
|
31
31
|
- **[Using D1](/platform/database/using-d1)** — Drizzle queries, dual-DB mode, schema patterns
|
|
32
|
+
- **[Read replication](/platform/database/read-replication)** — Serve reads from D1's regional replicas with the Sessions API
|
|
32
33
|
- **[Neon](/platform/database/neon)** — Serverless Postgres setup and usage
|
|
33
34
|
- **[PlanetScale Postgres](/platform/database/planetscale-postgres)** — Roles, connection usernames, the cache-disabled Hyperdrive binding
|
|
@@ -348,6 +348,92 @@ to your concurrency, not your statement count. Raise it later with
|
|
|
348
348
|
suspend pays the compute start. Lengthen or disable autosuspend on the
|
|
349
349
|
production branch.
|
|
350
350
|
|
|
351
|
+
### Cached public reads: a second Hyperdrive binding
|
|
352
|
+
|
|
353
|
+
Hyperdrive's query cache keys on query text and parameters alone and never
|
|
354
|
+
invalidates on write, so it cannot sit under the claims-scoped `HYPERDRIVE`
|
|
355
|
+
binding. It can serve **public, tenant-free** data through a second binding
|
|
356
|
+
whose database role can see nothing else. Opt a resource in with
|
|
357
|
+
`read.cache`:
|
|
358
|
+
|
|
359
|
+
{/* doc-compile: skip — read.cache fails closed without hyperdrive.cached on the project config, which the doc harness's default project does not declare. */}
|
|
360
|
+
```ts
|
|
361
|
+
// features/venues/venues.ts
|
|
362
|
+
import { q, defineTable } from "@quickback/compiler";
|
|
363
|
+
|
|
364
|
+
export const venues = q.table("venues", {
|
|
365
|
+
id: q.id(),
|
|
366
|
+
name: q.text().required(),
|
|
367
|
+
city: q.text().required(),
|
|
368
|
+
...q.audit(),
|
|
369
|
+
...q.softDelete(),
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
export default defineTable(venues, {
|
|
373
|
+
firewall: { exception: true },
|
|
374
|
+
read: {
|
|
375
|
+
access: { roles: ["PUBLIC"] },
|
|
376
|
+
cache: "hyperdrive",
|
|
377
|
+
},
|
|
378
|
+
});
|
|
379
|
+
```
|
|
380
|
+
|
|
381
|
+
`GET /api/v1/venues`, `GET /api/v1/venues/:id` and its named views then read
|
|
382
|
+
through `HYPERDRIVE_CACHED` as `quickback_reader`, a role the security
|
|
383
|
+
migration creates with one privilege: `SELECT` on the tables that declared
|
|
384
|
+
`read.cache`, each with a `USING (true)` SELECT policy for that role. The
|
|
385
|
+
cache can only ever hold rows that role can read, so cache safety is
|
|
386
|
+
structural, not a property of any query. Everything else (writes, actions,
|
|
387
|
+
every other table) stays on `HYPERDRIVE`.
|
|
388
|
+
|
|
389
|
+
The compiler refuses `read.cache` unless all of these hold:
|
|
390
|
+
|
|
391
|
+
- Postgres over Hyperdrive on the Cloudflare runtime.
|
|
392
|
+
- `hyperdrive.cached: { id }` on the provider config, or
|
|
393
|
+
`bindings.hyperdrive.cached` on every named environment.
|
|
394
|
+
- `firewall: { exception: true }` — no tenant or owner row filter.
|
|
395
|
+
- `read.access` is a roles-only tree that admits `PUBLIC`. Record predicates,
|
|
396
|
+
relationship / permission arms, principals and function-form access are
|
|
397
|
+
rejected.
|
|
398
|
+
- No FK display columns and no `include` on the resource — the reader role
|
|
399
|
+
holds no grant on other tables.
|
|
400
|
+
|
|
401
|
+
Masking still applies per caller after the query. Reads can be stale for up
|
|
402
|
+
to the cached config's `max_age` (default 60 s, `--max-age` to change it;
|
|
403
|
+
`--swr` extends serving-while-revalidating). `Server-Timing` counts these
|
|
404
|
+
statements and the cached connection's open under `stmts` / `cold`.
|
|
405
|
+
|
|
406
|
+
Set it up once per database:
|
|
407
|
+
|
|
408
|
+
```bash
|
|
409
|
+
# 1. The security migration created quickback_reader NOLOGIN; give it a login.
|
|
410
|
+
psql "$DATABASE_SETUP_URL" -c "ALTER ROLE quickback_reader LOGIN PASSWORD '<reader-password>';"
|
|
411
|
+
|
|
412
|
+
# 2. A second Hyperdrive config, caching ON, as that role.
|
|
413
|
+
npx wrangler hyperdrive create my-app-db-cached \
|
|
414
|
+
--max-age 60 \
|
|
415
|
+
--connection-string="postgresql://quickback_reader:<reader-password>@<endpoint>.<region>.aws.neon.tech/neondb?sslmode=require"
|
|
416
|
+
```
|
|
417
|
+
|
|
418
|
+
```ts
|
|
419
|
+
database: defineDatabase("neon", {
|
|
420
|
+
connectionMode: "hyperdrive",
|
|
421
|
+
hyperdrive: {
|
|
422
|
+
id: "<hyperdrive-config-id>",
|
|
423
|
+
cached: { id: "<cached-config-id>" },
|
|
424
|
+
},
|
|
425
|
+
}),
|
|
426
|
+
```
|
|
427
|
+
|
|
428
|
+
With named environments, declare `bindings.hyperdrive.cached: { id }` on
|
|
429
|
+
every target; the `dev` target also needs
|
|
430
|
+
`cached.localConnectionString` (the reader role's local URL), as does the
|
|
431
|
+
provider-level `hyperdrive.cached` whenever `hyperdrive.localConnectionString`
|
|
432
|
+
is set — `wrangler dev` connects the cached binding as `quickback_reader`,
|
|
433
|
+
and the `quickback` role's URL reads nothing through it. The emitted
|
|
434
|
+
`createCachedDb(env)` is read-only by construction: a write or a
|
|
435
|
+
`db.transaction()` on it throws before reaching the database.
|
|
436
|
+
|
|
351
437
|
For local `wrangler dev` without named environments, set
|
|
352
438
|
`providers.database.config.hyperdrive.localConnectionString` to a local or
|
|
353
439
|
development-only Postgres URL. With named environments, put it on the target
|
|
@@ -206,6 +206,13 @@ project sets neither. The rest of the tuning notes — the session cookie cache
|
|
|
206
206
|
and connection limits — are on
|
|
207
207
|
[Neon → Tuning the Worker for Hyperdrive](/platform/database/neon#tuning-the-worker-for-hyperdrive).
|
|
208
208
|
|
|
209
|
+
Public, tenant-free resources can opt into Hyperdrive's query cache with
|
|
210
|
+
`read: { cache: "hyperdrive" }` through a second binding and the read-only
|
|
211
|
+
`quickback_reader` role — see
|
|
212
|
+
[Cached public reads](/platform/database/neon#cached-public-reads-a-second-hyperdrive-binding).
|
|
213
|
+
On PlanetScale the reader's connection username is the role name plus the
|
|
214
|
+
branch id, `quickback_reader.<branch_id>`, like the other roles.
|
|
215
|
+
|
|
209
216
|
## What is shared with Neon, and what is not
|
|
210
217
|
|
|
211
218
|
Shared — read the Neon page for the detail, it is the same generated output:
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# Read replication
|
|
2
|
+
|
|
3
|
+
Cloudflare D1 can keep read-only copies of a database in every region
|
|
4
|
+
(ENAM, WNAM, WEUR, EEUR, APAC, OC) at no extra cost. Replicas only serve
|
|
5
|
+
queries made through the [D1 Sessions
|
|
6
|
+
API](https://developers.cloudflare.com/d1/best-practices/read-replication/);
|
|
7
|
+
plain binding queries always go to the primary. `readReplication` makes the
|
|
8
|
+
generated API use that session for every request-scoped feature read.
|
|
9
|
+
|
|
10
|
+
```typescript
|
|
11
|
+
// quickback.config.ts
|
|
12
|
+
database: defineDatabase("cloudflare-d1", {
|
|
13
|
+
readReplication: true,
|
|
14
|
+
}),
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Then enable replication on the features database itself — **Settings →
|
|
18
|
+
Enable Read Replication** in the D1 dashboard, or `PUT` the database with
|
|
19
|
+
`{ "read_replication": { "mode": "auto" } }` through the REST API. The
|
|
20
|
+
compiler never flips that switch. The generated code is correct either way:
|
|
21
|
+
without replicas every session runs on the primary, so turning the flag on
|
|
22
|
+
first and replication on later is safe.
|
|
23
|
+
|
|
24
|
+
D1 only. Postgres providers reject the option; Neon's read replicas are a
|
|
25
|
+
connection-string concern.
|
|
26
|
+
|
|
27
|
+
## What the generated API does
|
|
28
|
+
|
|
29
|
+
Each request's `db` handle runs on a D1 session. The session constraint is
|
|
30
|
+
chosen by method:
|
|
31
|
+
|
|
32
|
+
| Request | Session starts | Why |
|
|
33
|
+
|---------|----------------|-----|
|
|
34
|
+
| `GET` / `HEAD` carrying the bookmark header | at that bookmark | The client continues its own session: monotonic reads, read-your-writes |
|
|
35
|
+
| `GET` / `HEAD` without the header | `first-unconstrained` | Nearest replica — the common case for a fresh page load |
|
|
36
|
+
| Everything else (`POST`, `PATCH`, `PUT`, `DELETE`, actions, batch) | `first-primary` | Writes go to the primary anyway; starting there keeps a handler's reads after its own write fresh |
|
|
37
|
+
|
|
38
|
+
Every response carries the session's bookmark:
|
|
39
|
+
|
|
40
|
+
```http
|
|
41
|
+
HTTP/1.1 200 OK
|
|
42
|
+
x-d1-bookmark: 00000085-0000000a-00004e6e-9d8f2c1b
|
|
43
|
+
x-d1-served-by: WEUR;primary=false
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
A client that sends the bookmark back on its next `GET` gets sequential
|
|
47
|
+
consistency across requests: it never reads an older version of the database
|
|
48
|
+
than the one it last saw, and it sees its own writes. A client that ignores
|
|
49
|
+
the header gets eventual consistency on reads only — the same thing any
|
|
50
|
+
replicated database gives an un-sessioned reader — and still gets fresh
|
|
51
|
+
reads inside every write. Both headers are CORS-exposed so browser code can
|
|
52
|
+
read them.
|
|
53
|
+
|
|
54
|
+
`x-d1-served-by` is for verifying a rollout: it is set only when D1 reports
|
|
55
|
+
where the session ran (`meta.served_by_region` / `served_by_primary`), which
|
|
56
|
+
is every remote request and never `wrangler dev`.
|
|
57
|
+
|
|
58
|
+
### Echo the bookmark from your client
|
|
59
|
+
|
|
60
|
+
{/* doc-compile: skip — client-side fetch wrapper; `API` is the app's base URL, not a compiler symbol. */}
|
|
61
|
+
```typescript
|
|
62
|
+
let bookmark: string | null = null;
|
|
63
|
+
|
|
64
|
+
async function api(path: string, init: RequestInit = {}) {
|
|
65
|
+
const headers = new Headers(init.headers);
|
|
66
|
+
if (bookmark) headers.set("x-d1-bookmark", bookmark);
|
|
67
|
+
const res = await fetch(`${API}${path}`, { ...init, headers, credentials: "include" });
|
|
68
|
+
bookmark = res.headers.get("x-d1-bookmark") ?? bookmark;
|
|
69
|
+
return res;
|
|
70
|
+
}
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
One variable per browser tab or app session is enough. Sending a bookmark
|
|
74
|
+
from a different session is harmless: D1 only guarantees the new session is
|
|
75
|
+
at least as fresh as the bookmark.
|
|
76
|
+
|
|
77
|
+
Only a well-formed bookmark (four 8-hex groups, as D1 issues them) continues
|
|
78
|
+
a session. Any other header value is ignored and the request starts
|
|
79
|
+
`first-unconstrained`, so a stale or hand-edited header can never fail a
|
|
80
|
+
query.
|
|
81
|
+
|
|
82
|
+
### Rename the header
|
|
83
|
+
|
|
84
|
+
```typescript
|
|
85
|
+
readReplication: { header: "x-bookmark" },
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
The name must be a valid HTTP header token. It is matched case-insensitively
|
|
89
|
+
on the way in and emitted lowercase.
|
|
90
|
+
|
|
91
|
+
## What stays on the primary
|
|
92
|
+
|
|
93
|
+
Only the per-request features `db` rides the session. These keep their own
|
|
94
|
+
primary handles, exactly as before:
|
|
95
|
+
|
|
96
|
+
- the auth database (Better Auth's adapter and `c.get('authDb')`) — session
|
|
97
|
+
and membership rows must never be read from a lagging replica
|
|
98
|
+
- the audit and webhooks databases
|
|
99
|
+
- [schedules](/platform/schedules), [queues](/platform/queues) and
|
|
100
|
+
[email handlers](/platform/email) — no request, no client, no bookmark
|
|
101
|
+
- Durable Objects and anything that builds its own `drizzle(env.DB)`
|
|
102
|
+
|
|
103
|
+
A read that must be fresh regardless of the client — polling a payment
|
|
104
|
+
status, an OTP flow — belongs in an action or a non-`GET` route, which starts
|
|
105
|
+
on the primary.
|
|
106
|
+
|
|
107
|
+
## Replica lag
|
|
108
|
+
|
|
109
|
+
Replication is asynchronous and a `first-unconstrained` read may be
|
|
110
|
+
arbitrarily old. D1 bounds it per session, not globally: the session waits
|
|
111
|
+
until a replica has caught up to the bookmark you passed. That is why writes
|
|
112
|
+
start `first-primary` and why the bookmark is worth echoing.
|
|
113
|
+
|
|
114
|
+
With [`queryTimeoutMs`](/platform/database/using-d1#backend-stalls) set, the
|
|
115
|
+
deadline wraps the session as well — a replica that takes too long to catch up
|
|
116
|
+
to a bookmark answers `503 DB_TIMEOUT` like any other slow read.
|
|
117
|
+
|
|
118
|
+
## Related
|
|
119
|
+
|
|
120
|
+
- [Using D1](/platform/database/using-d1) — queries, dual-DB mode, backend stalls
|
|
121
|
+
- [Database options](/configure/providers#database-options) — every `defineDatabase("cloudflare-d1")` option
|
|
122
|
+
- [Cloudflare: Global read replication](https://developers.cloudflare.com/d1/best-practices/read-replication/)
|
|
@@ -63,9 +63,10 @@ dashboard or `wrangler tail --format json` filter on `event = "DB_DEADLINE"`
|
|
|
63
63
|
and group by `binding` / `kind` to track stalls over time. The response the
|
|
64
64
|
client saw carries the same `binding` in `details`. Unset, nothing changes: no wrapper is emitted and queries are
|
|
65
65
|
unbounded, as before. The option is D1-only; Postgres drivers carry their own
|
|
66
|
-
statement timeouts. `
|
|
66
|
+
statement timeouts. With [`readReplication`](/platform/database/read-replication) on, the deadline wraps the request's D1 session too.
|
|
67
67
|
|
|
68
68
|
## Related
|
|
69
69
|
|
|
70
70
|
- [D1 Setup](/platform/database/d1) — Bindings and wrangler config
|
|
71
|
+
- [Read replication](/platform/database/read-replication) — Serve reads from regional replicas with the Sessions API
|
|
71
72
|
- [Schema](/define/schema) — Defining your database schema
|