@auth-craft/worker-d1-stack 0.0.0-stage → 0.2.0

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.
Files changed (72) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/README.md +296 -2
  3. package/assets/check/config.mjs +1935 -0
  4. package/assets/data/snapshot.mjs +190 -0
  5. package/assets/engine/dev-engine.mjs +1 -0
  6. package/assets/manifest.json +113 -0
  7. package/assets/migrations/0001_baseline.sql +234 -0
  8. package/assets/migrations/0002_email.sql +31 -0
  9. package/assets/migrations/0003_email_provider_index.sql +7 -0
  10. package/assets/migrations/0004_audit.sql +27 -0
  11. package/assets/migrations/0005_allowed_origins.sql +14 -0
  12. package/assets/sbom/data.cdx.json +1042 -0
  13. package/assets/sbom/worker.cdx.json +647 -0
  14. package/assets/worker/worker.js +158 -0
  15. package/bin/auth-craft-worker.mjs +4 -0
  16. package/dist/check.d.ts +9 -0
  17. package/dist/check.d.ts.map +1 -0
  18. package/dist/check.js +125 -0
  19. package/dist/check.js.map +1 -0
  20. package/dist/cli.d.ts +14 -0
  21. package/dist/cli.d.ts.map +1 -0
  22. package/dist/cli.js +433 -0
  23. package/dist/cli.js.map +1 -0
  24. package/dist/commands.d.ts +39 -0
  25. package/dist/commands.d.ts.map +1 -0
  26. package/dist/commands.js +108 -0
  27. package/dist/commands.js.map +1 -0
  28. package/dist/cutover.d.ts +63 -0
  29. package/dist/cutover.d.ts.map +1 -0
  30. package/dist/cutover.js +310 -0
  31. package/dist/cutover.js.map +1 -0
  32. package/dist/data.d.ts +52 -0
  33. package/dist/data.d.ts.map +1 -0
  34. package/dist/data.js +131 -0
  35. package/dist/data.js.map +1 -0
  36. package/dist/dev.d.ts +16 -0
  37. package/dist/dev.d.ts.map +1 -0
  38. package/dist/dev.js +80 -0
  39. package/dist/dev.js.map +1 -0
  40. package/dist/init.d.ts +23 -0
  41. package/dist/init.d.ts.map +1 -0
  42. package/dist/init.js +71 -0
  43. package/dist/init.js.map +1 -0
  44. package/dist/paths.d.ts +17 -0
  45. package/dist/paths.d.ts.map +1 -0
  46. package/dist/paths.js +13 -0
  47. package/dist/paths.js.map +1 -0
  48. package/dist/preflight.d.ts +45 -0
  49. package/dist/preflight.d.ts.map +1 -0
  50. package/dist/preflight.js +335 -0
  51. package/dist/preflight.js.map +1 -0
  52. package/dist/secrets-file.d.ts +5 -0
  53. package/dist/secrets-file.d.ts.map +1 -0
  54. package/dist/secrets-file.js +57 -0
  55. package/dist/secrets-file.js.map +1 -0
  56. package/dist/service-token.d.ts +6 -0
  57. package/dist/service-token.d.ts.map +1 -0
  58. package/dist/service-token.js +26 -0
  59. package/dist/service-token.js.map +1 -0
  60. package/dist/smoke.d.ts +45 -0
  61. package/dist/smoke.d.ts.map +1 -0
  62. package/dist/smoke.js +186 -0
  63. package/dist/smoke.js.map +1 -0
  64. package/dist/wrangler-config.d.ts +52 -0
  65. package/dist/wrangler-config.d.ts.map +1 -0
  66. package/dist/wrangler-config.js +23 -0
  67. package/dist/wrangler-config.js.map +1 -0
  68. package/dist/wrangler-runner.d.ts +13 -0
  69. package/dist/wrangler-runner.d.ts.map +1 -0
  70. package/dist/wrangler-runner.js +52 -0
  71. package/dist/wrangler-runner.js.map +1 -0
  72. package/package.json +42 -3
package/CHANGELOG.md ADDED
@@ -0,0 +1,75 @@
1
+ # @auth-craft/worker-d1-stack
2
+
3
+ The package version is the auth-craft version you deploy: the Worker is prebuilt into it.
4
+
5
+ ## 0.2.0
6
+
7
+ Moving a deployment from the Lambda app (`@auth-craft/aws-cf-stack`) to this Worker
8
+ without signing browsers out, in one command; email through the app's existing SQS
9
+ queue; tools for a Worker's own operation. No new D1 migration.
10
+
11
+ **Breaking — check before upgrading:**
12
+ - Each app now has its own refresh cookie, named as the Lambda app names them:
13
+ `refresh_token` (customer), `refresh_token_tenant` (tenant), `refresh_token_system`
14
+ (system). 0.1.0 used one `refresh_token` for every app, so one app's login overwrote
15
+ another's. After upgrading, a browser signed in to the tenant or system app with the
16
+ 0.1.0 cookie signs in again once. Rename with `REFRESH_COOKIE_CUSTOMER` / `_TENANT` /
17
+ `_SYSTEM`.
18
+ - `REFRESH_TOKEN_COOKIE_NAME` with the customer / tenant / system presets is refused at
19
+ boot (it would be ignored). It still names the cookie of `AUTH_APPS` apps without a
20
+ `cookieName`.
21
+ - The refresh grace window is 30 s by default (was a fixed 5 s): a refresh token replayed
22
+ within 30 s of its rotation returns the current tokens instead of revoking the session.
23
+ `REFRESH_TOKEN_GRACE_WINDOW_MS=5000` keeps the old behaviour.
24
+
25
+ **Upgrade:** `npm i -D @auth-craft/worker-d1-stack@0.2.0`, remove `REFRESH_TOKEN_COOKIE_NAME`
26
+ from `vars` if set (or move to `REFRESH_COOKIE_*`), `npx auth-craft-worker check
27
+ --secrets-file .secrets`, then `deploy`.
28
+
29
+ **Settings, as the Lambda app reads them** (README › Moving from the Lambda app):
30
+ - `REFRESH_COOKIE_CUSTOMER` / `_TENANT` / `_SYSTEM`, `REFRESH_TOKEN_STRATEGY_CUSTOMER` /
31
+ `_TENANT` / `_SYSTEM`, `JWT_ISSUER` (default `AUTH_SYSTEM_NAME`, as before),
32
+ `REFRESH_TOKEN_GRACE_WINDOW_MS`, `VERIFICATION_RESEND_COOLDOWN_SECONDS` (default 60, as
33
+ before), `TOKEN_AUD_CUSTOMER` / `_TENANT` / `_SYSTEM` (the Lambda names of
34
+ `JWT_*_AUDIENCE`; both set must agree).
35
+
36
+ **Moving from Lambda:**
37
+ - `auth-craft-worker cutover`: preflight → Worker in maintenance → Lambda fence → export →
38
+ verify → check-hashes → import → reconcile → maintenance off → smoke → your switch.
39
+ Resumable; `--rollback` before the switch, `--rollback-after-writes` after it (the
40
+ Worker's data into a new Lambda table). Needs `@auth-craft/aws-cf-stack` 2.2.0 for the
41
+ fence and the table suffix.
42
+ - `auth-craft-worker preflight --from-lambda <function>`: read-only comparison of the
43
+ Lambda app's effective settings with the Worker's, D1 migrated and empty, relay token.
44
+ - `auth-craft-worker data export|verify|check-hashes|import|reconcile [--local]`: the
45
+ snapshot commands of the admin CLI, bundled (no clone of auth-craft); the D1 id,
46
+ `EMAIL_CANONICALIZE` and MFA key ids come from `wrangler.json`. `check-hashes`: every
47
+ password hash inside the password engine allowlist.
48
+ - `smoke --cookie --origin <https origin>` for an app that refreshes by cookie (a refresh
49
+ from a foreign origin must be refused); `smoke --app <id>` calls `/{id}/auth/...`.
50
+
51
+ **Email:**
52
+ - `EMAIL_PROVIDER=relay`: auth emails go through the email relay Lambda
53
+ (`auth-craft-stack email-relay`, `@auth-craft/aws-cf-stack` 2.2.0) to the app's SQS
54
+ queue, in the Lambda app's envelope, with no AWS key on Cloudflare. `EMAIL_RELAY_URL`,
55
+ `EMAIL_RELAY_SIGNING_KEY` (secret), `EMAIL_RELAY_ISSUER`, `EMAIL_RELAY_TIMEOUT_MS`.
56
+
57
+ **Operation:**
58
+ - `MAINTENANCE_MODE` and `auth-craft-worker maintenance on|off|status`: every route but
59
+ `/health` answers 503 with `Retry-After`, the cron skips, queued messages are retried.
60
+ `/health` reports `maintenance`.
61
+ - `auth-craft-worker bootstrap-admin --email … [--create] [--local]`: the system tenant's
62
+ owner on D1 (the same use case as the PostgreSQL server's `bootstrap-owner`).
63
+ - `auth-craft-worker dev [--seed-admin …]`: the Worker on your machine for end-to-end
64
+ tests (local D1, seeded admin, a local password engine for `remote`).
65
+ - `init --cron none|<expr>` and `POST /internal/maintenance/cleanup` (backend-sdk 0.16.0
66
+ `runCleanup`): cleanup without a Cron Trigger; `check` warns when none is set.
67
+ - README: the Workers Free limits shared with your app's account, with the rows per flow.
68
+
69
+ **Requirements:** `dev --seed-admin` and `--local` need Node 22.13+ (`node:sqlite`);
70
+ `preflight` and `cutover` need the `aws` CLI with read access to the Lambda function.
71
+
72
+ ## 0.1.0
73
+
74
+ First release: the Worker + D1 backend, `init`, `check`, `secrets`, `migrate`, `deploy`,
75
+ `smoke`, `version`.
package/README.md CHANGED
@@ -1,3 +1,297 @@
1
- # Temporary Holding Version
1
+ # @auth-craft/worker-d1-stack
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Auth Craft backend on Cloudflare Workers + D1, ready to deploy: the prebuilt Worker,
4
+ its D1 migrations, and `auth-craft-worker`, a CLI that writes the Wrangler config, checks
5
+ it, uploads secrets, applies migrations and deploys. No clone or build of auth-craft.
6
+
7
+ The package version is the auth-craft version you deploy. `main` in the generated
8
+ config points into the installed package and the Worker ships as built (`no_bundle`), so
9
+ upgrading is `npm i @auth-craft/worker-d1-stack@<version>` followed by `deploy`.
10
+
11
+ Clients call this Worker directly (no gateway in front): see the URL and app model in
12
+ the auth-craft docs (`docs/CLOUDFLARE_WORKERS_PLAN.md` §6.5).
13
+
14
+ ## Requirements
15
+
16
+ - Node.js 20+, `wrangler` 4 (`npm i -D wrangler`), `wrangler login` for real deploys.
17
+ - Node.js 22.13+ for `dev --seed-admin` and `--local` (they use `node:sqlite`); the `aws` CLI
18
+ for `preflight` / `cutover` (read access to the Lambda function, and SSM if it loads secrets there).
19
+ - A D1 database: `npx wrangler d1 create auth` (note its id).
20
+ - Workers Paid for `--password-engine local` (scrypt needs more than the Free 10 ms CPU),
21
+ or Workers Free with `--password-engine remote` and a password engine (deploy one with
22
+ `auth-craft-stack password-engine` from `@auth-craft/aws-cf-stack`).
23
+
24
+ ## Use
25
+
26
+ ```bash
27
+ npm i -D @auth-craft/worker-d1-stack wrangler
28
+
29
+ npx auth-craft-worker init --name auth-prod --database-name auth --database-id <uuid> \
30
+ --password-engine local --domain auth.example.com --cors-origins https://app.example.com
31
+ # → wrangler.json (edit vars as needed; never put secrets there)
32
+
33
+ cat > .secrets <<'SECRETS'
34
+ JWT_PRIVATE_KEY=...
35
+ JWT_PUBLIC_KEY=...
36
+ SECRETS
37
+ chmod 600 .secrets
38
+
39
+ npx auth-craft-worker check --secrets-file .secrets # no account needed
40
+ npx auth-craft-worker deploy --secrets-file .secrets --dry-run
41
+ npx auth-craft-worker secrets --secrets-file .secrets # wrangler secret bulk
42
+ npx auth-craft-worker deploy --secrets-file .secrets # check → D1 migrations → deploy
43
+ AUTH_CRAFT_SMOKE_PASSWORD=... npx auth-craft-worker smoke \
44
+ --url https://auth.example.com --password-engine local --email smoke@example.com
45
+ ```
46
+
47
+ | Command | Does |
48
+ | --- | --- |
49
+ | `init` | Writes `wrangler.json`: D1 as `DB`, the `RATE_LIMITER` Durable Object, the cleanup cron, optional custom domain and email queue, `workers_dev`/`preview_urls` off. Refuses to overwrite without `--force`. |
50
+ | `check` | Without an account: the config deploys this package's Worker unmodified (path, `no_bundle`, SHA-256); bindings the settings need (D1, the rate limiter in production, the email queue, `send_email`); the Worker's own config rules over `vars` + the secrets file (the refusals it would answer with 503); no secret in `vars`; unknown variables (typos) as warnings. Prints names, never values. |
51
+ | `secrets` | After `check`, uploads every key of the secrets file with one `wrangler secret bulk`; the JSON file exists (mode 600) only during the call. |
52
+ | `migrate` | `wrangler d1 migrations apply DB --remote` (or `--local`). |
53
+ | `deploy` | `check`, then migrations, then `wrangler deploy`. `--dry-run` builds and validates, uploads nothing; `--skip-migrations` leaves D1 alone. |
54
+ | `maintenance` | `on` / `off`: writes `MAINTENANCE_MODE` to `vars` and deploys (no migrations); a failed deploy restores the file. `status` reads the file; the live Worker reports `maintenance` on `/health`. |
55
+ | `cutover` | Move a Lambda deployment here in one resumable command, and roll back (below). |
56
+ | `bootstrap-admin` | The system tenant's owner on this D1 (`--local` for the local one): `--email`, `--create` with `BOOTSTRAP_OWNER_PASSWORD`. Idempotent; another owner is refused. |
57
+ | `dev` | This Worker on your machine for end-to-end tests: local D1 migrated, `--seed-admin`, `wrangler dev --local`; a local password engine when `PASSWORD_ENGINE=remote`. |
58
+ | `preflight` | Read-only checks before moving a Lambda deployment here (below). Exit 1 if any fails. |
59
+ | `data` | `export` / `verify` / `import` / `reconcile` a snapshot between DynamoDB (the Lambda app) or D1 and this Worker's D1 (below). |
60
+ | `smoke` | Black-box checks of a running Worker over HTTP (below). Exit 1 if any fails. |
61
+ | `version` | The packaged version and Worker hash. |
62
+
63
+ The secrets file is `NAME=value` lines (`#` comments, optional quotes) and must not be
64
+ readable by other users. Secret variables: `JWT_PRIVATE_KEY`, `GATEWAY_SECRET`,
65
+ `PASSWORD_ENGINE_SIGNING_KEY`, `MFA_SECRET_KEY`, `MFA_SECRET_PREVIOUS_KEYS`,
66
+ `RESEND_API_KEY`, `RESEND_WEBHOOK_SECRET`, `GOOGLE_CLIENT_SECRET`, `FACEBOOK_CLIENT_SECRET`.
67
+
68
+ ## Moving from the Lambda app (`@auth-craft/aws-cf-stack`)
69
+
70
+ The Worker reads the Lambda app's variables under the same names and defaults, so a
71
+ deploy that copies the Lambda env keeps browsers signed in after the data move:
72
+
73
+ | Variable | Default | |
74
+ | --- | --- | --- |
75
+ | `REFRESH_COOKIE_CUSTOMER` / `_TENANT` / `_SYSTEM` | `refresh_token` / `refresh_token_tenant` / `refresh_token_system` | One refresh cookie per app; two apps sharing one is refused. `REFRESH_TOKEN_COOKIE_NAME` is refused with these presets (it applies only to `AUTH_APPS` apps without a `cookieName`). |
76
+ | `REFRESH_TOKEN_STRATEGY_CUSTOMER` / `_TENANT` / `_SYSTEM` | `REFRESH_TOKEN_STRATEGY` | Per-app transport (`body` / `cookie` / `both`). |
77
+ | `JWT_ISSUER` | `AUTH_SYSTEM_NAME` | `iss` of user tokens. `AUTH_SYSTEM_NAME` stays the name in emails and authenticator apps. |
78
+ | `REFRESH_TOKEN_GRACE_WINDOW_MS` | 30000 (max 120000) | How long a just-rotated refresh token still works (reload or second tab mid-refresh). |
79
+ | `VERIFICATION_RESEND_COOLDOWN_SECONDS` | 60 | |
80
+ | `TOKEN_AUD_CUSTOMER` / `_TENANT` / `_SYSTEM` | the app id | The Lambda name of `JWT_*_AUDIENCE`; both set must agree. |
81
+
82
+ The cookie, strategy and audience variables cannot be combined with `AUTH_APPS`.
83
+ Variables of the Lambda app the Worker does not read (SMTP, DynamoDB, SSM, gateway JWT,
84
+ the SQS envelope) are listed with the reason in the auth-craft repository
85
+ (`apps/auth-worker-d1/test/lambda-parity.test.ts`).
86
+
87
+ `REFRESH_TOKEN_STRATEGY` still defaults to `body` on the Worker (the Lambda app defaults
88
+ to `cookie`): set it explicitly when copying.
89
+
90
+ ## Before the move (`preflight`)
91
+
92
+ ```bash
93
+ npx auth-craft-worker preflight --from-lambda myapp-prod-auth-api --region ap-southeast-1 --secrets-file .secrets
94
+ ```
95
+
96
+ Reads the Lambda's environment (`aws lambda get-function-configuration`, plus the SSM
97
+ parameters when it loads its secrets there) and compares each setting by its effective
98
+ value with `wrangler.json` + the secrets file: JWT public key and algorithm, issuer,
99
+ apps and audiences, refresh cookie names, strategies and attributes, browser origins
100
+ (the Lambda's `CORS_ORIGINS` must all be in the Worker's; behind the gateway it is a
101
+ warning to compare by hand), identity policy, session lifetimes, grace window and
102
+ lockout, MFA key ids, OAuth client ids and secrets. Then: D1 migrated and empty, the
103
+ email relay accepts the Worker's token (`EMAIL_PROVIDER=relay`), and `/health` with
104
+ `--url`. Prints check names, never values. Needs `aws` with read access to the function
105
+ (and the SSM parameters) and `wrangler` with D1 access.
106
+
107
+ ## A new deployment's admin (`bootstrap-admin`)
108
+
109
+ ```bash
110
+ BOOTSTRAP_OWNER_PASSWORD=... npx auth-craft-worker bootstrap-admin --email admin@example.com --create
111
+ ```
112
+
113
+ Makes the account the owner of the system tenant (`SYSTEM_TENANT_ID`, default
114
+ `__system__`), creating it already verified with `--create` when no account has that
115
+ email; an existing account keeps its password, an unverified one is refused. The same
116
+ use case as the PostgreSQL server's `auth-craft-admin bootstrap-owner`. Writes through
117
+ the D1 REST API (`CLOUDFLARE_ACCOUNT_ID` + `CLOUDFLARE_API_TOKEN`), or with `--local`
118
+ into the local D1 of `wrangler dev`. A moved deployment does not need it: the admin
119
+ comes with the snapshot.
120
+
121
+ ## Your app's end-to-end tests (`dev`)
122
+
123
+ ```bash
124
+ # .dev.vars holds JWT_PRIVATE_KEY / JWT_PUBLIC_KEY (and other secrets) for wrangler dev
125
+ BOOTSTRAP_OWNER_PASSWORD=... npx auth-craft-worker dev --port 8787 --seed-admin admin@example.com
126
+ ```
127
+
128
+ Migrates the local D1, seeds the admin (Node 22.13+: it writes the local D1 file with
129
+ `node:sqlite`), then runs `wrangler dev --local` until interrupted. With
130
+ `PASSWORD_ENGINE=remote` it also starts the real password engine on 127.0.0.1 with a key
131
+ made for the run and hands it to the Worker with `--var` (your `.dev.vars` is not
132
+ changed). The local D1 persists in `.wrangler/state` between runs; delete it for a clean
133
+ start.
134
+
135
+ ## Sharing a Workers Free account with your app
136
+
137
+ These limits are per **account**, shared with every Worker and D1 database of the app:
138
+
139
+ | Limit (Free, per day) | Auth's share, measured on Workers Free |
140
+ | --- | --- |
141
+ | 100,000 Worker requests | one per auth call (login, refresh, /auth/me, …) |
142
+ | 5 million D1 rows read | register ~6, login ~8, wrong password ~4, refresh ~2.5, /auth/me ~1, logout ~1.5 |
143
+ | 100,000 D1 rows written (index updates count) | register ~16, login ~5, wrong password ~1, refresh ~3.25, logout ~0.75; `AUDIT_STORE=d1` adds one per event |
144
+ | 5 Cron Triggers | one, for cleanup; `init --cron none` and call `runCleanup` from your own cron instead |
145
+
146
+ Rows written are the real ceiling: a user active one hour (1 login + 4 refreshes ≈ 18
147
+ rows) leaves room for about 5,000 users a day; one with the app open eight hours
148
+ (a refresh every 15 minutes ≈ 110 rows) for about 900, before your app's own writes. A
149
+ cutover imports every row once (`data import --dry-run` counts them); a large
150
+ deployment may not fit in one day on Free. Do not cut security writes (lockout counters,
151
+ token rotation, revocation) to save quota.
152
+
153
+ ## Moving a Lambda deployment in one command (`cutover`)
154
+
155
+ ```bash
156
+ npx auth-craft-worker cutover \
157
+ --from-lambda myapp-prod-auth-api --region ap-southeast-1 --table myapp-prod-auth-data \
158
+ --secrets-file .secrets --snapshot-dir ./cutover-snap \
159
+ --fence "npx auth-craft-stack fence --stage prod --app-name myapp" \
160
+ --switch "./deploy.sh web admin api" \
161
+ --smoke-url https://auth.myapp.com --smoke-email smoke@myapp.com --smoke-origin https://app.myapp.com --smoke-app tenant
162
+ # prints the plan and changes nothing; add --yes to carry it out
163
+ ```
164
+
165
+ Steps: `preflight` → Worker deployed in maintenance → `<fence> on` (and `<fence> status`
166
+ must print `FENCE=on`) → `data export` → `verify` → `check-hashes` (every password hash
167
+ inside the engine's allowlist; `--max-n` = the engine's `PASSWORD_ENGINE_MAX_N`) →
168
+ `import` → `reconcile` → maintenance off → `smoke` → `--switch` (your routing change).
169
+
170
+ - **Resumable.** State lives in `<snapshot-dir>.cutover.json`; a re-run skips finished
171
+ steps. An import that started and did not finish is never re-run blindly: reconcile
172
+ first.
173
+ - **Rollback before the switch:** `cutover --rollback --snapshot-dir … --fence … --secrets-file … --yes`
174
+ lifts the fence and keeps the Worker in maintenance.
175
+ - **From the first command of `--switch` on**, users may have written to the Worker (a
176
+ switch deploys several things one after the other), so `--rollback` is refused. A
177
+ failed switch puts the Worker back in maintenance; fix and re-run (it resumes at the
178
+ switch), or `cutover --rollback-after-writes --snapshot-dir <new> --fence … --lambda-deploy
179
+ "LAMBDA_DYNAMODB_TABLE_SUFFIX=-r1 npx auth-craft-stack lambda --stage prod" --table
180
+ myapp-prod-auth-data-r1 --region … --switch-back "…" --secrets-file … --yes`: Worker
181
+ into maintenance, its data exported, the Lambda deployed onto a new empty table (still
182
+ fenced, checked), imported, reconciled, fence off, your switch back.
183
+ - **The smoke account must be a dedicated account**, never a real user's: a smoke login
184
+ is one more session, and with `maxConcurrentSessions` it pushes out that user's oldest
185
+ session.
186
+ - **Not carried by the snapshot:** pending verification and reset links, sign-in and MFA
187
+ codes (users request them again), rate-limit counters, the Worker's email logs and
188
+ suppressions. Sessions, lockouts and MFA authenticators are carried. Do it at a quiet
189
+ hour.
190
+
191
+ Rehearsed locally in the auth-craft repository (`pnpm --filter
192
+ @auth-craft/worker-d1-stack test:release`): the real Lambda app on DynamoDB Local, this
193
+ package's Worker in Miniflare, the bundled snapshot CLI; a browser keeps both sessions,
194
+ and a password changed on the Worker comes back through `--rollback-after-writes`.
195
+
196
+ ## Moving the data (`data`)
197
+
198
+ The snapshot commands of the auth-craft admin CLI, bundled: encrypted by default (no
199
+ plaintext fallback), every type preflighted before the first write, reconciled after,
200
+ and only into an empty store. The D1 database id (`DB` binding), `EMAIL_CANONICALIZE` and
201
+ the MFA key ids are read from `wrangler.json` (and `--secrets-file` when the MFA keys are
202
+ secrets), so the data matches the Worker that will serve it.
203
+
204
+ ```bash
205
+ export MIGRATION_SNAPSHOT_KEY_FILE=~/keys/snapshot.key # 64 hex chars, mode 600, outside the snapshot dir
206
+ export CLOUDFLARE_ACCOUNT_ID=... CLOUDFLARE_API_TOKEN=... # D1 edit
207
+ # writers fenced first (Lambda: `auth-craft-stack fence on`)
208
+ npx auth-craft-worker data export ./snap --from dynamodb --table myapp-prod-auth-data --region ap-southeast-1 --write-fence
209
+ npx auth-craft-worker data verify ./snap
210
+ npx auth-craft-worker data import ./snap --write-fence --dry-run --secrets-file .secrets
211
+ npx auth-craft-worker data import ./snap --write-fence --secrets-file .secrets # imports, then reconciles
212
+ npx auth-craft-worker data reconcile ./snap --write-fence
213
+ ```
214
+
215
+ For a rollback, `export --from d1` and `import --to dynamodb --table <new empty table>`.
216
+ `--write-fence` only confirms that writers are stopped; it stops nothing. Challenges,
217
+ email logs and suppressions are not carried (see the auth-craft SNAPSHOT.md).
218
+
219
+ ## Maintenance mode
220
+
221
+ `auth-craft-worker maintenance on` deploys the Worker with `MAINTENANCE_MODE=true`: every
222
+ route but `/health` answers `503 SERVICE_UNAVAILABLE` with `Retry-After: 30` (webhooks and
223
+ internal routes included), the cleanup cron skips, and queued messages are retried
224
+ instead of processed. It is the Worker side of a write fence (a data move into or out of
225
+ its D1). A queued message retried past the queue's `max_retries` goes to the dead-letter
226
+ queue, and a sign-in code expires anyway (`EMAIL_MAX_AGE_MINUTES`): keep maintenance
227
+ windows short. Inbound mail (Email Routing) is still handled.
228
+
229
+ ## Email through your SQS queue (`EMAIL_PROVIDER=relay`)
230
+
231
+ For an app that already renders and sends its auth emails from an SQS queue (as with
232
+ the Lambda app's `EMAIL_MODE=queue`): deploy the relay with `auth-craft-stack
233
+ email-relay --queue-arn <arn>` from `@auth-craft/aws-cf-stack` and set
234
+
235
+ | Variable | |
236
+ | --- | --- |
237
+ | `EMAIL_PROVIDER=relay` | |
238
+ | `EMAIL_MODE` | `direct` (recommended: SQS is already a durable queue; no Queue operations on Workers Free) or `queue` |
239
+ | `EMAIL_RELAY_URL` | the relay's URL (https) |
240
+ | `EMAIL_RELAY_SIGNING_KEY` | secret: Ed25519 private JWK; the relay holds its public part |
241
+ | `EMAIL_RELAY_ISSUER` | default `PASSWORD_ENGINE_ISSUER`, else `AUTH_SYSTEM_NAME`; must match the relay |
242
+ | `EMAIL_RELAY_TIMEOUT_MS` | default 5000 (includes a cold start of the relay) |
243
+
244
+ The Worker does not render: the relay queues the request in the Lambda app's envelope
245
+ and your consumer renders and sends. `EMAIL_FROM` is not needed. Suppressions set on the
246
+ Worker still apply (a suppressed address is never forwarded and the caller cannot tell);
247
+ bounces and complaints are your consumer's. A refused token or an SQS configuration error
248
+ is recorded `failed`, a throttled or unreachable relay is retried.
249
+
250
+ ## Email delivery events (Cloudflare Email Service)
251
+
252
+ With `--email-queue` and `EMAIL_PROVIDER=cloudflare`, subscribe the Worker's email queue
253
+ (`<name>-email`) to the sending domain's Email Sending events `message.delivered`,
254
+ `message.bounced` and `message.complained` (dashboard: Queues → the queue →
255
+ Subscriptions). The Worker records them on the message it sent; a hard bounce or a
256
+ complaint suppresses that recipient, so no further sign-in codes go to a dead or
257
+ complaining mailbox. Soft bounces and deferrals change nothing.
258
+
259
+ ## Smoke after a deploy
260
+
261
+ `smoke` needs a verified account without MFA on that deployment (create it once and keep
262
+ it for smoke runs) and `REFRESH_TOKEN_STRATEGY=body` or `both`, or `--cookie --origin
263
+ https://app.example.com` for an app that refreshes by cookie (the origin must be one of
264
+ `CORS_ORIGINS`). `--app tenant` sends every auth call to `/tenant/auth/...`, the router a
265
+ Pages proxy locked to that app reaches. The password comes from
266
+ `AUTH_CRAFT_SMOKE_PASSWORD`, never the command line; `AUTH_CRAFT_SMOKE_GATEWAY_SECRET`
267
+ is sent as `X-Gateway-Secret` if something sits in front of the Worker. It checks, in
268
+ order: `/health` answers with the `PASSWORD_ENGINE` you name (anything else stops the
269
+ run); an undeclared app is refused; a wrong password is `INVALID_CREDENTIALS`, not 503
270
+ (the hasher or the engine is reachable); login; `/auth/me` with and without the token;
271
+ refresh rotates; logout ends the session; a foreign origin is not allowed by CORS. With
272
+ `--cookie`, also: a refresh carrying the cookie from a foreign origin is refused and sets
273
+ no cookie (CSRF), refresh rotates the app's cookie, logout clears it. A run
274
+ leaves one logged-out session and no failed attempt. It prints check names, never
275
+ tokens, passwords or bodies.
276
+
277
+ ## Release gate (auth-craft maintainers)
278
+
279
+ `pnpm verify:release:worker-d1-stack` (run by `publish:worker-d1-stack`) runs
280
+ `pnpm --filter @auth-craft/worker-d1-stack smoke:local` (`scripts/smoke-local.mjs`): for
281
+ each engine mode, `init` → `check` → `migrate --local` → the real `wrangler dev` → `smoke`,
282
+ with a real password engine on localhost for `remote`; a smoke naming the other mode must
283
+ fail. The tenant app refreshes by cookie there: `smoke --cookie --app tenant` must pass
284
+ from an allowed origin and fail from any other. No Cloudflare account is used: releases are not verified against a real deployment.
285
+
286
+ ## What is inside
287
+
288
+ - `assets/worker/worker.js` — the Worker, built by the auth-craft app's own build.
289
+ - `assets/migrations/` — D1 migrations, applied in order, additive.
290
+ - `assets/check/config.mjs` — the Worker's config loader, used by `check`.
291
+ - `assets/data/snapshot.mjs` — the admin CLI's snapshot commands, used by `data`.
292
+ - `assets/sbom/worker.cdx.json`, `assets/sbom/data.cdx.json` — CycloneDX SBOMs of both bundles.
293
+ - `assets/manifest.json` — version, Worker SHA-256, migrations, known variables.
294
+
295
+ Verified locally only, by design: `wrangler deploy --dry-run` with the real wrangler, and
296
+ `smoke` against the packaged Worker under `wrangler dev` in both modes. Run `smoke`
297
+ against your own deployment after each deploy.