@auth-craft/worker-d1-stack 0.1.0 → 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 (57) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/README.md +201 -4
  3. package/assets/check/config.mjs +119 -10
  4. package/assets/data/snapshot.mjs +190 -0
  5. package/assets/engine/dev-engine.mjs +1 -0
  6. package/assets/manifest.json +19 -2
  7. package/assets/sbom/data.cdx.json +1042 -0
  8. package/assets/sbom/worker.cdx.json +26 -8
  9. package/assets/worker/worker.js +56 -56
  10. package/dist/check.d.ts.map +1 -1
  11. package/dist/check.js +3 -0
  12. package/dist/check.js.map +1 -1
  13. package/dist/cli.d.ts +6 -1
  14. package/dist/cli.d.ts.map +1 -1
  15. package/dist/cli.js +262 -4
  16. package/dist/cli.js.map +1 -1
  17. package/dist/commands.d.ts +12 -0
  18. package/dist/commands.d.ts.map +1 -1
  19. package/dist/commands.js +34 -2
  20. package/dist/commands.js.map +1 -1
  21. package/dist/cutover.d.ts +63 -0
  22. package/dist/cutover.d.ts.map +1 -0
  23. package/dist/cutover.js +310 -0
  24. package/dist/cutover.js.map +1 -0
  25. package/dist/data.d.ts +52 -0
  26. package/dist/data.d.ts.map +1 -0
  27. package/dist/data.js +131 -0
  28. package/dist/data.js.map +1 -0
  29. package/dist/dev.d.ts +16 -0
  30. package/dist/dev.d.ts.map +1 -0
  31. package/dist/dev.js +80 -0
  32. package/dist/dev.js.map +1 -0
  33. package/dist/init.d.ts +5 -0
  34. package/dist/init.d.ts.map +1 -1
  35. package/dist/init.js +4 -1
  36. package/dist/init.js.map +1 -1
  37. package/dist/preflight.d.ts +45 -0
  38. package/dist/preflight.d.ts.map +1 -0
  39. package/dist/preflight.js +335 -0
  40. package/dist/preflight.js.map +1 -0
  41. package/dist/secrets-file.d.ts +1 -1
  42. package/dist/secrets-file.d.ts.map +1 -1
  43. package/dist/secrets-file.js +1 -0
  44. package/dist/secrets-file.js.map +1 -1
  45. package/dist/service-token.d.ts +6 -0
  46. package/dist/service-token.d.ts.map +1 -0
  47. package/dist/service-token.js +26 -0
  48. package/dist/service-token.js.map +1 -0
  49. package/dist/smoke.d.ts +11 -0
  50. package/dist/smoke.d.ts.map +1 -1
  51. package/dist/smoke.js +53 -11
  52. package/dist/smoke.js.map +1 -1
  53. package/dist/wrangler-runner.d.ts +8 -0
  54. package/dist/wrangler-runner.d.ts.map +1 -1
  55. package/dist/wrangler-runner.js +17 -0
  56. package/dist/wrangler-runner.js.map +1 -1
  57. package/package.json +12 -4
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
@@ -14,6 +14,8 @@ the auth-craft docs (`docs/CLOUDFLARE_WORKERS_PLAN.md` §6.5).
14
14
  ## Requirements
15
15
 
16
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).
17
19
  - A D1 database: `npx wrangler d1 create auth` (note its id).
18
20
  - Workers Paid for `--password-engine local` (scrypt needs more than the Free 10 ms CPU),
19
21
  or Workers Free with `--password-engine remote` and a password engine (deploy one with
@@ -49,6 +51,12 @@ AUTH_CRAFT_SMOKE_PASSWORD=... npx auth-craft-worker smoke \
49
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. |
50
52
  | `migrate` | `wrangler d1 migrations apply DB --remote` (or `--local`). |
51
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). |
52
60
  | `smoke` | Black-box checks of a running Worker over HTTP (below). Exit 1 if any fails. |
53
61
  | `version` | The packaged version and Worker hash. |
54
62
 
@@ -57,6 +65,188 @@ readable by other users. Secret variables: `JWT_PRIVATE_KEY`, `GATEWAY_SECRET`,
57
65
  `PASSWORD_ENGINE_SIGNING_KEY`, `MFA_SECRET_KEY`, `MFA_SECRET_PREVIOUS_KEYS`,
58
66
  `RESEND_API_KEY`, `RESEND_WEBHOOK_SECRET`, `GOOGLE_CLIENT_SECRET`, `FACEBOOK_CLIENT_SECRET`.
59
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
+
60
250
  ## Email delivery events (Cloudflare Email Service)
61
251
 
62
252
  With `--email-queue` and `EMAIL_PROVIDER=cloudflare`, subscribe the Worker's email queue
@@ -69,13 +259,18 @@ complaining mailbox. Soft bounces and deferrals change nothing.
69
259
  ## Smoke after a deploy
70
260
 
71
261
  `smoke` needs a verified account without MFA on that deployment (create it once and keep
72
- it for smoke runs) and `REFRESH_TOKEN_STRATEGY=body` or `both`. The password comes from
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
73
266
  `AUTH_CRAFT_SMOKE_PASSWORD`, never the command line; `AUTH_CRAFT_SMOKE_GATEWAY_SECRET`
74
267
  is sent as `X-Gateway-Secret` if something sits in front of the Worker. It checks, in
75
268
  order: `/health` answers with the `PASSWORD_ENGINE` you name (anything else stops the
76
269
  run); an undeclared app is refused; a wrong password is `INVALID_CREDENTIALS`, not 503
77
270
  (the hasher or the engine is reachable); login; `/auth/me` with and without the token;
78
- refresh rotates; logout ends the session; a foreign origin is not allowed by CORS. A run
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
79
274
  leaves one logged-out session and no failed attempt. It prints check names, never
80
275
  tokens, passwords or bodies.
81
276
 
@@ -85,14 +280,16 @@ tokens, passwords or bodies.
85
280
  `pnpm --filter @auth-craft/worker-d1-stack smoke:local` (`scripts/smoke-local.mjs`): for
86
281
  each engine mode, `init` → `check` → `migrate --local` → the real `wrangler dev` → `smoke`,
87
282
  with a real password engine on localhost for `remote`; a smoke naming the other mode must
88
- fail. No Cloudflare account is used: releases are not verified against a real deployment.
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.
89
285
 
90
286
  ## What is inside
91
287
 
92
288
  - `assets/worker/worker.js` — the Worker, built by the auth-craft app's own build.
93
289
  - `assets/migrations/` — D1 migrations, applied in order, additive.
94
290
  - `assets/check/config.mjs` — the Worker's config loader, used by `check`.
95
- - `assets/sbom/worker.cdx.json` — CycloneDX SBOM of the Worker bundle.
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.
96
293
  - `assets/manifest.json` — version, Worker SHA-256, migrations, known variables.
97
294
 
98
295
  Verified locally only, by design: `wrangler deploy --dry-run` with the real wrangler, and
@@ -1510,6 +1510,8 @@ var DEFAULTS = {
1510
1510
  ACCESS_TOKEN_LIFETIME_MINUTES: "15",
1511
1511
  REFRESH_TOKEN_LIFETIME_MINUTES: "10080",
1512
1512
  VERIFICATION_CODE_LIFETIME_MINUTES: "10",
1513
+ VERIFICATION_RESEND_COOLDOWN_SECONDS: "60",
1514
+ REFRESH_TOKEN_GRACE_WINDOW_MS: "30000",
1513
1515
  REFRESH_TOKEN_STRATEGY: "body",
1514
1516
  REFRESH_TOKEN_COOKIE_NAME: "refresh_token",
1515
1517
  REFRESH_TOKEN_COOKIE_HTTP_ONLY: "true",
@@ -1537,6 +1539,7 @@ var DEFAULTS = {
1537
1539
  EMAIL_INBOUND_MAX_BYTES: "26214400",
1538
1540
  EMAIL_LOG_RETENTION_DAYS: "30",
1539
1541
  PASSWORD_ENGINE_TIMEOUT_MS: "3000",
1542
+ EMAIL_RELAY_TIMEOUT_MS: "5000",
1540
1543
  FACEBOOK_REDIRECT_URI: "http://localhost:8787/auth/oauth/facebook/callback",
1541
1544
  GOOGLE_REDIRECT_URI: "http://localhost:8787/auth/oauth/google/callback",
1542
1545
  AUDIT_ENABLED: "true",
@@ -1555,6 +1558,11 @@ var EnvReader = class {
1555
1558
  if (typeof value === "string" && value !== "") return value;
1556
1559
  return DEFAULTS[name] ?? "";
1557
1560
  }
1561
+ /** Set by the operator (not a default). */
1562
+ explicit(name) {
1563
+ const value = this.env[name];
1564
+ return typeof value === "string" && value !== "";
1565
+ }
1558
1566
  optional(name) {
1559
1567
  const value = this.str(name);
1560
1568
  return value === "" ? void 0 : value;
@@ -1590,17 +1598,48 @@ var EnvReader = class {
1590
1598
  }
1591
1599
  };
1592
1600
  var normalizePath = (raw) => raw ? (raw.startsWith("/") ? raw : `/${raw}`).replace(/\/+$/, "") : "";
1593
- var PRESET_APP_VARS = ["JWT_CUSTOMER_AUDIENCE", "JWT_TENANT_AUDIENCE", "JWT_SYSTEM_AUDIENCE"];
1601
+ var PRESET_APP_VARS = [
1602
+ "JWT_CUSTOMER_AUDIENCE",
1603
+ "JWT_TENANT_AUDIENCE",
1604
+ "JWT_SYSTEM_AUDIENCE",
1605
+ "TOKEN_AUD_CUSTOMER",
1606
+ "TOKEN_AUD_TENANT",
1607
+ "TOKEN_AUD_SYSTEM",
1608
+ "REFRESH_COOKIE_CUSTOMER",
1609
+ "REFRESH_COOKIE_TENANT",
1610
+ "REFRESH_COOKIE_SYSTEM",
1611
+ "REFRESH_TOKEN_STRATEGY_CUSTOMER",
1612
+ "REFRESH_TOKEN_STRATEGY_TENANT",
1613
+ "REFRESH_TOKEN_STRATEGY_SYSTEM"
1614
+ ];
1615
+ var STRATEGIES2 = ["body", "cookie", "both"];
1616
+ function readRefreshTokenStrategy(r) {
1617
+ const global = r.oneOf("REFRESH_TOKEN_STRATEGY", STRATEGIES2);
1618
+ const perApp = {
1619
+ customer: r.optional("REFRESH_TOKEN_STRATEGY_CUSTOMER"),
1620
+ tenant: r.optional("REFRESH_TOKEN_STRATEGY_TENANT"),
1621
+ system: r.optional("REFRESH_TOKEN_STRATEGY_SYSTEM")
1622
+ };
1623
+ if (Object.values(perApp).every((v) => v === void 0)) return global;
1624
+ const pick = (name, value) => value === void 0 ? global : r.oneOf(name, STRATEGIES2);
1625
+ return {
1626
+ customer: pick("REFRESH_TOKEN_STRATEGY_CUSTOMER", perApp.customer),
1627
+ tenant: pick("REFRESH_TOKEN_STRATEGY_TENANT", perApp.tenant),
1628
+ system: pick("REFRESH_TOKEN_STRATEGY_SYSTEM", perApp.system)
1629
+ };
1630
+ }
1631
+ var usesCookie = (strategy) => (typeof strategy === "string" ? [strategy] : Object.values(strategy)).some((s) => s !== "body");
1594
1632
  function loadWorkerConfig(env) {
1595
1633
  const r = new EnvReader(env);
1596
- const refreshTokenStrategy = r.oneOf("REFRESH_TOKEN_STRATEGY", ["body", "cookie", "both"]);
1634
+ const refreshTokenStrategy = readRefreshTokenStrategy(r);
1597
1635
  const config = {
1598
1636
  nodeEnv: r.oneOf("NODE_ENV", ["production", "staging", "development", "test"]),
1599
1637
  basePath: normalizePath(r.str("APP_BASE_PATH")),
1600
1638
  jwt: {
1601
1639
  algorithm: r.oneOf("JWT_ALGORITHM", ["EdDSA", "HS256", "HS384", "HS512"]),
1602
1640
  privateKey: r.required("JWT_PRIVATE_KEY"),
1603
- publicKey: r.required("JWT_PUBLIC_KEY")
1641
+ publicKey: r.required("JWT_PUBLIC_KEY"),
1642
+ issuer: r.optional("JWT_ISSUER") ?? r.str("AUTH_SYSTEM_NAME")
1604
1643
  },
1605
1644
  auth: {
1606
1645
  systemName: r.str("AUTH_SYSTEM_NAME"),
@@ -1622,6 +1661,8 @@ function loadWorkerConfig(env) {
1622
1661
  lockoutDurationMinutes: r.int("LOCKOUT_DURATION_MINUTES", 1),
1623
1662
  verifySessionOnAuth: r.bool("VERIFY_SESSION_ON_AUTH"),
1624
1663
  systemTenantId: r.str("SYSTEM_TENANT_ID"),
1664
+ refreshTokenGraceWindowMs: r.int("REFRESH_TOKEN_GRACE_WINDOW_MS"),
1665
+ verificationResendCooldownSeconds: r.int("VERIFICATION_RESEND_COOLDOWN_SECONDS"),
1625
1666
  corsOrigins: r.list("CORS_ORIGINS"),
1626
1667
  dynamicOrigins: { enabled: r.bool("CORS_ORIGINS_DYNAMIC"), cacheSeconds: r.int("CORS_ORIGINS_CACHE_SECONDS", 1) },
1627
1668
  gatewaySecret: r.str("GATEWAY_SECRET"),
@@ -1632,10 +1673,11 @@ function loadWorkerConfig(env) {
1632
1673
  email: readEmail(r),
1633
1674
  oauth: {},
1634
1675
  features: { auditEnabled: r.bool("AUDIT_ENABLED"), deviceTracking: r.bool("DEVICE_TRACKING") },
1676
+ maintenance: r.bool("MAINTENANCE_MODE"),
1635
1677
  audit: { store: r.oneOf("AUDIT_STORE", ["log", "d1"]), retentionDays: r.int("AUDIT_RETENTION_DAYS", 1) },
1636
1678
  mfaSecretKeys: readMfaSecretKeys(r, env)
1637
1679
  };
1638
- if (refreshTokenStrategy !== "body") {
1680
+ if (usesCookie(refreshTokenStrategy)) {
1639
1681
  config.auth.refreshTokenCookie = {
1640
1682
  name: r.str("REFRESH_TOKEN_COOKIE_NAME"),
1641
1683
  httpOnly: r.bool("REFRESH_TOKEN_COOKIE_HTTP_ONLY"),
@@ -1646,6 +1688,9 @@ function loadWorkerConfig(env) {
1646
1688
  ...r.optional("REFRESH_TOKEN_COOKIE_DOMAIN") && { domain: r.str("REFRESH_TOKEN_COOKIE_DOMAIN") }
1647
1689
  };
1648
1690
  }
1691
+ if (config.security.refreshTokenGraceWindowMs > 12e4) {
1692
+ r.issues.push("REFRESH_TOKEN_GRACE_WINDOW_MS: at most 120000 (a replayed refresh token works that long)");
1693
+ }
1649
1694
  readAudiencesAndApps(r, config);
1650
1695
  readInternal(r, config);
1651
1696
  readOAuth(r, config);
@@ -1716,10 +1761,18 @@ function readEmail(r) {
1716
1761
  if (mode === "console") return email;
1717
1762
  const raw = r.str("EMAIL_PROVIDER");
1718
1763
  if (raw === "") {
1719
- r.issues.push(`EMAIL_PROVIDER: required with EMAIL_MODE=${mode} (resend | cloudflare)`);
1764
+ r.issues.push(`EMAIL_PROVIDER: required with EMAIL_MODE=${mode} (resend | cloudflare | relay)`);
1765
+ return email;
1766
+ }
1767
+ email.provider = r.oneOf("EMAIL_PROVIDER", ["resend", "cloudflare", "relay"]);
1768
+ if (email.provider === "relay") {
1769
+ email.relay = readRelay(r);
1770
+ const from2 = r.optional("EMAIL_FROM");
1771
+ if (from2 !== void 0 && !EMAIL_FROM.test(from2))
1772
+ r.issues.push('EMAIL_FROM: must be an address or "Name <address>"');
1773
+ email.from = from2 ?? "";
1720
1774
  return email;
1721
1775
  }
1722
- email.provider = r.oneOf("EMAIL_PROVIDER", ["resend", "cloudflare"]);
1723
1776
  if (email.provider === "resend") email.resendApiKey = r.required("RESEND_API_KEY");
1724
1777
  const from = r.required("EMAIL_FROM");
1725
1778
  if (from && !EMAIL_FROM.test(from)) r.issues.push('EMAIL_FROM: must be an address or "Name <address>"');
@@ -1731,6 +1784,29 @@ function readEmail(r) {
1731
1784
  }
1732
1785
  return email;
1733
1786
  }
1787
+ function readRelay(r) {
1788
+ const url = r.required("EMAIL_RELAY_URL");
1789
+ if (url && !/^https:\/\//.test(url) && !/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?(\/|$)/.test(url)) {
1790
+ r.issues.push("EMAIL_RELAY_URL: must be https (sign-in codes travel in the body)");
1791
+ }
1792
+ const signingKey = r.required("EMAIL_RELAY_SIGNING_KEY");
1793
+ if (signingKey) {
1794
+ try {
1795
+ const jwk = JSON.parse(signingKey);
1796
+ if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519" || typeof jwk.d !== "string") {
1797
+ r.issues.push("EMAIL_RELAY_SIGNING_KEY: must be an Ed25519 private JWK");
1798
+ }
1799
+ } catch {
1800
+ r.issues.push("EMAIL_RELAY_SIGNING_KEY: must be JSON (Ed25519 private JWK)");
1801
+ }
1802
+ }
1803
+ return {
1804
+ url,
1805
+ signingKey,
1806
+ issuer: r.optional("EMAIL_RELAY_ISSUER") ?? r.optional("PASSWORD_ENGINE_ISSUER") ?? r.str("AUTH_SYSTEM_NAME"),
1807
+ timeoutMs: r.int("EMAIL_RELAY_TIMEOUT_MS", 100)
1808
+ };
1809
+ }
1734
1810
  function readMfaSecretKeys(r, env) {
1735
1811
  const strings = {};
1736
1812
  for (const name of ["MFA_SECRET_KEY", "MFA_SECRET_KEY_ID", "MFA_SECRET_PREVIOUS_KEYS"]) {
@@ -1744,20 +1820,53 @@ function readMfaSecretKeys(r, env) {
1744
1820
  return null;
1745
1821
  }
1746
1822
  }
1823
+ function readAudience(r, worker, lambda, label) {
1824
+ if (worker !== void 0 && lambda !== void 0 && worker !== lambda)
1825
+ r.issues.push(`${label}: set one (they differ)`);
1826
+ return worker ?? lambda;
1827
+ }
1747
1828
  function readAudiencesAndApps(r, config) {
1748
- const customer = r.optional("JWT_CUSTOMER_AUDIENCE");
1749
- const tenant = r.optional("JWT_TENANT_AUDIENCE");
1750
- const system = r.optional("JWT_SYSTEM_AUDIENCE");
1829
+ const customer = readAudience(
1830
+ r,
1831
+ r.optional("JWT_CUSTOMER_AUDIENCE"),
1832
+ r.optional("TOKEN_AUD_CUSTOMER"),
1833
+ "JWT_CUSTOMER_AUDIENCE / TOKEN_AUD_CUSTOMER"
1834
+ );
1835
+ const tenant = readAudience(
1836
+ r,
1837
+ r.optional("JWT_TENANT_AUDIENCE"),
1838
+ r.optional("TOKEN_AUD_TENANT"),
1839
+ "JWT_TENANT_AUDIENCE / TOKEN_AUD_TENANT"
1840
+ );
1841
+ const system = readAudience(
1842
+ r,
1843
+ r.optional("JWT_SYSTEM_AUDIENCE"),
1844
+ r.optional("TOKEN_AUD_SYSTEM"),
1845
+ "JWT_SYSTEM_AUDIENCE / TOKEN_AUD_SYSTEM"
1846
+ );
1751
1847
  const raw = r.optional("AUTH_APPS");
1752
1848
  const defaultApp = r.optional("AUTH_DEFAULT_APP");
1753
1849
  if (raw === void 0) {
1754
1850
  if (defaultApp !== void 0) r.issues.push("AUTH_DEFAULT_APP: needs AUTH_APPS");
1755
1851
  const audiences = { customer: customer ?? "customer", tenant: tenant ?? "tenant", system: system ?? "system" };
1756
- config.security.tokenAudiences = audiences;
1757
1852
  const values = Object.values(audiences);
1758
1853
  if (new Set(values).size !== values.length) {
1759
1854
  r.issues.push("JWT_CUSTOMER_AUDIENCE / JWT_TENANT_AUDIENCE / JWT_SYSTEM_AUDIENCE: must differ");
1760
1855
  }
1856
+ const cookieNames = {
1857
+ customer: r.optional("REFRESH_COOKIE_CUSTOMER") ?? "refresh_token",
1858
+ tenant: r.optional("REFRESH_COOKIE_TENANT") ?? "refresh_token_tenant",
1859
+ system: r.optional("REFRESH_COOKIE_SYSTEM") ?? "refresh_token_system"
1860
+ };
1861
+ if (new Set(Object.values(cookieNames)).size !== 3) {
1862
+ r.issues.push("REFRESH_COOKIE_CUSTOMER / REFRESH_COOKIE_TENANT / REFRESH_COOKIE_SYSTEM: must differ");
1863
+ }
1864
+ if (r.explicit("REFRESH_TOKEN_COOKIE_NAME")) {
1865
+ r.issues.push(
1866
+ "REFRESH_TOKEN_COOKIE_NAME: not used by the customer / tenant / system apps; set REFRESH_COOKIE_CUSTOMER / _TENANT / _SYSTEM"
1867
+ );
1868
+ }
1869
+ config.security.tokenAudiences = { ...audiences, cookieNames };
1761
1870
  return;
1762
1871
  }
1763
1872
  const mixed = PRESET_APP_VARS.filter((name) => r.optional(name) !== void 0);