toiljs 0.0.116 → 0.0.117

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 (325) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/README.md +16 -7
  3. package/build/backend/.tsbuildinfo +1 -1
  4. package/build/cli/.tsbuildinfo +1 -1
  5. package/build/cli/index.js +2375 -258
  6. package/build/client/.tsbuildinfo +1 -1
  7. package/build/client/dev/devtools.js +1 -1
  8. package/build/client/dev/error-overlay.js +1 -1
  9. package/build/client/routing/mount.js +1 -1
  10. package/build/compiler/.tsbuildinfo +1 -1
  11. package/build/compiler/auth-emails.js +7 -3
  12. package/build/compiler/emails.js +1 -1
  13. package/build/compiler/index.d.ts +1 -0
  14. package/build/compiler/index.js +25 -4
  15. package/build/compiler/pages.js +2 -3
  16. package/build/compiler/prerender.d.ts +3 -8
  17. package/build/compiler/prerender.js +88 -127
  18. package/build/compiler/ssg.js +3 -4
  19. package/build/compiler/template-build.js +3 -4
  20. package/build/compiler/toil-docs.generated.js +6 -5
  21. package/build/compiler/vite.js +3 -6
  22. package/build/devserver/.tsbuildinfo +1 -1
  23. package/build/devserver/db/database.js +7 -3
  24. package/build/devserver/db/types.js +1 -1
  25. package/build/devserver/production.js +4 -3
  26. package/build/devserver/runtime/crypto.d.ts +1 -1
  27. package/build/io/.tsbuildinfo +1 -1
  28. package/build/logger/.tsbuildinfo +1 -1
  29. package/build/shared/.tsbuildinfo +1 -1
  30. package/examples/basic/client/routes/analytics.tsx +7 -5
  31. package/examples/basic/server/tsconfig.json +1 -3
  32. package/package.json +45 -44
  33. package/presets/no-uint8array-tostring.js +120 -153
  34. package/presets/oxlint.d.ts +5 -0
  35. package/presets/oxlint.js +224 -0
  36. package/server/runtime/tsconfig.json +1 -3
  37. package/tsconfig.json +2 -11
  38. package/.github/ISSUE_TEMPLATE/bug_report.md +0 -38
  39. package/.github/ISSUE_TEMPLATE/bug_report.yml +0 -90
  40. package/.github/ISSUE_TEMPLATE/config.yml +0 -8
  41. package/.github/ISSUE_TEMPLATE/feature_request.md +0 -20
  42. package/.github/PULL_REQUEST_TEMPLATE.md +0 -43
  43. package/.github/changelog-config.json +0 -45
  44. package/.github/dependabot.yml +0 -27
  45. package/.github/workflows/ci.yml +0 -222
  46. package/.vscode/settings.json +0 -10
  47. package/docs/README.md +0 -107
  48. package/docs/auth/README.md +0 -104
  49. package/docs/auth/configuration.md +0 -105
  50. package/docs/auth/emails.md +0 -92
  51. package/docs/auth/extending.md +0 -202
  52. package/docs/auth/how-it-works.md +0 -138
  53. package/docs/auth/usage.md +0 -188
  54. package/docs/backend/README.md +0 -143
  55. package/docs/backend/data.md +0 -351
  56. package/docs/backend/rest.md +0 -402
  57. package/docs/backend/rpc.md +0 -226
  58. package/docs/background/README.md +0 -114
  59. package/docs/background/daemons.md +0 -276
  60. package/docs/background/derive.md +0 -179
  61. package/docs/cli/README.md +0 -379
  62. package/docs/concepts/ai-guide.md +0 -132
  63. package/docs/concepts/config.md +0 -416
  64. package/docs/concepts/decorators.md +0 -127
  65. package/docs/concepts/security.md +0 -108
  66. package/docs/concepts/tiers.md +0 -166
  67. package/docs/concepts/types.md +0 -216
  68. package/docs/database/README.md +0 -143
  69. package/docs/database/capacity.md +0 -350
  70. package/docs/database/counters.md +0 -174
  71. package/docs/database/documents.md +0 -277
  72. package/docs/database/events.md +0 -307
  73. package/docs/database/membership.md +0 -246
  74. package/docs/database/setup.md +0 -155
  75. package/docs/database/unique.md +0 -216
  76. package/docs/database/views.md +0 -246
  77. package/docs/frontend/README.md +0 -104
  78. package/docs/frontend/components.md +0 -286
  79. package/docs/frontend/data-fetching.md +0 -260
  80. package/docs/frontend/images.md +0 -148
  81. package/docs/frontend/metadata.md +0 -344
  82. package/docs/frontend/navigation.md +0 -296
  83. package/docs/frontend/rendering.md +0 -236
  84. package/docs/frontend/routing.md +0 -346
  85. package/docs/frontend/scripts.md +0 -118
  86. package/docs/frontend/search.md +0 -191
  87. package/docs/frontend/styling.md +0 -147
  88. package/docs/frontend/toil-global.md +0 -216
  89. package/docs/getting-started/README.md +0 -81
  90. package/docs/getting-started/create-project.md +0 -131
  91. package/docs/getting-started/deploy.md +0 -101
  92. package/docs/getting-started/first-app.md +0 -215
  93. package/docs/getting-started/installation.md +0 -124
  94. package/docs/getting-started/migrating.md +0 -125
  95. package/docs/getting-started/project-structure.md +0 -163
  96. package/docs/introduction/README.md +0 -66
  97. package/docs/introduction/design-principles.md +0 -81
  98. package/docs/introduction/distributed.md +0 -91
  99. package/docs/introduction/how-it-works.md +0 -121
  100. package/docs/introduction/hyperscale.md +0 -70
  101. package/docs/introduction/modern-stack.md +0 -85
  102. package/docs/introduction/vs-other-frameworks.md +0 -64
  103. package/docs/introduction/why-toil.md +0 -99
  104. package/docs/llms.txt +0 -95
  105. package/docs/realtime/README.md +0 -102
  106. package/docs/realtime/channels.md +0 -211
  107. package/docs/realtime/streams.md +0 -369
  108. package/docs/services/README.md +0 -60
  109. package/docs/services/analytics.md +0 -279
  110. package/docs/services/caching.md +0 -175
  111. package/docs/services/cookies.md +0 -235
  112. package/docs/services/crypto.md +0 -209
  113. package/docs/services/email.md +0 -289
  114. package/docs/services/environment.md +0 -141
  115. package/docs/services/ratelimit.md +0 -174
  116. package/docs/services/time.md +0 -85
  117. package/eslint.config.js +0 -57
  118. package/examples/basic/client/routes/docs/[...slug].tsx +0 -12
  119. package/presets/eslint.js +0 -88
  120. package/src/backend/index.ts +0 -204
  121. package/src/cli/configure.ts +0 -363
  122. package/src/cli/create.ts +0 -924
  123. package/src/cli/db.ts +0 -158
  124. package/src/cli/diagnostics.ts +0 -665
  125. package/src/cli/doctor.ts +0 -982
  126. package/src/cli/features.ts +0 -170
  127. package/src/cli/index.ts +0 -326
  128. package/src/cli/notify.ts +0 -120
  129. package/src/cli/proc.ts +0 -56
  130. package/src/cli/ui.ts +0 -169
  131. package/src/cli/update.ts +0 -248
  132. package/src/cli/updates.ts +0 -92
  133. package/src/cli/validate.ts +0 -31
  134. package/src/cli/version-check.ts +0 -125
  135. package/src/client/auth.ts +0 -869
  136. package/src/client/channel/channel.ts +0 -146
  137. package/src/client/components/Form.tsx +0 -65
  138. package/src/client/components/Image.tsx +0 -160
  139. package/src/client/components/Script.tsx +0 -113
  140. package/src/client/components/Slot.tsx +0 -21
  141. package/src/client/dev/devtools.tsx +0 -1089
  142. package/src/client/dev/error-overlay.tsx +0 -225
  143. package/src/client/errors.ts +0 -11
  144. package/src/client/head/head.ts +0 -182
  145. package/src/client/head/metadata.ts +0 -110
  146. package/src/client/index.ts +0 -130
  147. package/src/client/navigation/Link.tsx +0 -108
  148. package/src/client/navigation/NavLink.tsx +0 -86
  149. package/src/client/navigation/navigation.ts +0 -235
  150. package/src/client/navigation/prefetch.ts +0 -169
  151. package/src/client/navigation/scroll.ts +0 -53
  152. package/src/client/routing/Router.tsx +0 -216
  153. package/src/client/routing/action.ts +0 -122
  154. package/src/client/routing/error-boundary.tsx +0 -43
  155. package/src/client/routing/hooks.ts +0 -140
  156. package/src/client/routing/lazy.ts +0 -77
  157. package/src/client/routing/loader.ts +0 -381
  158. package/src/client/routing/match.ts +0 -47
  159. package/src/client/routing/mount.tsx +0 -90
  160. package/src/client/routing/params-context.ts +0 -10
  161. package/src/client/routing/slot-context.ts +0 -7
  162. package/src/client/rpc.ts +0 -97
  163. package/src/client/search/search.ts +0 -189
  164. package/src/client/search/use-page-search.ts +0 -73
  165. package/src/client/ssr/markers.tsx +0 -172
  166. package/src/client/stream/client.ts +0 -237
  167. package/src/client/types.ts +0 -73
  168. package/src/compiler/auth-emails.ts +0 -312
  169. package/src/compiler/config.ts +0 -369
  170. package/src/compiler/docs.ts +0 -127
  171. package/src/compiler/email-preview.ts +0 -314
  172. package/src/compiler/emails.ts +0 -404
  173. package/src/compiler/fonts.ts +0 -89
  174. package/src/compiler/generate.ts +0 -471
  175. package/src/compiler/image-blur.ts +0 -42
  176. package/src/compiler/image-report.ts +0 -88
  177. package/src/compiler/index.ts +0 -1362
  178. package/src/compiler/pages.ts +0 -49
  179. package/src/compiler/plugin.ts +0 -391
  180. package/src/compiler/prerender.ts +0 -263
  181. package/src/compiler/routes.ts +0 -170
  182. package/src/compiler/seo.ts +0 -415
  183. package/src/compiler/sri.ts +0 -144
  184. package/src/compiler/ssg.ts +0 -177
  185. package/src/compiler/ssr-codegen.ts +0 -85
  186. package/src/compiler/template-build.ts +0 -676
  187. package/src/compiler/template.ts +0 -262
  188. package/src/compiler/toil-docs.generated.ts +0 -77
  189. package/src/compiler/vite.ts +0 -245
  190. package/src/devserver/analytics/index.ts +0 -317
  191. package/src/devserver/config/dotenv.ts +0 -102
  192. package/src/devserver/config/env.ts +0 -30
  193. package/src/devserver/config/ratelimit.ts +0 -123
  194. package/src/devserver/daemon/catalog.ts +0 -120
  195. package/src/devserver/daemon/cron.ts +0 -87
  196. package/src/devserver/daemon/host.ts +0 -134
  197. package/src/devserver/daemon/index.ts +0 -369
  198. package/src/devserver/daemon/runtime.ts +0 -48
  199. package/src/devserver/db/catalog.ts +0 -109
  200. package/src/devserver/db/database.ts +0 -1834
  201. package/src/devserver/db/derives.ts +0 -121
  202. package/src/devserver/db/index.ts +0 -20
  203. package/src/devserver/db/routeKinds.ts +0 -191
  204. package/src/devserver/db/types.ts +0 -168
  205. package/src/devserver/email/caps.ts +0 -0
  206. package/src/devserver/email/config.ts +0 -141
  207. package/src/devserver/email/console.ts +0 -348
  208. package/src/devserver/email/index.ts +0 -155
  209. package/src/devserver/email/providers.ts +0 -131
  210. package/src/devserver/email/status.ts +0 -23
  211. package/src/devserver/email/validate.ts +0 -37
  212. package/src/devserver/email/wire.ts +0 -55
  213. package/src/devserver/http/cache.ts +0 -0
  214. package/src/devserver/http/envelope.ts +0 -157
  215. package/src/devserver/http/proxy.ts +0 -172
  216. package/src/devserver/http/runtime.ts +0 -387
  217. package/src/devserver/index.ts +0 -43
  218. package/src/devserver/production-ipc.ts +0 -63
  219. package/src/devserver/production-worker.ts +0 -83
  220. package/src/devserver/production.ts +0 -718
  221. package/src/devserver/runtime/crypto.ts +0 -587
  222. package/src/devserver/runtime/host.ts +0 -427
  223. package/src/devserver/runtime/module.ts +0 -442
  224. package/src/devserver/server.ts +0 -251
  225. package/src/devserver/ssr.ts +0 -208
  226. package/src/devserver/stream/catalog.ts +0 -106
  227. package/src/devserver/stream/host.ts +0 -42
  228. package/src/devserver/stream/index.ts +0 -301
  229. package/src/devserver/stream/manager.ts +0 -167
  230. package/src/devserver/stream/router.ts +0 -101
  231. package/src/devserver/stream/wire.ts +0 -58
  232. package/src/devserver/stream/ws.ts +0 -78
  233. package/src/devserver/wasm/sections.ts +0 -59
  234. package/src/devserver/wasm/surface.ts +0 -115
  235. package/src/io/FastMap.ts +0 -151
  236. package/src/io/FastSet.ts +0 -113
  237. package/src/io/codec.ts +0 -362
  238. package/src/io/index.ts +0 -10
  239. package/src/io/lengths.ts +0 -14
  240. package/src/io/types.ts +0 -19
  241. package/src/logger/index.ts +0 -22
  242. package/src/shared/index.ts +0 -46
  243. package/test/analytics-dev.test.ts +0 -113
  244. package/test/assembly/aspect-shim.ts +0 -33
  245. package/test/assembly/cookie.spec.ts +0 -303
  246. package/test/assembly/example.spec.ts +0 -22
  247. package/test/assembly/ssr.spec.ts +0 -95
  248. package/test/assembly.test.ts +0 -59
  249. package/test/auth-emails.test.ts +0 -118
  250. package/test/built-ssr.test.ts +0 -148
  251. package/test/channel.test.ts +0 -21
  252. package/test/config-host-port.test.ts +0 -59
  253. package/test/configure.test.ts +0 -94
  254. package/test/daemon-build.test.ts +0 -278
  255. package/test/daemon-catalog.test.ts +0 -349
  256. package/test/daemon-emulation.test.ts +0 -256
  257. package/test/db.test.ts +0 -0
  258. package/test/devserver-database.test.ts +0 -1102
  259. package/test/devserver-email.test.ts +0 -306
  260. package/test/devserver-pqauth.test.ts +0 -93
  261. package/test/devserver-secrets.test.ts +0 -63
  262. package/test/devserver.test.ts +0 -259
  263. package/test/doctor.test.ts +0 -298
  264. package/test/dom/Image.test.tsx +0 -144
  265. package/test/dom/Link.test.tsx +0 -67
  266. package/test/dom/NavLink.test.tsx +0 -37
  267. package/test/dom/Script.test.tsx +0 -48
  268. package/test/dom/action.test.tsx +0 -146
  269. package/test/dom/error-overlay.test.tsx +0 -44
  270. package/test/dom/loader.test.tsx +0 -121
  271. package/test/dom/navigation.test.ts +0 -59
  272. package/test/dom/revalidate.test.tsx +0 -38
  273. package/test/dom/route-head.test.tsx +0 -56
  274. package/test/dom/router-loading.test.tsx +0 -44
  275. package/test/dom/scroll.test.ts +0 -56
  276. package/test/dom/slot.test.tsx +0 -131
  277. package/test/dom/use-metadata.test.tsx +0 -58
  278. package/test/dom/view-transitions.test.tsx +0 -53
  279. package/test/dynamic-routing.test.ts +0 -132
  280. package/test/email-console.test.ts +0 -86
  281. package/test/email-preview.test.ts +0 -73
  282. package/test/emails.test.ts +0 -58
  283. package/test/errors.test.ts +0 -21
  284. package/test/example-guestbook.test.ts +0 -123
  285. package/test/features.test.ts +0 -149
  286. package/test/fixtures/bignum-wire/spec.ts +0 -25
  287. package/test/fixtures/daemon-app.ts +0 -65
  288. package/test/fixtures/stream-echo.ts +0 -26
  289. package/test/fixtures/stream-gate.ts +0 -28
  290. package/test/fixtures/stream-trap.ts +0 -18
  291. package/test/fixtures/stream-typed.ts +0 -41
  292. package/test/fonts.test.ts +0 -28
  293. package/test/global-setup.ts +0 -17
  294. package/test/head.test.ts +0 -42
  295. package/test/image-blur.test.ts +0 -50
  296. package/test/io.test.ts +0 -117
  297. package/test/metadata.test.ts +0 -40
  298. package/test/navlink.test.ts +0 -28
  299. package/test/pages.test.ts +0 -105
  300. package/test/placeholder.test.ts +0 -9
  301. package/test/pqauth-e2e.test.ts +0 -216
  302. package/test/pqauth-email.test.ts +0 -801
  303. package/test/prerender.test.ts +0 -116
  304. package/test/prettier-plugin.test.ts +0 -46
  305. package/test/routes.test.ts +0 -76
  306. package/test/rpc-bignum-wire.test.ts +0 -164
  307. package/test/rpc-dispatch.test.ts +0 -132
  308. package/test/rpc-kinds.test.ts +0 -18
  309. package/test/rpc.test.ts +0 -66
  310. package/test/search.test.ts +0 -114
  311. package/test/seo.test.ts +0 -175
  312. package/test/slot-layouts.test.ts +0 -69
  313. package/test/sri.test.ts +0 -129
  314. package/test/ssg.test.ts +0 -36
  315. package/test/ssr-hydration.test.tsx +0 -122
  316. package/test/ssr-render.test.ts +0 -197
  317. package/test/ssr-template.test.tsx +0 -482
  318. package/test/stream-emulation.test.ts +0 -479
  319. package/test/ui.test.ts +0 -40
  320. package/test/update.test.ts +0 -58
  321. package/test/validate.test.ts +0 -42
  322. package/test/version-check.test.ts +0 -130
  323. package/tests/data-parity/generated-parity.ts +0 -99
  324. package/tests/data-parity/parity.ts +0 -80
  325. package/tests/data-parity/spec.ts +0 -46
@@ -1,801 +0,0 @@
1
- /**
2
- * End-to-end email-verification + password-reset for the BUILT-IN auth controller
3
- * (`server/auth/AuthController.ts`, mounted into `examples/basic` via
4
- * `server: { auth: true }`). Drives the REAL browser client (`src/client/auth.ts`)
5
- * against the toilscript-compiled example wasm through the same fetch-shim harness
6
- * as `pqauth-e2e.test.ts`: a `fetch` shim routes the client's requests into
7
- * `WasmServerModule.dispatch`, and the in-process dev ToilDB persists across
8
- * dispatches so a register -> login -> confirm/reset flow spans "requests".
9
- *
10
- * The confirm/reset one-time tokens are only delivered by email, so this reads
11
- * them out of the dev email-capture seam (`__sentEmails`) and regexes the token
12
- * from the emitted link. Confirmation is toggled per case via the plain env var
13
- * the controller reads (`AUTH_REQUIRE_EMAIL_CONFIRMATION`), set through
14
- * `process.env` + a dev env-cache clear.
15
- */
16
- import fs from 'node:fs';
17
- import path from 'node:path';
18
- import { fileURLToPath } from 'node:url';
19
-
20
- import { describe, expect, it, beforeEach, afterEach } from 'vitest';
21
-
22
- import { WasmServerModule } from '../src/devserver/index.js';
23
- import { __resetDbForTests } from '../src/devserver/db/index.js';
24
- import { __resetRatelimitForTests } from '../src/devserver/config/ratelimit.js';
25
- import { clearEnvCache } from '../src/devserver/config/dotenv.js';
26
- import { __sentEmails, __clearSentEmails } from '../src/devserver/email/index.js';
27
- import {
28
- Auth,
29
- AuthErrorCode,
30
- checkPassword,
31
- EmailInUseError,
32
- EmailNotConfirmedError,
33
- InvalidEmailError,
34
- InvalidUsernameError,
35
- isValidEmail,
36
- TwoFactorRequiredError,
37
- WeakPasswordError,
38
- } from '../src/client/auth.js';
39
- import { DataReader, DataWriter } from '../src/io/codec.js';
40
-
41
- const EXAMPLE_WASM = path.resolve(
42
- path.dirname(fileURLToPath(import.meta.url)),
43
- '../examples/basic/build/server/release.wasm',
44
- );
45
-
46
- const haveWasm = fs.existsSync(EXAMPLE_WASM);
47
-
48
- function loadModule(): WasmServerModule {
49
- const m = new WasmServerModule(EXAMPLE_WASM);
50
- m.refresh();
51
- return m;
52
- }
53
-
54
- /** Route the client's `fetch(path, {body})` into the dev wasm dispatcher (with a cookie jar).
55
- * The Host header the client's requests carry is settable (`setHost`) so a test can drive
56
- * the same client against DIFFERENT tenant domains and prove per-host auth isolation. */
57
- function installFetchShim(m: WasmServerModule): () => void {
58
- const original = globalThis.fetch;
59
- const jar = new Map<string, string>();
60
- let host = 'localhost:3000';
61
- globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
62
- const url = typeof input === 'string' ? input : input.toString();
63
- const pathname = new URL(url, 'http://localhost').pathname;
64
- const bodyBytes =
65
- init?.body == null ? new Uint8Array(0) : new Uint8Array(init.body as ArrayBuffer);
66
- const headers: [string, string][] = [
67
- ['host', host],
68
- ['content-type', 'application/octet-stream'],
69
- ];
70
- if (jar.size > 0)
71
- headers.push(['cookie', [...jar.entries()].map(([k, v]) => `${k}=${v}`).join('; ')]);
72
- const r = m.dispatch({
73
- method: (init?.method ?? 'GET') as 'GET' | 'POST',
74
- path: pathname,
75
- headers,
76
- body: bodyBytes,
77
- });
78
- for (const [name, value] of r.headers) {
79
- if (name.toLowerCase() !== 'set-cookie') continue;
80
- const pair = value.split(';', 1)[0];
81
- const eq = pair.indexOf('=');
82
- if (eq > 0) jar.set(pair.slice(0, eq).trim(), pair.slice(eq + 1).trim());
83
- }
84
- const ab = r.body.buffer.slice(r.body.byteOffset, r.body.byteOffset + r.body.byteLength);
85
- return {
86
- ok: r.status >= 200 && r.status < 300,
87
- status: r.status,
88
- arrayBuffer: async () => ab,
89
- text: async () => Buffer.from(r.body).toString('utf8'),
90
- } as Response;
91
- }) as typeof fetch;
92
- return {
93
- restore: () => {
94
- globalThis.fetch = original;
95
- },
96
- jar,
97
- setHost: (h: string) => {
98
- host = h;
99
- },
100
- };
101
- }
102
-
103
- const CONFIRM_ENV = 'AUTH_REQUIRE_EMAIL_CONFIRMATION';
104
-
105
- /** Toggle the domain's email-confirmation requirement the way the dev env store exposes plain vars:
106
- * set/unset the `process.env` var, then drop the cached env snapshot so the next `Environment.get`
107
- * (a per-dispatch host call) re-reads it. */
108
- function setConfirmation(on: boolean): void {
109
- if (on) process.env[CONFIRM_ENV] = 'true';
110
- else delete process.env[CONFIRM_ENV];
111
- clearEnvCache();
112
- }
113
-
114
- const EMAIL_CONFIRM_ENV = 'AUTH_EMAIL_CONFIRMATION';
115
-
116
- /** Toggle "send a verify email at register but DO NOT block login" (the decoupled flag). */
117
- function setEmailConfirmation(on: boolean): void {
118
- if (on) process.env[EMAIL_CONFIRM_ENV] = 'true';
119
- else delete process.env[EMAIL_CONFIRM_ENV];
120
- clearEnvCache();
121
- }
122
-
123
- function hexToBytes(hex: string): Uint8Array {
124
- const out = new Uint8Array(hex.length / 2);
125
- for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
126
- return out;
127
- }
128
-
129
- /** Pull the one-time token out of the most-recent captured confirm/reset email to `to`. */
130
- function tokenFromEmail(kind: 'confirm' | 'reset', to: string): string {
131
- // Tokens live in the URL FRAGMENT now (#token=), kept out of server/CDN logs.
132
- const re = kind === 'confirm' ? /\/confirm#token=([0-9a-f]+)/ : /\/reset#token=([0-9a-f]+)/;
133
- for (let i = __sentEmails.length - 1; i >= 0; i--) {
134
- const msg = __sentEmails[i];
135
- if (msg.to !== to) continue;
136
- const hit = re.exec(msg.text) ?? re.exec(msg.html);
137
- if (hit) return hit[1];
138
- }
139
- throw new Error(
140
- `no ${kind} token emailed to ${to}; captured=${JSON.stringify(
141
- __sentEmails.map((e) => ({ to: e.to, purpose: e.purpose })),
142
- )}`,
143
- );
144
- }
145
-
146
- /** Pull the 6-digit code out of the most-recent captured 2FA email (purpose `2fa`) to `to`. */
147
- function codeFromEmail(to: string): string {
148
- for (let i = __sentEmails.length - 1; i >= 0; i--) {
149
- const msg = __sentEmails[i];
150
- if (msg.to !== to || msg.purpose !== '2fa') continue;
151
- const hit = /\b(\d{6})\b/.exec(msg.text) ?? /\b(\d{6})\b/.exec(msg.html);
152
- if (hit) return hit[1];
153
- }
154
- throw new Error(
155
- `no 2fa code emailed to ${to}; captured=${JSON.stringify(
156
- __sentEmails.map((e) => ({ to: e.to, purpose: e.purpose })),
157
- )}`,
158
- );
159
- }
160
-
161
- describe.skipIf(!haveWasm)('built-in auth: email verification + password reset (client <-> example wasm)', () => {
162
- let restoreFetch: () => void;
163
- let mod: WasmServerModule;
164
- let jar: Map<string, string>;
165
- let setHost: (h: string) => void;
166
-
167
- beforeEach(() => {
168
- __resetDbForTests();
169
- // The controller decorates every route with `@ratelimit`; the dev limiter is a module
170
- // singleton, so reset it per case to keep the many dispatches across this file isolated.
171
- __resetRatelimitForTests();
172
- __clearSentEmails();
173
- setConfirmation(false); // default: confirmation off unless a case opts in
174
- setEmailConfirmation(false);
175
- mod = loadModule();
176
- const shim = installFetchShim(mod);
177
- restoreFetch = shim.restore;
178
- jar = shim.jar;
179
- setHost = shim.setHost;
180
- });
181
- afterEach(() => {
182
- restoreFetch();
183
- setConfirmation(false);
184
- setEmailConfirmation(false);
185
- });
186
-
187
- it(
188
- 'confirmation OFF (default): register auto-confirms, login succeeds, /auth/me returns the user',
189
- async () => {
190
- await Auth.register('ada', 'correct horse battery stapleA1', 'ada@example.com');
191
- const session = await Auth.login('ada', 'correct horse battery stapleA1');
192
- expect(session.length).toBeGreaterThan(0);
193
-
194
- // The controller's `@auth`-gated /auth/me returns bytes(toilUserId) str(username).
195
- const meRes = await fetch('/auth/me');
196
- expect(meRes.status).toBe(200);
197
- const me = new DataReader(new Uint8Array(await meRes.arrayBuffer()));
198
- expect(me.readBytes().length).toBeGreaterThan(0); // stable toilUserId
199
- expect(me.readString()).toBe('ada');
200
-
201
- // No confirmation required -> no email was sent.
202
- expect(__sentEmails.length).toBe(0);
203
- },
204
- 60_000,
205
- );
206
-
207
- // ---- security regressions ----
208
-
209
- it(
210
- 'reset link is NOT poisonable via a crafted Host header (#6 host-header reset-poisoning)',
211
- async () => {
212
- // grace lives on the victim tenant (realm = normalized Host "victim.com").
213
- setHost('victim.com');
214
- await Auth.register('grace', 'pw-grace-correctA1', 'grace@x.com');
215
- __clearSentEmails();
216
- // Attacker triggers reset/request with a Host that routes to the victim
217
- // (the edge strip_port -> "victim.com", which is grace's realm, so the
218
- // request DOES resolve her account) but, dropped raw into a link,
219
- // reparents the URL authority to attacker.com.
220
- const body = new DataWriter().writeString('grace@x.com').toBytes();
221
- const r = mod.dispatch({
222
- method: 'POST',
223
- path: '/auth/reset/request',
224
- headers: [
225
- ['host', 'victim.com:@attacker.com'],
226
- ['content-type', 'application/octet-stream'],
227
- ],
228
- body,
229
- });
230
- expect(r.status).toBe(200); // always the generic non-enumerating ack
231
- const msg = __sentEmails.find((e) => e.to === 'grace@x.com');
232
- expect(msg).toBeTruthy();
233
- // The poisoned Host is rejected (contains `@`) and the link falls back to
234
- // a safe origin -> the attacker domain never appears in the emailed link.
235
- expect((msg!.html + msg!.text).includes('attacker.com')).toBe(false);
236
- },
237
- 60_000,
238
- );
239
-
240
- it(
241
- 'a session minted for one tenant does NOT verify for another (#2 cross-tenant session)',
242
- async () => {
243
- await Auth.register('heidi', 'pw-heidi-correctA1', 'heidi@x.com');
244
- await Auth.login('heidi', 'pw-heidi-correctA1'); // minted under the shim Host localhost:3000
245
- const sess = jar.get('toil_sess'); // dev is plain HTTP -> unprefixed cookie
246
- expect(sess).toBeTruthy();
247
- const meHeaders = (host: string): [string, string][] => [
248
- ['host', host],
249
- ['cookie', 'toil_sess=' + String(sess)],
250
- ];
251
- // Same tenant (localhost) -> the @auth-gated /auth/me accepts it.
252
- const same = mod.dispatch({
253
- method: 'GET',
254
- path: '/auth/me',
255
- headers: meHeaders('localhost:3000'),
256
- body: new Uint8Array(0),
257
- });
258
- expect(same.status).toBe(200);
259
- // A DIFFERENT tenant Host derives a different session key -> the same
260
- // cookie fails to open -> 401. A B-minted session cannot bypass A.
261
- const cross = mod.dispatch({
262
- method: 'GET',
263
- path: '/auth/me',
264
- headers: meHeaders('evil-tenant.com'),
265
- body: new Uint8Array(0),
266
- });
267
- expect(cross.status).toBe(401);
268
- },
269
- 60_000,
270
- );
271
-
272
- it(
273
- 'token bound: a new reset request invalidates the previous token (#5c growth bound)',
274
- async () => {
275
- await Auth.register('ivan', 'pw-ivan-correctA1', 'ivan@x.com');
276
- await Auth.requestPasswordReset('ivan@x.com');
277
- const token1 = tokenFromEmail('reset', 'ivan@x.com');
278
- __clearSentEmails();
279
- await Auth.requestPasswordReset('ivan@x.com'); // mints token2, invalidates token1
280
- const token2 = tokenFromEmail('reset', 'ivan@x.com');
281
- expect(token2).not.toBe(token1);
282
- // The superseded token no longer works...
283
- await expect(Auth.resetPassword(token1, 'new-pw-unusedA1')).rejects.toThrow();
284
- // ...only the latest does.
285
- await Auth.resetPassword(token2, 'new-pw-ivanA1');
286
- const session = await Auth.login('ivan', 'new-pw-ivanA1');
287
- expect(session.length).toBeGreaterThan(0);
288
- },
289
- 60_000,
290
- );
291
-
292
- it(
293
- 'confirmation ON: login is refused until the emailed token confirms the account',
294
- async () => {
295
- setConfirmation(true);
296
- await Auth.register('bob', 'hunter2-correctA1', 'bob@example.com');
297
-
298
- // A valid credential is not enough: the domain requires a confirmed email.
299
- await expect(Auth.login('bob', 'hunter2-correctA1')).rejects.toThrow(EmailNotConfirmedError);
300
-
301
- // Read the confirm link out of the captured email and confirm.
302
- const token = tokenFromEmail('confirm', 'bob@example.com');
303
- await Auth.confirmEmail(token);
304
-
305
- // Now login succeeds.
306
- const session = await Auth.login('bob', 'hunter2-correctA1');
307
- expect(session.length).toBeGreaterThan(0);
308
- },
309
- 60_000,
310
- );
311
-
312
- it(
313
- 'duplicate email is rejected at registration (distinct "email already in use")',
314
- async () => {
315
- await Auth.register('carol', 'carol-pw-strongA1', 'dupe@x.com');
316
- // Typed error: a distinct EmailInUseError carrying the stable code, so a UI can
317
- // branch reliably (never on the message/name string).
318
- const err = await Auth.register('dave', 'dave-pw-strongA1', 'dupe@x.com').catch(
319
- (e: unknown) => e,
320
- );
321
- expect(err).toBeInstanceOf(EmailInUseError);
322
- expect((err as EmailInUseError).code).toBe(AuthErrorCode.EmailInUse);
323
- },
324
- 60_000,
325
- );
326
-
327
- it(
328
- 'password reset round trip: old password stops working, the new one logs in',
329
- async () => {
330
- await Auth.register('erin', 'oldpw-erin-strongA1', 'erin@x.com');
331
- // Sanity: confirmation is off, so she can log in before the reset.
332
- expect((await Auth.login('erin', 'oldpw-erin-strongA1')).length).toBeGreaterThan(0);
333
-
334
- await Auth.requestPasswordReset('erin@x.com');
335
- const token = tokenFromEmail('reset', 'erin@x.com');
336
- await Auth.resetPassword(token, 'newpw-erin-strongA1');
337
-
338
- await expect(Auth.login('erin', 'oldpw-erin-strongA1')).rejects.toThrow(
339
- /login failed|request failed/,
340
- );
341
- expect((await Auth.login('erin', 'newpw-erin-strongA1')).length).toBeGreaterThan(0);
342
- },
343
- 60_000,
344
- );
345
-
346
- it(
347
- 'non-enumeration: reset/resend for an unknown email resolve and send NOTHING',
348
- async () => {
349
- __clearSentEmails();
350
- await expect(Auth.requestPasswordReset('nobody@x.com')).resolves.toBeUndefined();
351
- await expect(Auth.resendConfirmation('nobody@x.com')).resolves.toBeUndefined();
352
- expect(__sentEmails.length).toBe(0);
353
- },
354
- 60_000,
355
- );
356
-
357
- it(
358
- 'a reset token is one-time: replaying /auth/reset/finish with the consumed token fails',
359
- async () => {
360
- await Auth.register('frank', 'oldpw-frank-strongA1', 'frank@x.com');
361
- await Auth.requestPasswordReset('frank@x.com');
362
- const tokenHex = tokenFromEmail('reset', 'frank@x.com');
363
- await Auth.resetPassword(tokenHex, 'newpw-frank-strongA1'); // consumes the token
364
-
365
- // Replay reset/finish with a valid-length pk/proof so the controller reaches the
366
- // token-consume step, which now finds the token already deleted -> generic fail.
367
- const body = new DataWriter()
368
- .writeBytes(hexToBytes(tokenHex))
369
- .writeBytes(new Uint8Array(1312)) // AuthService.PUBLIC_KEY_LEN (ML-DSA-44)
370
- .writeBytes(new Uint8Array(2420)) // AuthService.SIGNATURE_LEN
371
- .toBytes();
372
- const r = mod.dispatch({
373
- method: 'POST',
374
- path: '/auth/reset/finish',
375
- headers: [
376
- ['host', 'localhost:3000'],
377
- ['content-type', 'application/octet-stream'],
378
- ],
379
- body,
380
- });
381
- expect(r.status).not.toBe(200);
382
- },
383
- 60_000,
384
- );
385
-
386
- // ---- multi-method 2FA (email) ----
387
-
388
- it(
389
- '(a) full email-2FA login round-trip: enable, login requires a code, verify mints the session',
390
- async () => {
391
- await Auth.register('dave', 'dave-pw-strongA1', 'dave@x.com');
392
- await Auth.login('dave', 'dave-pw-strongA1'); // 2FA off -> session
393
-
394
- // Enable email 2FA: setup delivers a code, confirm switches the method on.
395
- await Auth.setupTwoFactor(Auth.TwoFactorMethod.Email);
396
- await Auth.confirmTwoFactorSetup(codeFromEmail('dave@x.com'));
397
- expect(await Auth.twoFactorStatus()).toBe(Auth.TwoFactorMethod.Email);
398
-
399
- __clearSentEmails();
400
- jar.clear(); // drop the existing session so login is a clean 2FA challenge
401
-
402
- // Login now demands a second factor: mutual auth still passes (login()
403
- // verifies serverConfirm before throwing), but NO session is minted.
404
- let err: unknown;
405
- try {
406
- await Auth.login('dave', 'dave-pw-strongA1');
407
- } catch (e) {
408
- err = e;
409
- }
410
- expect(err).toBeInstanceOf(TwoFactorRequiredError);
411
- const twoFaId = (err as TwoFactorRequiredError).twoFaId;
412
- expect(twoFaId.length).toBeGreaterThan(0);
413
- expect(jar.get('toil_sess')).toBeUndefined(); // no session at login/finish
414
-
415
- // Read the login code out of the captured email and verify -> session.
416
- const session = await Auth.verifyTwoFactor(twoFaId, codeFromEmail('dave@x.com'));
417
- expect(session.length).toBeGreaterThan(0);
418
-
419
- // /auth/me now returns the user.
420
- const meRes = await fetch('/auth/me');
421
- expect(meRes.status).toBe(200);
422
- const me = new DataReader(new Uint8Array(await meRes.arrayBuffer()));
423
- expect(me.readBytes().length).toBeGreaterThan(0); // toilUserId
424
- expect(me.readString()).toBe('dave');
425
- },
426
- 90_000,
427
- );
428
-
429
- it(
430
- '(b) 2FA code security: wrong code rejected + attempt-limited to death, correct code single-use',
431
- async () => {
432
- await Auth.register('eve', 'eve-pw-strongA1', 'eve@x.com');
433
- await Auth.login('eve', 'eve-pw-strongA1');
434
- await Auth.setupTwoFactor(Auth.TwoFactorMethod.Email);
435
- await Auth.confirmTwoFactorSetup(codeFromEmail('eve@x.com'));
436
-
437
- // ---- wrong code is rejected, and after TWOFA_MAX_ATTEMPTS the challenge dies ----
438
- __clearSentEmails();
439
- jar.clear();
440
- let err: unknown;
441
- try {
442
- await Auth.login('eve', 'eve-pw-strongA1');
443
- } catch (e) {
444
- err = e;
445
- }
446
- const twoFaId = (err as TwoFactorRequiredError).twoFaId;
447
- const code = codeFromEmail('eve@x.com');
448
- const wrong = code === '000000' ? '111111' : '000000';
449
-
450
- // 5 (TWOFA_MAX_ATTEMPTS) wrong guesses. Reset the per-IP limiter between
451
- // each so this exercises the CHALLENGE's own attempt cap, not @ratelimit.
452
- for (let i = 0; i < 5; i++) {
453
- __resetRatelimitForTests();
454
- await expect(Auth.verifyTwoFactor(twoFaId, wrong)).rejects.toThrow();
455
- }
456
- // The challenge is now destroyed: even the CORRECT code fails.
457
- __resetRatelimitForTests();
458
- await expect(Auth.verifyTwoFactor(twoFaId, code)).rejects.toThrow();
459
-
460
- // ---- a correct code is single-use: replay fails ----
461
- __clearSentEmails();
462
- jar.clear();
463
- __resetRatelimitForTests();
464
- let err2: unknown;
465
- try {
466
- await Auth.login('eve', 'eve-pw-strongA1');
467
- } catch (e) {
468
- err2 = e;
469
- }
470
- const twoFaId2 = (err2 as TwoFactorRequiredError).twoFaId;
471
- const code2 = codeFromEmail('eve@x.com');
472
- const session = await Auth.verifyTwoFactor(twoFaId2, code2); // consumes
473
- expect(session.length).toBeGreaterThan(0);
474
- __resetRatelimitForTests();
475
- await expect(Auth.verifyTwoFactor(twoFaId2, code2)).rejects.toThrow(); // replay dead
476
- },
477
- 120_000,
478
- );
479
-
480
- it(
481
- '(c) cross-flow: reset tokens and 2FA codes are NOT interchangeable (namespace separation)',
482
- async () => {
483
- await Auth.register('frank', 'frank-pw-strongA1', 'frank@x.com');
484
-
485
- // ---- direction 1: a LIVE reset token is useless at /auth/2fa/verify ----
486
- await Auth.requestPasswordReset('frank@x.com');
487
- const resetToken = tokenFromEmail('reset', 'frank@x.com'); // live resetTokens entry
488
- __resetRatelimitForTests();
489
- // Present the reset token as BOTH the twoFaId AND the code: /2fa/verify
490
- // looks in `twoFaLogins` (a different collection) -> nothing -> rejected.
491
- await expect(Auth.verifyTwoFactor(resetToken, resetToken)).rejects.toThrow();
492
-
493
- // ---- direction 2: a LIVE 2FA login challenge id is useless at /auth/reset/finish ----
494
- await Auth.login('frank', 'frank-pw-strongA1'); // session (2FA still off here)
495
- __clearSentEmails();
496
- await Auth.setupTwoFactor(Auth.TwoFactorMethod.Email);
497
- await Auth.confirmTwoFactorSetup(codeFromEmail('frank@x.com'));
498
- __clearSentEmails();
499
- jar.clear();
500
- __resetRatelimitForTests();
501
- let err: unknown;
502
- try {
503
- await Auth.login('frank', 'frank-pw-strongA1');
504
- } catch (e) {
505
- err = e;
506
- }
507
- const twoFaId = (err as TwoFactorRequiredError).twoFaId; // live twoFaLogins key
508
- const loginCode = codeFromEmail('frank@x.com');
509
-
510
- // Submit the live 2FA challenge id AND the live 2FA code to
511
- // /auth/reset/finish as the reset token: reset/finish looks in
512
- // `resetTokens` -> nothing -> non-200. A live 2FA challenge is NOT a
513
- // reset token.
514
- const probes: Uint8Array[] = [hexToBytes(twoFaId), new TextEncoder().encode(loginCode)];
515
- for (const raw of probes) {
516
- __resetRatelimitForTests();
517
- const body = new DataWriter()
518
- .writeBytes(raw)
519
- .writeBytes(new Uint8Array(1312)) // valid-length pk (reach the consume step)
520
- .writeBytes(new Uint8Array(2420)) // valid-length proof
521
- .toBytes();
522
- const r = mod.dispatch({
523
- method: 'POST',
524
- path: '/auth/reset/finish',
525
- headers: [
526
- ['host', 'localhost:3000'],
527
- ['content-type', 'application/octet-stream'],
528
- ],
529
- body,
530
- });
531
- expect(r.status).not.toBe(200);
532
- }
533
-
534
- // The cross-flow probes touched NOTHING: the real 2FA login still
535
- // completes with its real (twoFaId, code).
536
- __resetRatelimitForTests();
537
- const session = await Auth.verifyTwoFactor(twoFaId, loginCode);
538
- expect(session.length).toBeGreaterThan(0);
539
- },
540
- 120_000,
541
- );
542
-
543
- it(
544
- '(d) NO session cookie is set on the ST_TWOFA_REQUIRED login response',
545
- async () => {
546
- await Auth.register('gwen', 'gwen-pw-strongA1', 'gwen@x.com');
547
- await Auth.login('gwen', 'gwen-pw-strongA1');
548
- await Auth.setupTwoFactor(Auth.TwoFactorMethod.Email);
549
- await Auth.confirmTwoFactorSetup(codeFromEmail('gwen@x.com'));
550
-
551
- jar.clear(); // drop every cookie
552
- __clearSentEmails();
553
- __resetRatelimitForTests();
554
-
555
- let err: unknown;
556
- try {
557
- await Auth.login('gwen', 'gwen-pw-strongA1');
558
- } catch (e) {
559
- err = e;
560
- }
561
- expect(err).toBeInstanceOf(TwoFactorRequiredError);
562
- // The shim folds any Set-Cookie into the jar; login/finish set NONE.
563
- expect(jar.get('toil_sess')).toBeUndefined();
564
- expect(jar.get('toil_user')).toBeUndefined();
565
- // With no session cookie, the @auth-gated /auth/me is 401.
566
- const meRes = await fetch('/auth/me');
567
- expect(meRes.status).toBe(401);
568
- },
569
- 60_000,
570
- );
571
-
572
- it(
573
- '(e) login<->setup 2FA challenges are separate: a setup code cannot mint a login session, and setup/verify never silently disables 2FA',
574
- async () => {
575
- await Auth.register('ivy', 'ivy-pw-strongA1', 'ivy@x.com');
576
- await Auth.login('ivy', 'ivy-pw-strongA1'); // session; 2FA still off
577
-
578
- // Begin a 2FA SETUP: writes a challenge into `twoFaSetup` (keyed by
579
- // username), NOT a login challenge into `twoFaLogins`.
580
- __clearSentEmails();
581
- __resetRatelimitForTests();
582
- await Auth.setupTwoFactor(Auth.TwoFactorMethod.Email);
583
- const setupCode = codeFromEmail('ivy@x.com');
584
-
585
- // Present the LIVE setup code at /auth/2fa/verify with a fabricated
586
- // twoFaId: /2fa/verify consults ONLY `twoFaLogins`, so the id misses and
587
- // a setup code can never mint a login session.
588
- __resetRatelimitForTests();
589
- const fakeId = 'ab'.repeat(16); // 16-byte hex, not a real twoFaLogins key
590
- await expect(Auth.verifyTwoFactor(fakeId, setupCode)).rejects.toThrow();
591
-
592
- // The probe consumed NOTHING: the real setup still completes with the code.
593
- __resetRatelimitForTests();
594
- await Auth.confirmTwoFactorSetup(setupCode);
595
- expect(await Auth.twoFactorStatus()).toBe(Auth.TwoFactorMethod.Email);
596
-
597
- // With 2FA now ON but NO pending setup challenge, /auth/2fa/setup/verify is
598
- // a no-op: a stray code cannot flip (disable) the method. A login challenge
599
- // (targetMethod=NONE) has no wire path here and can never be routed in to
600
- // silently disable 2FA.
601
- __resetRatelimitForTests();
602
- await expect(Auth.confirmTwoFactorSetup('000000')).rejects.toThrow();
603
- expect(await Auth.twoFactorStatus()).toBe(Auth.TwoFactorMethod.Email);
604
- },
605
- 120_000,
606
- );
607
-
608
- it(
609
- '(f) cross-flow: confirm tokens and 2FA codes are NOT interchangeable (namespace separation)',
610
- async () => {
611
- setConfirmation(true);
612
- await Auth.register('jade', 'jade-pw-strongA1', 'jade@x.com'); // unconfirmed -> confirm token emailed
613
- const confirmToken = tokenFromEmail('confirm', 'jade@x.com'); // live confirmTokens entry
614
-
615
- // ---- direction 1: a LIVE confirm token is useless at /auth/2fa/verify ----
616
- __resetRatelimitForTests();
617
- // Present the confirm token as BOTH the twoFaId AND the code: /2fa/verify
618
- // reads `twoFaLogins` (a different collection) -> nothing -> rejected.
619
- await expect(Auth.verifyTwoFactor(confirmToken, confirmToken)).rejects.toThrow();
620
-
621
- // The probe consumed NOTHING: the confirm token still confirms the account,
622
- // and login then succeeds (email now confirmed).
623
- __resetRatelimitForTests();
624
- await Auth.confirmEmail(confirmToken);
625
- __resetRatelimitForTests();
626
- expect((await Auth.login('jade', 'jade-pw-strongA1')).length).toBeGreaterThan(0);
627
-
628
- // ---- direction 2: a LIVE 2FA login id/code is useless at /auth/confirm ----
629
- // Enable 2FA (jade is confirmed + has a session from the login above).
630
- __clearSentEmails();
631
- __resetRatelimitForTests();
632
- await Auth.setupTwoFactor(Auth.TwoFactorMethod.Email);
633
- await Auth.confirmTwoFactorSetup(codeFromEmail('jade@x.com'));
634
-
635
- // Fresh login -> a live `twoFaLogins` challenge (id + emailed code).
636
- __clearSentEmails();
637
- jar.clear();
638
- __resetRatelimitForTests();
639
- let err: unknown;
640
- try {
641
- await Auth.login('jade', 'jade-pw-strongA1');
642
- } catch (e) {
643
- err = e;
644
- }
645
- const twoFaId = (err as TwoFactorRequiredError).twoFaId;
646
- const loginCode = codeFromEmail('jade@x.com');
647
-
648
- // Submit the live 2FA id AND the live code to /auth/confirm as the confirm
649
- // token: /auth/confirm consumes from `confirmTokens` (sha256(raw)) -> nothing
650
- // -> non-200. A 2FA credential is NOT a confirm token.
651
- const probes: Uint8Array[] = [hexToBytes(twoFaId), new TextEncoder().encode(loginCode)];
652
- for (const raw of probes) {
653
- __resetRatelimitForTests();
654
- const body = new DataWriter().writeBytes(raw).toBytes();
655
- const r = mod.dispatch({
656
- method: 'POST',
657
- path: '/auth/confirm',
658
- headers: [
659
- ['host', 'localhost:3000'],
660
- ['content-type', 'application/octet-stream'],
661
- ],
662
- body,
663
- });
664
- expect(r.status).not.toBe(200);
665
- }
666
-
667
- // The probes touched NOTHING: the real 2FA login still completes.
668
- __resetRatelimitForTests();
669
- const session = await Auth.verifyTwoFactor(twoFaId, loginCode);
670
- expect(session.length).toBeGreaterThan(0);
671
- },
672
- 120_000,
673
- );
674
-
675
- it(
676
- '(g) per-domain isolation: a confirm/reset/2FA code minted on domain A is USELESS on domain B',
677
- async () => {
678
- const A = 'a.example.com';
679
- const B = 'b.example.com';
680
-
681
- // ---- confirm token: minted on A, unredeemable on B ----
682
- setConfirmation(true);
683
- setHost(A);
684
- await Auth.register('mia', 'mia-pw-strongA1', 'mia@x.com'); // realm A + confirm token emailed
685
- const confirmTok = tokenFromEmail('confirm', 'mia@x.com');
686
-
687
- setHost(B);
688
- __resetRatelimitForTests();
689
- // Same raw token, different realm -> tokenId(B, raw) is a different key -> miss.
690
- await expect(Auth.confirmEmail(confirmTok)).rejects.toThrow();
691
-
692
- setHost(A);
693
- __resetRatelimitForTests();
694
- await Auth.confirmEmail(confirmTok); // realm A -> confirms
695
- setConfirmation(false);
696
-
697
- // ---- reset token: minted on A, unredeemable on B ----
698
- setHost(A);
699
- __clearSentEmails();
700
- __resetRatelimitForTests();
701
- await Auth.requestPasswordReset('mia@x.com');
702
- const resetTok = tokenFromEmail('reset', 'mia@x.com');
703
-
704
- setHost(B);
705
- __resetRatelimitForTests();
706
- await expect(Auth.resetPassword(resetTok, 'mia-pw-newA1')).rejects.toThrow(); // realm B miss
707
-
708
- setHost(A);
709
- __resetRatelimitForTests();
710
- await Auth.resetPassword(resetTok, 'mia-pw-newA1'); // realm A -> resets
711
-
712
- // ---- 2FA login code: minted on A, unusable on B ----
713
- setHost(A);
714
- __resetRatelimitForTests();
715
- await Auth.login('mia', 'mia-pw-newA1'); // session on A (2FA still off)
716
- __clearSentEmails();
717
- await Auth.setupTwoFactor(Auth.TwoFactorMethod.Email);
718
- await Auth.confirmTwoFactorSetup(codeFromEmail('mia@x.com')); // 2FA enabled on A
719
-
720
- __clearSentEmails();
721
- jar.clear();
722
- __resetRatelimitForTests();
723
- let err: unknown;
724
- try {
725
- await Auth.login('mia', 'mia-pw-newA1'); // -> 2FA challenge (twoFaId + code, realm A)
726
- } catch (e) {
727
- err = e;
728
- }
729
- const twoFaId = (err as TwoFactorRequiredError).twoFaId;
730
- const loginCode = codeFromEmail('mia@x.com');
731
-
732
- setHost(B);
733
- __resetRatelimitForTests();
734
- // The twoFaId lives in twoFaLogins under realm A; on B its key (and the
735
- // realm-bound codeHash) miss -> a code from A cannot mint a session on B.
736
- await expect(Auth.verifyTwoFactor(twoFaId, loginCode)).rejects.toThrow();
737
-
738
- setHost(A);
739
- __resetRatelimitForTests();
740
- const session = await Auth.verifyTwoFactor(twoFaId, loginCode); // realm A -> mints
741
- expect(session.length).toBeGreaterThan(0);
742
- },
743
- 180_000,
744
- );
745
-
746
- // ---- input validation (client-side, before any crypto / network) ----
747
-
748
- it('checkPassword + isValidEmail: the pure validators behave', () => {
749
- expect(checkPassword('Str0ng-pw!')).toEqual([]); // meets every rule
750
- expect(checkPassword('short1A').sort()).toEqual(['minLength', 'special'].sort()); // 7 chars, no special
751
- expect(checkPassword('alllowercase1!')).toEqual(['uppercase']);
752
- expect(checkPassword('NoDigits!!')).toEqual(['digit']);
753
- expect(isValidEmail('bob@example.com')).toBe(true);
754
- expect(isValidEmail('bobfwehfuewhfwf.com')).toBe(false); // no @
755
- expect(isValidEmail('a@b')).toBe(false); // no dotted domain
756
- expect(isValidEmail('a b@x.com')).toBe(false); // space
757
- });
758
-
759
- it('register rejects a weak password with WeakPasswordError (before any network)', async () => {
760
- const err = await Auth.register('newbie', 'weak', 'newbie@x.com').catch((e: unknown) => e);
761
- expect(err).toBeInstanceOf(WeakPasswordError);
762
- expect((err as WeakPasswordError).code).toBe(AuthErrorCode.WeakPassword);
763
- // the unmet rules are exposed so a UI can show a checklist
764
- expect((err as WeakPasswordError).unmet).toContain('minLength');
765
- expect((err as WeakPasswordError).unmet).toContain('uppercase');
766
- // no confirm email was sent (it threw before the request)
767
- __clearSentEmails();
768
- expect(__sentEmails.length).toBe(0);
769
- });
770
-
771
- it('register rejects an invalid email + a bad username with typed errors', async () => {
772
- await expect(Auth.register('newbie', 'Str0ng-pw!', 'not-an-email')).rejects.toBeInstanceOf(
773
- InvalidEmailError,
774
- );
775
- await expect(Auth.register('', 'Str0ng-pw!', 'ok@x.com')).rejects.toBeInstanceOf(
776
- InvalidUsernameError,
777
- );
778
- });
779
-
780
- it(
781
- 'AUTH_EMAIL_CONFIRMATION sends the verify email at register but does NOT block login',
782
- async () => {
783
- // The decoupled flag: verify-at-register, login NOT gated (unlike the
784
- // stricter AUTH_REQUIRE_EMAIL_CONFIRMATION, which also blocks login).
785
- setEmailConfirmation(true);
786
- __clearSentEmails();
787
- await Auth.register('kev', 'Kev-pw-strong1!', 'kev@x.com');
788
- // a confirm link was emailed (the account is stored unconfirmed)
789
- const tok = tokenFromEmail('confirm', 'kev@x.com');
790
- expect(tok.length).toBeGreaterThan(0);
791
- // login SUCCEEDS despite the unconfirmed email (no login gate)
792
- __resetRatelimitForTests();
793
- const session = await Auth.login('kev', 'Kev-pw-strong1!');
794
- expect(session.length).toBeGreaterThan(0);
795
- // and the emailed confirm link still works
796
- __resetRatelimitForTests();
797
- await Auth.confirmEmail(tok);
798
- },
799
- 90_000,
800
- );
801
- });