@quickback-dev/cli 0.70.27 → 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 +1 -0
- package/dist/skill/docs/define/encryption.md +2 -2
- package/dist/skill/docs/define/sealed-protocol.md +111 -9
- package/dist/skill/docs/platform/database/index.md +1 -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 +1 -0
- package/src/skill/docs/define/encryption.md +2 -2
- package/src/skill/docs/define/sealed-protocol.md +111 -9
- package/src/skill/docs/platform/database/index.md +1 -0
- package/src/skill/docs/platform/database/read-replication.md +122 -0
- package/src/skill/docs/platform/database/using-d1.md +2 -1
|
@@ -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
|
|
|
@@ -243,22 +244,32 @@ A reader who has a role for a scope but no grant publishes their X25519 USER pub
|
|
|
243
244
|
```
|
|
244
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.
|
|
245
246
|
|
|
246
|
-
### 12. `/recovery/enroll` — escrow the scope key under a recovery
|
|
247
|
+
### 12. `/recovery/enroll` — escrow the scope key under a recovery factor (key-admin)
|
|
247
248
|
|
|
248
|
-
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 |
|
|
249
257
|
|
|
250
258
|
```jsonc
|
|
251
|
-
// → { scopeRef, wrappedPrivateKey: "<qbseal envelope,
|
|
252
|
-
// ← { 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" }
|
|
253
261
|
```
|
|
254
262
|
|
|
255
|
-
### 13. `/recovery/use` — retrieve the recovery blob (key-admin)
|
|
263
|
+
### 13. `/recovery/use` — retrieve the recovery blob(s) (key-admin)
|
|
256
264
|
|
|
257
|
-
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.
|
|
258
268
|
|
|
259
269
|
```jsonc
|
|
260
|
-
// → { scopeRef }
|
|
261
|
-
// ← { 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
|
|
262
273
|
```
|
|
263
274
|
|
|
264
275
|
#### role→grant: readers request, key-admins fulfil
|
|
@@ -274,10 +285,99 @@ When the passkey plugin is enabled, `/reveal` verifies a WebAuthn assertion whos
|
|
|
274
285
|
| `challenge` | the `/challenge` `nonce` **as the base64url string** (the client signs the b64url text, the server passes `expectedChallenge = nonce`) |
|
|
275
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) |
|
|
276
287
|
| `userVerification` | **required** (`requireUserVerification: true` — a reveal is a deliberate re-auth) |
|
|
277
|
-
| 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>`) |
|
|
278
289
|
|
|
279
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.
|
|
280
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
|
+
|
|
281
381
|
## Conformance vectors
|
|
282
382
|
|
|
283
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.
|
|
@@ -291,6 +391,8 @@ Canonical vectors live at **`packages/seal-client/vectors/qbseal-v1.json`**, gen
|
|
|
291
391
|
| `sealedBoxOpen` | recipient secret + box → plaintext | open-direction (canonical) |
|
|
292
392
|
| `reveal` | passphrase → keys; owner + scope unwrap paths → plaintext | open-direction (canonical) |
|
|
293
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) |
|
|
294
396
|
|
|
295
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.
|
|
296
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
|
|
@@ -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
|