toiljs 0.0.116 → 0.0.118

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 (337) hide show
  1. package/CHANGELOG.md +14 -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/auth.d.ts +3 -0
  8. package/build/client/auth.js +19 -10
  9. package/build/client/dev/devtools.js +1 -1
  10. package/build/client/dev/error-overlay.js +1 -1
  11. package/build/client/index.d.ts +1 -1
  12. package/build/client/index.js +1 -1
  13. package/build/client/navigation/navigation.js +28 -3
  14. package/build/client/routing/Router.js +5 -2
  15. package/build/client/routing/mount.js +1 -1
  16. package/build/compiler/.tsbuildinfo +1 -1
  17. package/build/compiler/auth-emails.js +7 -3
  18. package/build/compiler/emails.js +1 -1
  19. package/build/compiler/index.d.ts +1 -0
  20. package/build/compiler/index.js +26 -5
  21. package/build/compiler/pages.js +2 -3
  22. package/build/compiler/prerender.d.ts +3 -8
  23. package/build/compiler/prerender.js +88 -127
  24. package/build/compiler/ssg.js +3 -4
  25. package/build/compiler/template-build.js +3 -4
  26. package/build/compiler/toil-docs.generated.js +8 -7
  27. package/build/compiler/vite.js +4 -6
  28. package/build/devserver/.tsbuildinfo +1 -1
  29. package/build/devserver/db/database.js +7 -3
  30. package/build/devserver/db/types.js +1 -1
  31. package/build/devserver/production.js +4 -3
  32. package/build/devserver/runtime/crypto.d.ts +1 -1
  33. package/build/io/.tsbuildinfo +1 -1
  34. package/build/logger/.tsbuildinfo +1 -1
  35. package/build/shared/.tsbuildinfo +1 -1
  36. package/examples/basic/client/routes/analytics.tsx +7 -5
  37. package/examples/basic/client/routes/pq.tsx +2 -1
  38. package/examples/basic/server/tsconfig.json +1 -3
  39. package/package.json +45 -44
  40. package/presets/no-uint8array-tostring.js +120 -153
  41. package/presets/oxlint.d.ts +5 -0
  42. package/presets/oxlint.js +224 -0
  43. package/server/auth/AuthController.ts +53 -14
  44. package/server/auth/FactorSettings.ts +41 -0
  45. package/server/auth/SessionEpochs.ts +58 -0
  46. package/server/auth/SessionRevocations.ts +13 -0
  47. package/server/globals/auth.ts +27 -2
  48. package/server/runtime/tsconfig.json +1 -3
  49. package/tsconfig.json +2 -11
  50. package/.github/ISSUE_TEMPLATE/bug_report.md +0 -38
  51. package/.github/ISSUE_TEMPLATE/bug_report.yml +0 -90
  52. package/.github/ISSUE_TEMPLATE/config.yml +0 -8
  53. package/.github/ISSUE_TEMPLATE/feature_request.md +0 -20
  54. package/.github/PULL_REQUEST_TEMPLATE.md +0 -43
  55. package/.github/changelog-config.json +0 -45
  56. package/.github/dependabot.yml +0 -27
  57. package/.github/workflows/ci.yml +0 -222
  58. package/.vscode/settings.json +0 -10
  59. package/docs/README.md +0 -107
  60. package/docs/auth/README.md +0 -104
  61. package/docs/auth/configuration.md +0 -105
  62. package/docs/auth/emails.md +0 -92
  63. package/docs/auth/extending.md +0 -202
  64. package/docs/auth/how-it-works.md +0 -138
  65. package/docs/auth/usage.md +0 -188
  66. package/docs/backend/README.md +0 -143
  67. package/docs/backend/data.md +0 -351
  68. package/docs/backend/rest.md +0 -402
  69. package/docs/backend/rpc.md +0 -226
  70. package/docs/background/README.md +0 -114
  71. package/docs/background/daemons.md +0 -276
  72. package/docs/background/derive.md +0 -179
  73. package/docs/cli/README.md +0 -379
  74. package/docs/concepts/ai-guide.md +0 -132
  75. package/docs/concepts/config.md +0 -416
  76. package/docs/concepts/decorators.md +0 -127
  77. package/docs/concepts/security.md +0 -108
  78. package/docs/concepts/tiers.md +0 -166
  79. package/docs/concepts/types.md +0 -216
  80. package/docs/database/README.md +0 -143
  81. package/docs/database/capacity.md +0 -350
  82. package/docs/database/counters.md +0 -174
  83. package/docs/database/documents.md +0 -277
  84. package/docs/database/events.md +0 -307
  85. package/docs/database/membership.md +0 -246
  86. package/docs/database/setup.md +0 -155
  87. package/docs/database/unique.md +0 -216
  88. package/docs/database/views.md +0 -246
  89. package/docs/frontend/README.md +0 -104
  90. package/docs/frontend/components.md +0 -286
  91. package/docs/frontend/data-fetching.md +0 -260
  92. package/docs/frontend/images.md +0 -148
  93. package/docs/frontend/metadata.md +0 -344
  94. package/docs/frontend/navigation.md +0 -296
  95. package/docs/frontend/rendering.md +0 -236
  96. package/docs/frontend/routing.md +0 -346
  97. package/docs/frontend/scripts.md +0 -118
  98. package/docs/frontend/search.md +0 -191
  99. package/docs/frontend/styling.md +0 -147
  100. package/docs/frontend/toil-global.md +0 -216
  101. package/docs/getting-started/README.md +0 -81
  102. package/docs/getting-started/create-project.md +0 -131
  103. package/docs/getting-started/deploy.md +0 -101
  104. package/docs/getting-started/first-app.md +0 -215
  105. package/docs/getting-started/installation.md +0 -124
  106. package/docs/getting-started/migrating.md +0 -125
  107. package/docs/getting-started/project-structure.md +0 -163
  108. package/docs/introduction/README.md +0 -66
  109. package/docs/introduction/design-principles.md +0 -81
  110. package/docs/introduction/distributed.md +0 -91
  111. package/docs/introduction/how-it-works.md +0 -121
  112. package/docs/introduction/hyperscale.md +0 -70
  113. package/docs/introduction/modern-stack.md +0 -85
  114. package/docs/introduction/vs-other-frameworks.md +0 -64
  115. package/docs/introduction/why-toil.md +0 -99
  116. package/docs/llms.txt +0 -95
  117. package/docs/realtime/README.md +0 -102
  118. package/docs/realtime/channels.md +0 -211
  119. package/docs/realtime/streams.md +0 -369
  120. package/docs/services/README.md +0 -60
  121. package/docs/services/analytics.md +0 -279
  122. package/docs/services/caching.md +0 -175
  123. package/docs/services/cookies.md +0 -235
  124. package/docs/services/crypto.md +0 -209
  125. package/docs/services/email.md +0 -289
  126. package/docs/services/environment.md +0 -141
  127. package/docs/services/ratelimit.md +0 -174
  128. package/docs/services/time.md +0 -85
  129. package/eslint.config.js +0 -57
  130. package/examples/basic/client/routes/docs/[...slug].tsx +0 -12
  131. package/presets/eslint.js +0 -88
  132. package/src/backend/index.ts +0 -204
  133. package/src/cli/configure.ts +0 -363
  134. package/src/cli/create.ts +0 -924
  135. package/src/cli/db.ts +0 -158
  136. package/src/cli/diagnostics.ts +0 -665
  137. package/src/cli/doctor.ts +0 -982
  138. package/src/cli/features.ts +0 -170
  139. package/src/cli/index.ts +0 -326
  140. package/src/cli/notify.ts +0 -120
  141. package/src/cli/proc.ts +0 -56
  142. package/src/cli/ui.ts +0 -169
  143. package/src/cli/update.ts +0 -248
  144. package/src/cli/updates.ts +0 -92
  145. package/src/cli/validate.ts +0 -31
  146. package/src/cli/version-check.ts +0 -125
  147. package/src/client/auth.ts +0 -869
  148. package/src/client/channel/channel.ts +0 -146
  149. package/src/client/components/Form.tsx +0 -65
  150. package/src/client/components/Image.tsx +0 -160
  151. package/src/client/components/Script.tsx +0 -113
  152. package/src/client/components/Slot.tsx +0 -21
  153. package/src/client/dev/devtools.tsx +0 -1089
  154. package/src/client/dev/error-overlay.tsx +0 -225
  155. package/src/client/errors.ts +0 -11
  156. package/src/client/head/head.ts +0 -182
  157. package/src/client/head/metadata.ts +0 -110
  158. package/src/client/index.ts +0 -130
  159. package/src/client/navigation/Link.tsx +0 -108
  160. package/src/client/navigation/NavLink.tsx +0 -86
  161. package/src/client/navigation/navigation.ts +0 -235
  162. package/src/client/navigation/prefetch.ts +0 -169
  163. package/src/client/navigation/scroll.ts +0 -53
  164. package/src/client/routing/Router.tsx +0 -216
  165. package/src/client/routing/action.ts +0 -122
  166. package/src/client/routing/error-boundary.tsx +0 -43
  167. package/src/client/routing/hooks.ts +0 -140
  168. package/src/client/routing/lazy.ts +0 -77
  169. package/src/client/routing/loader.ts +0 -381
  170. package/src/client/routing/match.ts +0 -47
  171. package/src/client/routing/mount.tsx +0 -90
  172. package/src/client/routing/params-context.ts +0 -10
  173. package/src/client/routing/slot-context.ts +0 -7
  174. package/src/client/rpc.ts +0 -97
  175. package/src/client/search/search.ts +0 -189
  176. package/src/client/search/use-page-search.ts +0 -73
  177. package/src/client/ssr/markers.tsx +0 -172
  178. package/src/client/stream/client.ts +0 -237
  179. package/src/client/types.ts +0 -73
  180. package/src/compiler/auth-emails.ts +0 -312
  181. package/src/compiler/config.ts +0 -369
  182. package/src/compiler/docs.ts +0 -127
  183. package/src/compiler/email-preview.ts +0 -314
  184. package/src/compiler/emails.ts +0 -404
  185. package/src/compiler/fonts.ts +0 -89
  186. package/src/compiler/generate.ts +0 -471
  187. package/src/compiler/image-blur.ts +0 -42
  188. package/src/compiler/image-report.ts +0 -88
  189. package/src/compiler/index.ts +0 -1362
  190. package/src/compiler/pages.ts +0 -49
  191. package/src/compiler/plugin.ts +0 -391
  192. package/src/compiler/prerender.ts +0 -263
  193. package/src/compiler/routes.ts +0 -170
  194. package/src/compiler/seo.ts +0 -415
  195. package/src/compiler/sri.ts +0 -144
  196. package/src/compiler/ssg.ts +0 -177
  197. package/src/compiler/ssr-codegen.ts +0 -85
  198. package/src/compiler/template-build.ts +0 -676
  199. package/src/compiler/template.ts +0 -262
  200. package/src/compiler/toil-docs.generated.ts +0 -77
  201. package/src/compiler/vite.ts +0 -245
  202. package/src/devserver/analytics/index.ts +0 -317
  203. package/src/devserver/config/dotenv.ts +0 -102
  204. package/src/devserver/config/env.ts +0 -30
  205. package/src/devserver/config/ratelimit.ts +0 -123
  206. package/src/devserver/daemon/catalog.ts +0 -120
  207. package/src/devserver/daemon/cron.ts +0 -87
  208. package/src/devserver/daemon/host.ts +0 -134
  209. package/src/devserver/daemon/index.ts +0 -369
  210. package/src/devserver/daemon/runtime.ts +0 -48
  211. package/src/devserver/db/catalog.ts +0 -109
  212. package/src/devserver/db/database.ts +0 -1834
  213. package/src/devserver/db/derives.ts +0 -121
  214. package/src/devserver/db/index.ts +0 -20
  215. package/src/devserver/db/routeKinds.ts +0 -191
  216. package/src/devserver/db/types.ts +0 -168
  217. package/src/devserver/email/caps.ts +0 -0
  218. package/src/devserver/email/config.ts +0 -141
  219. package/src/devserver/email/console.ts +0 -348
  220. package/src/devserver/email/index.ts +0 -155
  221. package/src/devserver/email/providers.ts +0 -131
  222. package/src/devserver/email/status.ts +0 -23
  223. package/src/devserver/email/validate.ts +0 -37
  224. package/src/devserver/email/wire.ts +0 -55
  225. package/src/devserver/http/cache.ts +0 -0
  226. package/src/devserver/http/envelope.ts +0 -157
  227. package/src/devserver/http/proxy.ts +0 -172
  228. package/src/devserver/http/runtime.ts +0 -387
  229. package/src/devserver/index.ts +0 -43
  230. package/src/devserver/production-ipc.ts +0 -63
  231. package/src/devserver/production-worker.ts +0 -83
  232. package/src/devserver/production.ts +0 -718
  233. package/src/devserver/runtime/crypto.ts +0 -587
  234. package/src/devserver/runtime/host.ts +0 -427
  235. package/src/devserver/runtime/module.ts +0 -442
  236. package/src/devserver/server.ts +0 -251
  237. package/src/devserver/ssr.ts +0 -208
  238. package/src/devserver/stream/catalog.ts +0 -106
  239. package/src/devserver/stream/host.ts +0 -42
  240. package/src/devserver/stream/index.ts +0 -301
  241. package/src/devserver/stream/manager.ts +0 -167
  242. package/src/devserver/stream/router.ts +0 -101
  243. package/src/devserver/stream/wire.ts +0 -58
  244. package/src/devserver/stream/ws.ts +0 -78
  245. package/src/devserver/wasm/sections.ts +0 -59
  246. package/src/devserver/wasm/surface.ts +0 -115
  247. package/src/io/FastMap.ts +0 -151
  248. package/src/io/FastSet.ts +0 -113
  249. package/src/io/codec.ts +0 -362
  250. package/src/io/index.ts +0 -10
  251. package/src/io/lengths.ts +0 -14
  252. package/src/io/types.ts +0 -19
  253. package/src/logger/index.ts +0 -22
  254. package/src/shared/index.ts +0 -46
  255. package/test/analytics-dev.test.ts +0 -113
  256. package/test/assembly/aspect-shim.ts +0 -33
  257. package/test/assembly/cookie.spec.ts +0 -303
  258. package/test/assembly/example.spec.ts +0 -22
  259. package/test/assembly/ssr.spec.ts +0 -95
  260. package/test/assembly.test.ts +0 -59
  261. package/test/auth-emails.test.ts +0 -118
  262. package/test/built-ssr.test.ts +0 -148
  263. package/test/channel.test.ts +0 -21
  264. package/test/config-host-port.test.ts +0 -59
  265. package/test/configure.test.ts +0 -94
  266. package/test/daemon-build.test.ts +0 -278
  267. package/test/daemon-catalog.test.ts +0 -349
  268. package/test/daemon-emulation.test.ts +0 -256
  269. package/test/db.test.ts +0 -0
  270. package/test/devserver-database.test.ts +0 -1102
  271. package/test/devserver-email.test.ts +0 -306
  272. package/test/devserver-pqauth.test.ts +0 -93
  273. package/test/devserver-secrets.test.ts +0 -63
  274. package/test/devserver.test.ts +0 -259
  275. package/test/doctor.test.ts +0 -298
  276. package/test/dom/Image.test.tsx +0 -144
  277. package/test/dom/Link.test.tsx +0 -67
  278. package/test/dom/NavLink.test.tsx +0 -37
  279. package/test/dom/Script.test.tsx +0 -48
  280. package/test/dom/action.test.tsx +0 -146
  281. package/test/dom/error-overlay.test.tsx +0 -44
  282. package/test/dom/loader.test.tsx +0 -121
  283. package/test/dom/navigation.test.ts +0 -59
  284. package/test/dom/revalidate.test.tsx +0 -38
  285. package/test/dom/route-head.test.tsx +0 -56
  286. package/test/dom/router-loading.test.tsx +0 -44
  287. package/test/dom/scroll.test.ts +0 -56
  288. package/test/dom/slot.test.tsx +0 -131
  289. package/test/dom/use-metadata.test.tsx +0 -58
  290. package/test/dom/view-transitions.test.tsx +0 -53
  291. package/test/dynamic-routing.test.ts +0 -132
  292. package/test/email-console.test.ts +0 -86
  293. package/test/email-preview.test.ts +0 -73
  294. package/test/emails.test.ts +0 -58
  295. package/test/errors.test.ts +0 -21
  296. package/test/example-guestbook.test.ts +0 -123
  297. package/test/features.test.ts +0 -149
  298. package/test/fixtures/bignum-wire/spec.ts +0 -25
  299. package/test/fixtures/daemon-app.ts +0 -65
  300. package/test/fixtures/stream-echo.ts +0 -26
  301. package/test/fixtures/stream-gate.ts +0 -28
  302. package/test/fixtures/stream-trap.ts +0 -18
  303. package/test/fixtures/stream-typed.ts +0 -41
  304. package/test/fonts.test.ts +0 -28
  305. package/test/global-setup.ts +0 -17
  306. package/test/head.test.ts +0 -42
  307. package/test/image-blur.test.ts +0 -50
  308. package/test/io.test.ts +0 -117
  309. package/test/metadata.test.ts +0 -40
  310. package/test/navlink.test.ts +0 -28
  311. package/test/pages.test.ts +0 -105
  312. package/test/placeholder.test.ts +0 -9
  313. package/test/pqauth-e2e.test.ts +0 -216
  314. package/test/pqauth-email.test.ts +0 -801
  315. package/test/prerender.test.ts +0 -116
  316. package/test/prettier-plugin.test.ts +0 -46
  317. package/test/routes.test.ts +0 -76
  318. package/test/rpc-bignum-wire.test.ts +0 -164
  319. package/test/rpc-dispatch.test.ts +0 -132
  320. package/test/rpc-kinds.test.ts +0 -18
  321. package/test/rpc.test.ts +0 -66
  322. package/test/search.test.ts +0 -114
  323. package/test/seo.test.ts +0 -175
  324. package/test/slot-layouts.test.ts +0 -69
  325. package/test/sri.test.ts +0 -129
  326. package/test/ssg.test.ts +0 -36
  327. package/test/ssr-hydration.test.tsx +0 -122
  328. package/test/ssr-render.test.ts +0 -197
  329. package/test/ssr-template.test.tsx +0 -482
  330. package/test/stream-emulation.test.ts +0 -479
  331. package/test/ui.test.ts +0 -40
  332. package/test/update.test.ts +0 -58
  333. package/test/validate.test.ts +0 -42
  334. package/test/version-check.test.ts +0 -130
  335. package/tests/data-parity/generated-parity.ts +0 -99
  336. package/tests/data-parity/parity.ts +0 -80
  337. package/tests/data-parity/spec.ts +0 -46
@@ -1,869 +0,0 @@
1
- /**
2
- * Client half of the post-quantum auth primitive (browser).
3
- *
4
- * The password never leaves this module. It is stretched with Argon2id into a
5
- * 32-byte seed, which deterministically expands into an ML-DSA-44 keypair
6
- * (FIPS 204). Only the 1312-byte PUBLIC key is ever sent; the secret key and
7
- * the seed are zeroized the instant signing is done. There is no recovery: the
8
- * password IS the key.
9
- *
10
- * Wire encoding is deterministic binary (`DataWriter`/`DataReader`), never
11
- * JSON, byte-identical to the server's `AuthService.buildLoginMessage`.
12
- */
13
-
14
- import { argon2id, createHMAC, createSHA256 } from 'hash-wasm';
15
- import { ml_dsa44 } from '@dacely/noble-post-quantum/ml-dsa.js';
16
- import { ml_kem768 } from '@dacely/noble-post-quantum/ml-kem.js';
17
- import { ristretto255_oprf } from '@noble/curves/ed25519.js';
18
-
19
- import { DataReader, DataWriter } from 'toiljs/io';
20
-
21
- /** FIPS 204 signing context (domain separator). Byte-identical to the server. */
22
- export const LOGIN_CONTEXT = 'qauth:login:v1';
23
- /** Registration proof-of-possession context (binds a sig to "register"). */
24
- export const REGISTER_CONTEXT = 'qauth:register:v1';
25
- /** Domain separators for the session-key derivation and the confirmation tag.
26
- * Byte-identical to the server. */
27
- export const SESSION_KEY_LABEL = 'toil-session-key-v1';
28
- export const SERVER_CONFIRM_LABEL = 'toil-server-confirm-v1';
29
-
30
- /** ML-KEM-768 sizes (FIPS 203). */
31
- export const KEM_PUBLIC_KEY_LEN = 1184;
32
- export const KEM_CIPHERTEXT_LEN = 1088;
33
- export const SHARED_SECRET_LEN = 32;
34
-
35
- /** Lowercase-hex -> bytes. */
36
- function fromHex(hex: string): Uint8Array {
37
- const out = new Uint8Array(hex.length / 2);
38
- for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
39
- return out;
40
- }
41
-
42
- /** bytes -> lowercase-hex. */
43
- function toHex(bytes: Uint8Array): string {
44
- let s = '';
45
- for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, '0');
46
- return s;
47
- }
48
-
49
- /**
50
- * The server's PINNED static ML-KEM-768 public key. The client encapsulates to
51
- * it; only the genuine server (holder of the matching secret key) can
52
- * decapsulate, so a valid confirmation tag authenticates the server. This is
53
- * the demo dev key; a real deployment pins its own (and rotates it).
54
- */
55
- export const SERVER_KEM_PUBLIC_KEY = fromHex(
56
- '29d765e8083182891302569b3712a856e564fdd484b0706b0c68568d5ab7edc742cf74459d64595455a60f267973aa55e43c5be61925a3822eafcca445e36dc4655636e31e6fc9bec338b253f94290008ef7f40dbddb49c15c690f6755a23a1b3c85cfd5207e71a607086a6fc6d74a05080f43276901a19cafdb8de7771d58ea07f0f1056b905127b22223d08e75173199f13ab13c5dcd3b51ac784f84e520484a262b845a897c41cf27324ab6ba545c78c9ccab361051e0bba53498af26240fa0d566d1572684f4b42e253e6d052c848650915063c35641e1121ef8d9cfd17b667b351103c56d195007c9376d0c08aa268396814490eab4c364175a94533267a1933862cc4c33bcf0a13d1fa2b9d6c5082eeca1480672f2526cbe013beff14dc908a386e0b633c8761023cbed760deac6709bc328d865ac82e12307b673d96711dbb27a4d939230d25b53d594169a318be0200fa33550e9418e2a3b30e9719edc09d5fc4306f1abfd021eab14637a8a72c5931d25dc9b56db0e6ab677522b10f25307dbb804a6774ce05b87b0976a4b227bfe6caf20a79e64004fbd27b1eea018b3ab8ffa629f2dc87f19278f95168e94e44660a3370c537795678eb2f056260609769740583b51b291862927a1938737c6a37f40b78f00671cccbcb88ac3427b37915ed58782998f84051647707d48995472baad3f64a7cca54e1c0734db08751c614a34f28b84f2c1b5a6817355ab61957c486b7acffbc092bc8a7b46387f33b53ed372f7168d31a71cd008539928b0cdf91e835aa97f6a2be6d327b87a6ae478701d75a59a25179cb14997bb2552853014724170a1c49b82c2bcebc3279024e1fa44c53c7afdc43f0bd22116490f3b74c90e7296be58b9a91168f2fa0c3d378a3bcac959f357825c9976a8c9ee944f29b45e96d7345d9b478431a20cf1c5d3a3227c717fd204619777636c0cb140db5c50d2a3302334461030bee34e4eb1a6f02b733f9ccda4290fa168bc039568373241542728d00030d1f251e83737cb215adbdc1de75978675a0cd0d75b12748abdda7a9852629c63697d145af2c69854b06e03f37c4b064e4c9a4c03f2ad4d081e70180e9547247921918118086b62b4f7727f46b24e3e79ba3f28209f32b5102035bf935856232f83642268c0292ec6bf8e9462382163d30a20b4bcb7b4439310ec9d0a148193907fc07697342967cf1a16c6b3c71558951fa915400736cf699262b54b723abb2ecc27b74b68ee494287595ef818388adb49e883c67bfa5c226c0eef037a0851a29d34675912c1ea1068310b6dfcd017c809c8fbfc2c3ae78dfef07299960eeefba182662a90fa422c1790f356a2ea909012b15623a9b9e450a282cb530589a68368b3583159d9010ac3e52cc974753c342e58279516339dfb691df94b13a223ad97eb6a09c21dafe6304a3642d6d2067b5238497661fe88ad1227ca3557be2a576b6e17c5a7f997ea07929e76407e376aba74c44cd8504804776f39bbb8327624188a63501e83b404d9438cade0b11dc3ac61856447fb072b91761c228878f01b2eb6b4b21ba664c2c75882431603b25a449ffeb8410b910558581777562aa9b2181fd9c04713ad9326462d3e842121c4997f9aa932417c67851625816de66e0d65637434629f39',
57
- );
58
-
59
- export const PUBLIC_KEY_LEN = 1312;
60
- export const SECRET_KEY_LEN = 2560;
61
- export const SIGNATURE_LEN = 2420;
62
- export const SEED_LEN = 32;
63
-
64
- /** Argon2id parameters, pinned PER ACCOUNT and echoed by the server. The client
65
- * derives against whatever it is handed -- never hardcoded -- so a future
66
- * parameter bump just works. They are part of the credential. */
67
- export interface KdfParams {
68
- /** `m`: memory in kibibytes (>= 256 MiB = 262144). */
69
- readonly memKiB: number;
70
- /** `t`: iterations (>= 3). */
71
- readonly iterations: number;
72
- /** `p`: degree of parallelism. */
73
- readonly parallelism: number;
74
- /** per-account salt (16 bytes, server-issued). */
75
- readonly salt: Uint8Array;
76
- }
77
-
78
- /** Overwrite a secret buffer with random bytes, then zero. Best-effort: JS GC
79
- * cannot scrub copies, so we never store or close over secrets beyond one call. */
80
- function wipe(buf: Uint8Array): void {
81
- crypto.getRandomValues(buf as unknown as Uint8Array<ArrayBuffer>);
82
- buf.fill(0);
83
- }
84
-
85
- /** Argon2id(oprfOutput, salt; m,t,p, len=32) -> 32-byte ML-DSA seed. The KDF
86
- * input is the OPRF output (the keyed salt), NOT the raw password: the password
87
- * is first run through the server-keyed OPRF, so a server breach yields no
88
- * precomputable salt. */
89
- async function deriveSeed(oprfOutput: Uint8Array, kdf: KdfParams): Promise<Uint8Array> {
90
- return argon2id({
91
- password: oprfOutput,
92
- salt: kdf.salt,
93
- iterations: kdf.iterations,
94
- parallelism: kdf.parallelism,
95
- memorySize: kdf.memKiB,
96
- hashLength: SEED_LEN,
97
- outputType: 'binary',
98
- });
99
- }
100
-
101
- const utf8 = (s: string): Uint8Array => new TextEncoder().encode(s);
102
-
103
- /** SHA-256 over `data` -> 32 raw bytes. Uses hash-wasm (pure WASM), so it works
104
- * in an insecure context (plain HTTP) where `crypto.subtle` is undefined. */
105
- async function sha256Bytes(data: Uint8Array): Promise<Uint8Array> {
106
- const h = await createSHA256();
107
- h.init();
108
- h.update(data);
109
- return h.digest('binary') as unknown as Uint8Array;
110
- }
111
-
112
- /** HMAC-SHA256(key, msg) -> 32 raw bytes, via hash-wasm (pure WASM, works in an
113
- * insecure context). Mirrors the server's `AuthService` HMAC for the session-key
114
- * derivation and the mutual-auth confirmation tag. */
115
- async function hmacSha256(key: Uint8Array, msg: Uint8Array): Promise<Uint8Array> {
116
- const h = await createHMAC(createSHA256(), key);
117
- h.init();
118
- h.update(msg);
119
- return h.digest('binary') as unknown as Uint8Array;
120
- }
121
-
122
- function concatBytes(...parts: Uint8Array[]): Uint8Array {
123
- let n = 0;
124
- for (const p of parts) n += p.length;
125
- const out = new Uint8Array(n);
126
- let off = 0;
127
- for (const p of parts) {
128
- out.set(p, off);
129
- off += p.length;
130
- }
131
- return out;
132
- }
133
-
134
- /** Length-checked constant-time-ish equality (no early-exit on content). */
135
- function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {
136
- if (a.length !== b.length) return false;
137
- let diff = 0;
138
- for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
139
- return diff === 0;
140
- }
141
-
142
- /** The canonical login message `M` -- ONE fixed binary layout, byte-identical to
143
- * the server's `AuthService.buildLoginMessage`. Binds the ML-KEM ciphertext (so
144
- * the signature commits to the key encapsulation), the Argon2id params (so a
145
- * MITM cannot slip a downgrade past the signature), and the server KEM key id
146
- * (so it commits to which server key was encapsulated to). */
147
- export function buildLoginMessage(
148
- sub: string,
149
- aud: string,
150
- cid: Uint8Array,
151
- nonce: Uint8Array,
152
- iat: bigint,
153
- exp: bigint,
154
- ciphertext: Uint8Array,
155
- memKiB: number,
156
- iterations: number,
157
- parallelism: number,
158
- serverKemKeyId: Uint8Array,
159
- ): Uint8Array {
160
- return new DataWriter()
161
- .writeU8(1)
162
- .writeString(sub)
163
- .writeString(aud)
164
- .writeBytes(cid)
165
- .writeBytes(nonce)
166
- .writeU64(iat)
167
- .writeU64(exp)
168
- .writeBytes(ciphertext)
169
- .writeU32(memKiB)
170
- .writeU32(iterations)
171
- .writeU32(parallelism)
172
- .writeBytes(serverKemKeyId)
173
- .toBytes();
174
- }
175
-
176
- /** Registration proof-of-possession message: `u8(1) str(username) bytes(pk)`,
177
- * signed under {@link REGISTER_CONTEXT}. Byte-identical to the server's
178
- * `buildRegisterMessage`. */
179
- export function buildRegisterMessage(username: string, publicKey: Uint8Array): Uint8Array {
180
- return new DataWriter().writeU8(1).writeString(username).writeBytes(publicKey).toBytes();
181
- }
182
-
183
- function decodeKdf(r: DataReader): KdfParams {
184
- return {
185
- memKiB: r.readU32(),
186
- iterations: r.readU32(),
187
- parallelism: r.readU32(),
188
- salt: r.readBytes(),
189
- };
190
- }
191
-
192
- async function postBinary(baseUrl: string, path: string, body: Uint8Array): Promise<DataReader> {
193
- const res = await fetch(baseUrl + path, {
194
- method: 'POST',
195
- headers: { 'content-type': 'application/octet-stream' },
196
- body: body as BodyInit,
197
- credentials: 'same-origin',
198
- });
199
- if (!res.ok) throw new AuthError(AuthErrorCode.RequestFailed, 'The auth request failed.');
200
- return new DataReader(new Uint8Array(await res.arrayBuffer()));
201
- }
202
-
203
- export interface AuthOptions {
204
- /** Endpoint prefix the server mounts the auth controller under. */
205
- readonly baseUrl?: string;
206
- }
207
-
208
- /**
209
- * Register a new account. The password never leaves the browser:
210
- * it is blinded and run through the server-keyed OPRF, the OPRF output is
211
- * stretched with Argon2id into an ML-DSA-44 keypair, and ONLY the public key
212
- * (plus a proof-of-possession signature) is submitted. Throws on failure.
213
- */
214
- export async function register(
215
- username: string,
216
- password: string,
217
- email: string,
218
- opts: AuthOptions = {},
219
- ): Promise<void> {
220
- const baseUrl = opts.baseUrl ?? '/auth';
221
- // Validate BEFORE any crypto or network. The password never leaves this module,
222
- // so the client is the ONLY place its policy can be enforced.
223
- if (!isValidUsername(username)) throw new InvalidUsernameError();
224
- if (!isValidEmail(email)) throw new InvalidEmailError();
225
- const weak = checkPassword(password);
226
- if (weak.length > 0) throw new WeakPasswordError(weak);
227
- const oprf = ristretto255_oprf.oprf;
228
- const pw = utf8(password.normalize('NFKC'));
229
-
230
- // 1. Blind the password and start registration: the server confirms the name
231
- // is free, issues salt + KDF params, and OPRF-evaluates the blinded input.
232
- const { blind, blinded } = oprf.blind(pw);
233
- const start = await postBinary(
234
- baseUrl,
235
- '/register/start',
236
- new DataWriter().writeString(username).writeBytes(blinded).toBytes(),
237
- );
238
- const status = start.readU8();
239
- if (status !== 0)
240
- throw new AuthError(AuthErrorCode.RequestFailed, 'Registration is unavailable right now.');
241
- const kdf = decodeKdf(start);
242
- const evaluated = start.readBytes();
243
-
244
- // 2. Finalize the OPRF -> keyed salt -> seed -> keypair. Keep only the public
245
- // key + a PoP signature; wipe the secret key and seed immediately.
246
- const oprfOutput = oprf.finalize(pw, blind, evaluated);
247
- const seed = await deriveSeed(oprfOutput, kdf);
248
- let publicKey: Uint8Array;
249
- let regProof: Uint8Array;
250
- try {
251
- const kp = ml_dsa44.keygen(seed);
252
- publicKey = kp.publicKey;
253
- try {
254
- regProof = ml_dsa44.sign(buildRegisterMessage(username, publicKey), kp.secretKey, {
255
- context: utf8(REGISTER_CONTEXT),
256
- });
257
- } finally {
258
- wipe(kp.secretKey);
259
- }
260
- } finally {
261
- wipe(seed);
262
- }
263
- if (publicKey.length !== PUBLIC_KEY_LEN)
264
- throw new AuthError(AuthErrorCode.ProtocolError, 'Server returned a bad public key length.');
265
-
266
- // 3. Submit the username + email + public key + proof-of-possession.
267
- const finish = await postBinary(
268
- baseUrl,
269
- '/register/finish',
270
- new DataWriter()
271
- .writeString(username)
272
- .writeString(email)
273
- .writeBytes(publicKey)
274
- .writeBytes(regProof)
275
- .toBytes(),
276
- );
277
- const finishStatus = finish.readU8();
278
- if (finishStatus === 1) throw new UsernameTakenError();
279
- if (finishStatus === 2) throw new EmailInUseError();
280
- if (finishStatus !== 0)
281
- throw new AuthError(AuthErrorCode.RegistrationRejected, 'Registration was rejected.');
282
- }
283
-
284
- /**
285
- * Log in (challenge-response with ML-KEM mutual auth). Steps:
286
- * 1. Blind the password; `login/start` returns the challenge + the OPRF
287
- * evaluation (a fully-formed response even for unknown users -> no oracle).
288
- * 2. Finalize the OPRF -> keyed salt -> seed -> ML-DSA keypair.
289
- * 3. Encapsulate a shared secret to the PINNED server ML-KEM public key, build
290
- * the v2 message (which binds the ciphertext), and sign it once.
291
- * 4. Submit `{cid, ct, signature}`; the server consumes the challenge, verifies
292
- * the signature, decapsulates, and returns a confirmation tag.
293
- * 5. Verify that tag against our own shared secret -> the server proved it
294
- * holds the KEM secret key (mutual authentication).
295
- * The secret key, seed, and shared secret are wiped as soon as they are used.
296
- * Returns the opaque session token. Throws (one generic message) on any failure.
297
- */
298
- export async function login(
299
- username: string,
300
- password: string,
301
- opts: AuthOptions = {},
302
- ): Promise<Uint8Array> {
303
- const baseUrl = opts.baseUrl ?? '/auth';
304
- const oprf = ristretto255_oprf.oprf;
305
- const pw = utf8(password.normalize('NFKC'));
306
-
307
- // 1. Blinded login/start.
308
- const { blind, blinded } = oprf.blind(pw);
309
- const r = await postBinary(
310
- baseUrl,
311
- '/login/start',
312
- new DataWriter().writeString(username).writeBytes(blinded).toBytes(),
313
- );
314
- const cid = r.readBytes();
315
- const aud = r.readString();
316
- const kdf = decodeKdf(r);
317
- const nonce = r.readBytes();
318
- const iat = r.readU64();
319
- const exp = r.readU64();
320
- const evaluated = r.readBytes();
321
- // Client-side fast-fail only; the server re-checks expiry authoritatively.
322
- if (BigInt(Math.floor(Date.now() / 1000)) >= exp)
323
- throw new AuthError(AuthErrorCode.ProtocolError, 'The login challenge expired; retry.');
324
-
325
- // 2. OPRF -> keyed salt -> seed.
326
- const oprfOutput = oprf.finalize(pw, blind, evaluated);
327
- const seed = await deriveSeed(oprfOutput, kdf);
328
-
329
- // 3. Encapsulate to the pinned server KEM key; build + sign the message,
330
- // which binds the ciphertext, the KDF params, and the server key id.
331
- const { cipherText, sharedSecret } = ml_kem768.encapsulate(SERVER_KEM_PUBLIC_KEY);
332
- const serverKemKeyId = await sha256Bytes(SERVER_KEM_PUBLIC_KEY);
333
- const message = buildLoginMessage(
334
- username,
335
- aud,
336
- cid,
337
- nonce,
338
- iat,
339
- exp,
340
- cipherText,
341
- kdf.memKiB,
342
- kdf.iterations,
343
- kdf.parallelism,
344
- serverKemKeyId,
345
- );
346
- let signature: Uint8Array;
347
- try {
348
- const kp = ml_dsa44.keygen(seed);
349
- try {
350
- signature = ml_dsa44.sign(message, kp.secretKey, { context: utf8(LOGIN_CONTEXT) });
351
- } finally {
352
- wipe(kp.secretKey);
353
- }
354
- } finally {
355
- wipe(seed);
356
- }
357
- if (signature.length !== SIGNATURE_LEN)
358
- throw new AuthError(AuthErrorCode.ProtocolError, 'Computed a bad signature length.');
359
-
360
- // 4. Submit {cid, ct, signature}.
361
- const res = await postBinary(
362
- baseUrl,
363
- '/login/finish',
364
- new DataWriter().writeBytes(cid).writeBytes(cipherText).writeBytes(signature).toBytes(),
365
- );
366
- const loginStatus = res.readU8();
367
- if (loginStatus === 2) {
368
- // The credential verified, but the domain requires a confirmed email and
369
- // this account is not confirmed yet. Distinguishable so the UI can prompt
370
- // "confirm your email" / offer a resend, rather than a generic failure.
371
- wipe(sharedSecret);
372
- throw new EmailNotConfirmedError();
373
- }
374
- // status 3 = 2FA required: the credential verified but the account has a second
375
- // factor. The server ALSO returns its serverConfirm tag (so we still complete
376
- // mutual auth below) but mints NO session/cookie. Both the success (0) and the
377
- // 2FA (3) responses are `bytes(first) bytes(serverConfirm)` -- `first` is the
378
- // session token on 0 and the twoFaId on 3.
379
- if (loginStatus !== 0 && loginStatus !== 3) {
380
- wipe(sharedSecret);
381
- throw new InvalidCredentialsError();
382
- }
383
- const first = res.readBytes();
384
- const serverConfirm = res.readBytes();
385
-
386
- // 5. Mutual auth: derive the session key K = HMAC(sharedSecret, label || H(M)),
387
- // then check the server's tag = HMAC(K, label || H(M)). Only a server that
388
- // decapsulated correctly derives the same K, so a valid tag proves its
389
- // identity. Runs for BOTH statuses, so a 2FA prompt only ever appears AFTER
390
- // the server has authenticated itself.
391
- const transcriptHash = await sha256Bytes(message);
392
- const sessionKey = await hmacSha256(
393
- sharedSecret,
394
- concatBytes(utf8(SESSION_KEY_LABEL), transcriptHash),
395
- );
396
- wipe(sharedSecret);
397
- const expected = await hmacSha256(
398
- sessionKey,
399
- concatBytes(utf8(SERVER_CONFIRM_LABEL), transcriptHash),
400
- );
401
- if (!bytesEqual(expected, serverConfirm)) throw new ServerAuthFailedError();
402
-
403
- if (loginStatus === 3) {
404
- // The server authenticated itself, but a second factor is required. Surface
405
- // the twoFaId (hex) so the caller can collect a code and call
406
- // verifyTwoFactor. NO session exists yet.
407
- throw new TwoFactorRequiredError(toHex(first));
408
- }
409
-
410
- return first; // session token
411
- }
412
-
413
- /**
414
- * The STABLE, typed discriminant carried by every auth error as `err.code`. Branch
415
- * on THIS (or on the error class via `instanceof`), never on `err.message` (human
416
- * facing, may change) nor `err.name` (a bare string, mangled by minifiers). Each
417
- * value maps 1:1 to an {@link AuthError} subclass below.
418
- *
419
- * ```ts
420
- * try { await Auth.login(email, password); }
421
- * catch (err) {
422
- * if (err instanceof Auth.EmailNotConfirmedError) return promptConfirm();
423
- * if (err instanceof Auth.TwoFactorRequiredError) return promptCode(err.twoFaId);
424
- * if (err instanceof Auth.AuthError && err.code === Auth.AuthErrorCode.InvalidCredentials)
425
- * return setError('Incorrect email or password.');
426
- * throw err;
427
- * }
428
- * ```
429
- */
430
- export enum AuthErrorCode {
431
- /** Network failure or a non-2xx / malformed response from the auth endpoint. */
432
- RequestFailed = 'request_failed',
433
- /** A client/server protocol mismatch (bad key or signature length, expired challenge). */
434
- ProtocolError = 'protocol_error',
435
- /** register: the username is already registered. */
436
- UsernameTaken = 'username_taken',
437
- /** register: the email is already in use. */
438
- EmailInUse = 'email_in_use',
439
- /** register: rejected for another reason (e.g. failed proof-of-possession). */
440
- RegistrationRejected = 'registration_rejected',
441
- /** login: wrong username/password. Deliberately indistinguishable from "no such user". */
442
- InvalidCredentials = 'invalid_credentials',
443
- /** login: the credential is valid but the account's email is not confirmed. */
444
- EmailNotConfirmed = 'email_not_confirmed',
445
- /** login: password + server auth OK, but a second factor is required (no session yet). */
446
- TwoFactorRequired = 'two_factor_required',
447
- /** login/2fa: the SERVER failed to authenticate itself (mutual-auth mismatch) -> possible MITM. */
448
- ServerAuthFailed = 'server_auth_failed',
449
- /** 2fa: the submitted code was wrong, expired, or already used. */
450
- TwoFactorCodeInvalid = 'two_factor_code_invalid',
451
- /** 2fa setup: enabling/disabling the second factor failed. */
452
- TwoFactorSetupFailed = 'two_factor_setup_failed',
453
- /** confirm: the email-confirmation link was invalid or expired. */
454
- ConfirmationInvalid = 'confirmation_invalid',
455
- /** reset: the password-reset link was invalid or expired. */
456
- PasswordResetInvalid = 'password_reset_invalid',
457
- /** register/reset: the password does not meet the strength policy (see WeakPasswordError.unmet). */
458
- WeakPassword = 'weak_password',
459
- /** register: the email address is not a valid format / length. */
460
- InvalidEmail = 'invalid_email',
461
- /** register: the username is empty or too long. */
462
- InvalidUsername = 'invalid_username',
463
- }
464
-
465
- /**
466
- * Base class for EVERY error thrown by the auth client. Always carries a typed
467
- * {@link AuthErrorCode} as `err.code`, so `err instanceof AuthError` narrows the
468
- * whole family and `err.code` discriminates within it. The specific subclasses
469
- * below are sugar for the common branches; any error is still an `AuthError`.
470
- */
471
- export class AuthError extends Error {
472
- /** The stable machine-readable discriminant. Prefer this over `message`/`name`. */
473
- readonly code: AuthErrorCode;
474
- constructor(code: AuthErrorCode, message: string) {
475
- super(message);
476
- this.name = 'AuthError';
477
- this.code = code;
478
- }
479
- }
480
-
481
- /** register: the username is already registered ({@link AuthErrorCode.UsernameTaken}). */
482
- export class UsernameTakenError extends AuthError {
483
- constructor() {
484
- super(AuthErrorCode.UsernameTaken, 'That username is already registered.');
485
- this.name = 'UsernameTakenError';
486
- }
487
- }
488
-
489
- /** register: the email is already in use ({@link AuthErrorCode.EmailInUse}). */
490
- export class EmailInUseError extends AuthError {
491
- constructor() {
492
- super(AuthErrorCode.EmailInUse, 'That email is already in use.');
493
- this.name = 'EmailInUseError';
494
- }
495
- }
496
-
497
- /** login: wrong username/password, or no such account ({@link AuthErrorCode.InvalidCredentials}). */
498
- export class InvalidCredentialsError extends AuthError {
499
- constructor() {
500
- super(AuthErrorCode.InvalidCredentials, 'Incorrect username or password.');
501
- this.name = 'InvalidCredentialsError';
502
- }
503
- }
504
-
505
- /** login: the credential is valid but the account's email is not confirmed and the
506
- * domain requires confirmation. Catch it to prompt the user to confirm (and offer
507
- * {@link resendConfirmation}). {@link AuthErrorCode.EmailNotConfirmed}. */
508
- export class EmailNotConfirmedError extends AuthError {
509
- constructor() {
510
- super(AuthErrorCode.EmailNotConfirmed, 'Your email address is not confirmed yet.');
511
- this.name = 'EmailNotConfirmedError';
512
- }
513
- }
514
-
515
- /** login: the password verified AND the server authenticated itself (mutual auth
516
- * passed) but the account requires a SECOND FACTOR. No session exists yet. Catch it,
517
- * collect the delivered code, and call {@link verifyTwoFactor} with `err.twoFaId`.
518
- * {@link AuthErrorCode.TwoFactorRequired}. */
519
- export class TwoFactorRequiredError extends AuthError {
520
- /** The opaque login-challenge id (hex) to echo to {@link verifyTwoFactor}. */
521
- readonly twoFaId: string;
522
- constructor(twoFaId: string) {
523
- super(AuthErrorCode.TwoFactorRequired, 'A second factor is required to sign in.');
524
- this.name = 'TwoFactorRequiredError';
525
- this.twoFaId = twoFaId;
526
- }
527
- }
528
-
529
- /** login/2fa: the SERVER failed to prove its identity (mutual-auth tag mismatch).
530
- * Treat as hostile: a genuine server always authenticates. Possible MITM / wrong
531
- * pinned KEM key. {@link AuthErrorCode.ServerAuthFailed}. */
532
- export class ServerAuthFailedError extends AuthError {
533
- constructor() {
534
- super(AuthErrorCode.ServerAuthFailed, 'Server authentication failed (possible MITM).');
535
- this.name = 'ServerAuthFailedError';
536
- }
537
- }
538
-
539
- /** 2fa: the submitted code was wrong, expired, or already used ({@link AuthErrorCode.TwoFactorCodeInvalid}). */
540
- export class TwoFactorCodeError extends AuthError {
541
- constructor() {
542
- super(AuthErrorCode.TwoFactorCodeInvalid, 'The verification code is invalid or expired.');
543
- this.name = 'TwoFactorCodeError';
544
- }
545
- }
546
-
547
- /** confirm: the email-confirmation link was invalid or expired ({@link AuthErrorCode.ConfirmationInvalid}). */
548
- export class ConfirmationInvalidError extends AuthError {
549
- constructor() {
550
- super(AuthErrorCode.ConfirmationInvalid, 'This confirmation link is invalid or has expired.');
551
- this.name = 'ConfirmationInvalidError';
552
- }
553
- }
554
-
555
- /** reset: the password-reset link was invalid or expired ({@link AuthErrorCode.PasswordResetInvalid}). */
556
- export class PasswordResetInvalidError extends AuthError {
557
- constructor() {
558
- super(AuthErrorCode.PasswordResetInvalid, 'This password-reset link is invalid or has expired.');
559
- this.name = 'PasswordResetInvalidError';
560
- }
561
- }
562
-
563
- // --- INPUT VALIDATION (client-side) --------------------------------------------------------------
564
- //
565
- // The password NEVER leaves this module (it is stretched into a key), so the SERVER
566
- // cannot enforce a password policy: it is enforced HERE, before any crypto or
567
- // network. Email + username are validated here too (and the server re-validates the
568
- // email format independently, since a hostile client can skip this). All exported so
569
- // a form can show live feedback with the SAME rules register/reset enforce.
570
-
571
- /** One password requirement. See {@link checkPassword} / {@link DEFAULT_PASSWORD_POLICY}. */
572
- export type PasswordRule = 'minLength' | 'maxLength' | 'digit' | 'uppercase' | 'special';
573
-
574
- /** The enforced password strength policy. */
575
- export interface PasswordPolicy {
576
- /** Minimum length. Default 8. */
577
- readonly minLength: number;
578
- /** Maximum length (guards against absurd inputs before Argon2id). Default 256. */
579
- readonly maxLength: number;
580
- /** Require at least one digit (0-9). Default true. */
581
- readonly digit: boolean;
582
- /** Require at least one uppercase letter (A-Z). Default true. */
583
- readonly uppercase: boolean;
584
- /** Require at least one special (non-alphanumeric) character. Default true. */
585
- readonly special: boolean;
586
- }
587
-
588
- /** The default policy: at least 8 characters, a digit, an uppercase letter, a special character. */
589
- export const DEFAULT_PASSWORD_POLICY: PasswordPolicy = {
590
- minLength: 8,
591
- maxLength: 256,
592
- digit: true,
593
- uppercase: true,
594
- special: true,
595
- };
596
-
597
- /** Human labels for the requirements, for messages or a live checklist. */
598
- export const PASSWORD_RULE_LABELS: Record<PasswordRule, string> = {
599
- minLength: 'at least 8 characters',
600
- maxLength: 'at most 256 characters',
601
- digit: 'a number',
602
- uppercase: 'an uppercase letter',
603
- special: 'a special character',
604
- };
605
-
606
- /**
607
- * Which password rules are UNMET (an empty array means the password is acceptable).
608
- * Pure and exported, so a form can show live feedback as the user types using the
609
- * SAME rules {@link register} / {@link resetPassword} enforce.
610
- */
611
- export function checkPassword(
612
- password: string,
613
- policy: PasswordPolicy = DEFAULT_PASSWORD_POLICY,
614
- ): PasswordRule[] {
615
- const unmet: PasswordRule[] = [];
616
- if (password.length < policy.minLength) unmet.push('minLength');
617
- if (password.length > policy.maxLength) unmet.push('maxLength');
618
- if (policy.digit && !/[0-9]/.test(password)) unmet.push('digit');
619
- if (policy.uppercase && !/[A-Z]/.test(password)) unmet.push('uppercase');
620
- if (policy.special && !/[^A-Za-z0-9]/.test(password)) unmet.push('special');
621
- return unmet;
622
- }
623
-
624
- /** Whether `email` is a plausible address (length 3 to 254, one `@`, a dotted domain). */
625
- export function isValidEmail(email: string): boolean {
626
- return email.length >= 3 && email.length <= 254 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
627
- }
628
-
629
- /** Whether `username` is a valid length (1 to 64), matching the server bound. */
630
- export function isValidUsername(username: string): boolean {
631
- return username.length >= 1 && username.length <= 64;
632
- }
633
-
634
- /** register/reset: the password failed the policy. `unmet` lists which rules failed so a
635
- * UI can render a precise checklist. {@link AuthErrorCode.WeakPassword}. */
636
- export class WeakPasswordError extends AuthError {
637
- readonly unmet: readonly PasswordRule[];
638
- constructor(unmet: readonly PasswordRule[]) {
639
- super(
640
- AuthErrorCode.WeakPassword,
641
- 'Password must have ' + unmet.map((r) => PASSWORD_RULE_LABELS[r]).join(', ') + '.',
642
- );
643
- this.name = 'WeakPasswordError';
644
- this.unmet = unmet;
645
- }
646
- }
647
-
648
- /** register: the email address is not a valid format ({@link AuthErrorCode.InvalidEmail}). */
649
- export class InvalidEmailError extends AuthError {
650
- constructor() {
651
- super(AuthErrorCode.InvalidEmail, 'Please enter a valid email address.');
652
- this.name = 'InvalidEmailError';
653
- }
654
- }
655
-
656
- /** register: the username is empty or too long ({@link AuthErrorCode.InvalidUsername}). */
657
- export class InvalidUsernameError extends AuthError {
658
- constructor() {
659
- super(AuthErrorCode.InvalidUsername, 'Username must be 1 to 64 characters.');
660
- this.name = 'InvalidUsernameError';
661
- }
662
- }
663
-
664
- /** The 2FA method values, mirroring the server enum (append-only). */
665
- export const TwoFactorMethod = { None: 0, Email: 1 } as const;
666
-
667
- /**
668
- * Complete a 2FA login: submit the delivered `code` for the challenge `twoFaId`
669
- * (from {@link TwoFactorRequiredError}). On success the server mints the session
670
- * (sets the cookies) and returns the opaque session token. Throws one generic
671
- * error ("code invalid or expired") on any failure -- the code is single-use and
672
- * attempt-limited server-side.
673
- */
674
- export async function verifyTwoFactor(
675
- twoFaId: string,
676
- code: string,
677
- opts: AuthOptions = {},
678
- ): Promise<Uint8Array> {
679
- const baseUrl = opts.baseUrl ?? '/auth';
680
- const res = await postBinary(
681
- baseUrl,
682
- '/2fa/verify',
683
- new DataWriter().writeBytes(fromHex(twoFaId)).writeString(code).toBytes(),
684
- );
685
- if (res.readU8() !== 0) throw new TwoFactorCodeError();
686
- return res.readBytes(); // opaque session token
687
- }
688
-
689
- /**
690
- * Begin enabling or disabling 2FA for the CURRENT session user. Pass a
691
- * {@link TwoFactorMethod} value (`Email` to enable email 2FA, `None` to disable).
692
- * The server delivers a proof code (to the new method when enabling, or the
693
- * CURRENT method when disabling - anti-hijack); confirm it with
694
- * {@link confirmTwoFactorSetup}. Requires a valid session.
695
- */
696
- export async function setupTwoFactor(method: number, opts: AuthOptions = {}): Promise<void> {
697
- const baseUrl = opts.baseUrl ?? '/auth';
698
- const res = await postBinary(
699
- baseUrl,
700
- '/2fa/setup',
701
- new DataWriter().writeU8(method).toBytes(),
702
- );
703
- if (res.readU8() !== 0)
704
- throw new AuthError(AuthErrorCode.TwoFactorSetupFailed, 'Enabling or disabling two-factor failed.');
705
- }
706
-
707
- /**
708
- * Confirm a pending {@link setupTwoFactor} by submitting the delivered `code`.
709
- * On success the account's 2FA method is switched (enabled or disabled). Requires
710
- * a valid session. Throws (generic) if the code is wrong or expired.
711
- */
712
- export async function confirmTwoFactorSetup(code: string, opts: AuthOptions = {}): Promise<void> {
713
- const baseUrl = opts.baseUrl ?? '/auth';
714
- const res = await postBinary(
715
- baseUrl,
716
- '/2fa/setup/verify',
717
- new DataWriter().writeString(code).toBytes(),
718
- );
719
- if (res.readU8() !== 0)
720
- throw new AuthError(AuthErrorCode.TwoFactorSetupFailed, 'Confirming the two-factor setup failed.');
721
- }
722
-
723
- /**
724
- * The current session user's 2FA method (a {@link TwoFactorMethod} value; `0` =
725
- * off). Requires a valid session. For the UI to reflect enabled/disabled state.
726
- */
727
- export async function twoFactorStatus(opts: AuthOptions = {}): Promise<number> {
728
- const baseUrl = opts.baseUrl ?? '/auth';
729
- const res = await fetch(baseUrl + '/2fa/status', {
730
- method: 'GET',
731
- credentials: 'same-origin',
732
- });
733
- if (!res.ok) throw new AuthError(AuthErrorCode.RequestFailed, 'The auth request failed.');
734
- return new DataReader(new Uint8Array(await res.arrayBuffer())).readU8();
735
- }
736
-
737
- /** Confirm an account from the one-time token in the emailed link
738
- * (`/confirm?token=<hex>`). Throws if the token is invalid or expired. */
739
- export async function confirmEmail(token: string, opts: AuthOptions = {}): Promise<void> {
740
- const baseUrl = opts.baseUrl ?? '/auth';
741
- const res = await postBinary(
742
- baseUrl,
743
- '/confirm',
744
- new DataWriter().writeBytes(fromHex(token)).toBytes(),
745
- );
746
- if (res.readU8() !== 0) throw new ConfirmationInvalidError();
747
- }
748
-
749
- /** Ask the server to re-send the confirmation email. Resolves regardless of
750
- * whether the email maps to an unconfirmed account (the server never reveals
751
- * it): treat success as "if that address needs confirming, a link is on its
752
- * way." */
753
- export async function resendConfirmation(email: string, opts: AuthOptions = {}): Promise<void> {
754
- const baseUrl = opts.baseUrl ?? '/auth';
755
- await postBinary(baseUrl, '/confirm/resend', new DataWriter().writeString(email).toBytes());
756
- }
757
-
758
- /** Begin a password reset: ask the server to email a reset link. Resolves
759
- * regardless of whether the email exists (anti-enumeration) — always show the
760
- * user "if that email exists, a reset link is on its way." */
761
- export async function requestPasswordReset(email: string, opts: AuthOptions = {}): Promise<void> {
762
- const baseUrl = opts.baseUrl ?? '/auth';
763
- await postBinary(baseUrl, '/reset/request', new DataWriter().writeString(email).toBytes());
764
- }
765
-
766
- /**
767
- * Complete a password reset from the one-time token in the emailed link
768
- * (`/reset?token=<hex>`) and a NEW password. Mirrors registration's crypto: the
769
- * new password is blinded through the OPRF, stretched with Argon2id into a fresh
770
- * ML-DSA keypair, and only the new public key (+ a proof-of-possession) is sent;
771
- * the server overwrites the stored login key. The username is recovered from the
772
- * token server-side, so the caller only needs the token + the new password.
773
- * Throws (generic) if the token is invalid or expired.
774
- */
775
- export async function resetPassword(
776
- token: string,
777
- newPassword: string,
778
- opts: AuthOptions = {},
779
- ): Promise<void> {
780
- const baseUrl = opts.baseUrl ?? '/auth';
781
- // The new password is subject to the same policy as registration.
782
- const weak = checkPassword(newPassword);
783
- if (weak.length > 0) throw new WeakPasswordError(weak);
784
- const rawToken = fromHex(token);
785
- const oprf = ristretto255_oprf.oprf;
786
- const pw = utf8(newPassword.normalize('NFKC'));
787
-
788
- // 1. Peek the token + OPRF-evaluate the new blinded password. The server
789
- // returns the account's username + KDF params (the token is not consumed
790
- // until finish).
791
- const { blind, blinded } = oprf.blind(pw);
792
- const start = await postBinary(
793
- baseUrl,
794
- '/reset/start',
795
- new DataWriter().writeBytes(rawToken).writeBytes(blinded).toBytes(),
796
- );
797
- if (start.readU8() !== 0) throw new PasswordResetInvalidError();
798
- const username = start.readString();
799
- const kdf = decodeKdf(start);
800
- const evaluated = start.readBytes();
801
-
802
- // 2. OPRF -> keyed salt -> seed -> NEW keypair; keep only the public key + a
803
- // PoP over it. Wipe the secret key and seed immediately.
804
- const oprfOutput = oprf.finalize(pw, blind, evaluated);
805
- const seed = await deriveSeed(oprfOutput, kdf);
806
- let publicKey: Uint8Array;
807
- let regProof: Uint8Array;
808
- try {
809
- const kp = ml_dsa44.keygen(seed);
810
- publicKey = kp.publicKey;
811
- try {
812
- regProof = ml_dsa44.sign(buildRegisterMessage(username, publicKey), kp.secretKey, {
813
- context: utf8(REGISTER_CONTEXT),
814
- });
815
- } finally {
816
- wipe(kp.secretKey);
817
- }
818
- } finally {
819
- wipe(seed);
820
- }
821
- if (publicKey.length !== PUBLIC_KEY_LEN)
822
- throw new AuthError(AuthErrorCode.ProtocolError, 'Server returned a bad public key length.');
823
-
824
- // 3. Consume the token + overwrite the stored login key.
825
- const finish = await postBinary(
826
- baseUrl,
827
- '/reset/finish',
828
- new DataWriter().writeBytes(rawToken).writeBytes(publicKey).writeBytes(regProof).toBytes(),
829
- );
830
- if (finish.readU8() !== 0) throw new PasswordResetInvalidError();
831
- }
832
-
833
- /** The client auth surface, grouped for `Auth.register` / `Auth.login` use. */
834
- export const Auth = {
835
- register,
836
- login,
837
- confirmEmail,
838
- resendConfirmation,
839
- requestPasswordReset,
840
- resetPassword,
841
- verifyTwoFactor,
842
- setupTwoFactor,
843
- confirmTwoFactorSetup,
844
- twoFactorStatus,
845
- TwoFactorMethod,
846
- buildLoginMessage,
847
- LOGIN_CONTEXT,
848
- // Typed error surface: branch on `Auth.AuthErrorCode` or `instanceof Auth.<X>Error`.
849
- AuthError,
850
- AuthErrorCode,
851
- UsernameTakenError,
852
- EmailInUseError,
853
- InvalidCredentialsError,
854
- EmailNotConfirmedError,
855
- TwoFactorRequiredError,
856
- ServerAuthFailedError,
857
- TwoFactorCodeError,
858
- ConfirmationInvalidError,
859
- PasswordResetInvalidError,
860
- WeakPasswordError,
861
- InvalidEmailError,
862
- InvalidUsernameError,
863
- // Input validation (exported so a form can show live feedback with the enforced rules).
864
- checkPassword,
865
- isValidEmail,
866
- isValidUsername,
867
- DEFAULT_PASSWORD_POLICY,
868
- PASSWORD_RULE_LABELS,
869
- } as const;