toiljs 0.0.115 → 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 (326) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +16 -7
  3. package/TYPESCRIPT_LAW.md +1946 -2073
  4. package/build/backend/.tsbuildinfo +1 -1
  5. package/build/cli/.tsbuildinfo +1 -1
  6. package/build/cli/index.js +2375 -258
  7. package/build/client/.tsbuildinfo +1 -1
  8. package/build/client/dev/devtools.js +1 -1
  9. package/build/client/dev/error-overlay.js +1 -1
  10. package/build/client/routing/mount.js +1 -1
  11. package/build/compiler/.tsbuildinfo +1 -1
  12. package/build/compiler/auth-emails.js +7 -3
  13. package/build/compiler/emails.js +1 -1
  14. package/build/compiler/index.d.ts +1 -0
  15. package/build/compiler/index.js +25 -4
  16. package/build/compiler/pages.js +2 -3
  17. package/build/compiler/prerender.d.ts +3 -8
  18. package/build/compiler/prerender.js +88 -127
  19. package/build/compiler/ssg.js +3 -4
  20. package/build/compiler/template-build.js +3 -4
  21. package/build/compiler/toil-docs.generated.js +6 -5
  22. package/build/compiler/vite.js +3 -6
  23. package/build/devserver/.tsbuildinfo +1 -1
  24. package/build/devserver/db/database.js +7 -3
  25. package/build/devserver/db/types.js +1 -1
  26. package/build/devserver/production.js +4 -3
  27. package/build/devserver/runtime/crypto.d.ts +1 -1
  28. package/build/io/.tsbuildinfo +1 -1
  29. package/build/logger/.tsbuildinfo +1 -1
  30. package/build/shared/.tsbuildinfo +1 -1
  31. package/examples/basic/client/routes/analytics.tsx +7 -5
  32. package/examples/basic/server/tsconfig.json +1 -3
  33. package/package.json +45 -44
  34. package/presets/no-uint8array-tostring.js +120 -153
  35. package/presets/oxlint.d.ts +5 -0
  36. package/presets/oxlint.js +224 -0
  37. package/server/runtime/tsconfig.json +1 -3
  38. package/tsconfig.json +2 -11
  39. package/.github/ISSUE_TEMPLATE/bug_report.md +0 -38
  40. package/.github/ISSUE_TEMPLATE/bug_report.yml +0 -90
  41. package/.github/ISSUE_TEMPLATE/config.yml +0 -8
  42. package/.github/ISSUE_TEMPLATE/feature_request.md +0 -20
  43. package/.github/PULL_REQUEST_TEMPLATE.md +0 -43
  44. package/.github/changelog-config.json +0 -45
  45. package/.github/dependabot.yml +0 -27
  46. package/.github/workflows/ci.yml +0 -222
  47. package/.vscode/settings.json +0 -10
  48. package/docs/README.md +0 -107
  49. package/docs/auth/README.md +0 -104
  50. package/docs/auth/configuration.md +0 -105
  51. package/docs/auth/emails.md +0 -92
  52. package/docs/auth/extending.md +0 -202
  53. package/docs/auth/how-it-works.md +0 -138
  54. package/docs/auth/usage.md +0 -188
  55. package/docs/backend/README.md +0 -143
  56. package/docs/backend/data.md +0 -351
  57. package/docs/backend/rest.md +0 -402
  58. package/docs/backend/rpc.md +0 -226
  59. package/docs/background/README.md +0 -114
  60. package/docs/background/daemons.md +0 -276
  61. package/docs/background/derive.md +0 -179
  62. package/docs/cli/README.md +0 -379
  63. package/docs/concepts/ai-guide.md +0 -132
  64. package/docs/concepts/config.md +0 -416
  65. package/docs/concepts/decorators.md +0 -127
  66. package/docs/concepts/security.md +0 -108
  67. package/docs/concepts/tiers.md +0 -166
  68. package/docs/concepts/types.md +0 -216
  69. package/docs/database/README.md +0 -143
  70. package/docs/database/capacity.md +0 -350
  71. package/docs/database/counters.md +0 -174
  72. package/docs/database/documents.md +0 -277
  73. package/docs/database/events.md +0 -307
  74. package/docs/database/membership.md +0 -246
  75. package/docs/database/setup.md +0 -155
  76. package/docs/database/unique.md +0 -216
  77. package/docs/database/views.md +0 -246
  78. package/docs/frontend/README.md +0 -104
  79. package/docs/frontend/components.md +0 -286
  80. package/docs/frontend/data-fetching.md +0 -260
  81. package/docs/frontend/images.md +0 -148
  82. package/docs/frontend/metadata.md +0 -344
  83. package/docs/frontend/navigation.md +0 -296
  84. package/docs/frontend/rendering.md +0 -236
  85. package/docs/frontend/routing.md +0 -346
  86. package/docs/frontend/scripts.md +0 -118
  87. package/docs/frontend/search.md +0 -191
  88. package/docs/frontend/styling.md +0 -147
  89. package/docs/frontend/toil-global.md +0 -216
  90. package/docs/getting-started/README.md +0 -81
  91. package/docs/getting-started/create-project.md +0 -131
  92. package/docs/getting-started/deploy.md +0 -101
  93. package/docs/getting-started/first-app.md +0 -215
  94. package/docs/getting-started/installation.md +0 -124
  95. package/docs/getting-started/migrating.md +0 -125
  96. package/docs/getting-started/project-structure.md +0 -163
  97. package/docs/introduction/README.md +0 -66
  98. package/docs/introduction/design-principles.md +0 -81
  99. package/docs/introduction/distributed.md +0 -91
  100. package/docs/introduction/how-it-works.md +0 -121
  101. package/docs/introduction/hyperscale.md +0 -70
  102. package/docs/introduction/modern-stack.md +0 -85
  103. package/docs/introduction/vs-other-frameworks.md +0 -64
  104. package/docs/introduction/why-toil.md +0 -99
  105. package/docs/llms.txt +0 -95
  106. package/docs/realtime/README.md +0 -102
  107. package/docs/realtime/channels.md +0 -211
  108. package/docs/realtime/streams.md +0 -369
  109. package/docs/services/README.md +0 -60
  110. package/docs/services/analytics.md +0 -279
  111. package/docs/services/caching.md +0 -175
  112. package/docs/services/cookies.md +0 -235
  113. package/docs/services/crypto.md +0 -209
  114. package/docs/services/email.md +0 -289
  115. package/docs/services/environment.md +0 -141
  116. package/docs/services/ratelimit.md +0 -174
  117. package/docs/services/time.md +0 -85
  118. package/eslint.config.js +0 -57
  119. package/examples/basic/client/routes/docs/[...slug].tsx +0 -12
  120. package/presets/eslint.js +0 -88
  121. package/src/backend/index.ts +0 -204
  122. package/src/cli/configure.ts +0 -363
  123. package/src/cli/create.ts +0 -924
  124. package/src/cli/db.ts +0 -158
  125. package/src/cli/diagnostics.ts +0 -665
  126. package/src/cli/doctor.ts +0 -982
  127. package/src/cli/features.ts +0 -170
  128. package/src/cli/index.ts +0 -326
  129. package/src/cli/notify.ts +0 -120
  130. package/src/cli/proc.ts +0 -56
  131. package/src/cli/ui.ts +0 -169
  132. package/src/cli/update.ts +0 -248
  133. package/src/cli/updates.ts +0 -92
  134. package/src/cli/validate.ts +0 -31
  135. package/src/cli/version-check.ts +0 -125
  136. package/src/client/auth.ts +0 -869
  137. package/src/client/channel/channel.ts +0 -146
  138. package/src/client/components/Form.tsx +0 -65
  139. package/src/client/components/Image.tsx +0 -160
  140. package/src/client/components/Script.tsx +0 -113
  141. package/src/client/components/Slot.tsx +0 -21
  142. package/src/client/dev/devtools.tsx +0 -1089
  143. package/src/client/dev/error-overlay.tsx +0 -225
  144. package/src/client/errors.ts +0 -11
  145. package/src/client/head/head.ts +0 -182
  146. package/src/client/head/metadata.ts +0 -110
  147. package/src/client/index.ts +0 -130
  148. package/src/client/navigation/Link.tsx +0 -108
  149. package/src/client/navigation/NavLink.tsx +0 -86
  150. package/src/client/navigation/navigation.ts +0 -235
  151. package/src/client/navigation/prefetch.ts +0 -169
  152. package/src/client/navigation/scroll.ts +0 -53
  153. package/src/client/routing/Router.tsx +0 -216
  154. package/src/client/routing/action.ts +0 -122
  155. package/src/client/routing/error-boundary.tsx +0 -43
  156. package/src/client/routing/hooks.ts +0 -140
  157. package/src/client/routing/lazy.ts +0 -77
  158. package/src/client/routing/loader.ts +0 -381
  159. package/src/client/routing/match.ts +0 -47
  160. package/src/client/routing/mount.tsx +0 -90
  161. package/src/client/routing/params-context.ts +0 -10
  162. package/src/client/routing/slot-context.ts +0 -7
  163. package/src/client/rpc.ts +0 -97
  164. package/src/client/search/search.ts +0 -189
  165. package/src/client/search/use-page-search.ts +0 -73
  166. package/src/client/ssr/markers.tsx +0 -172
  167. package/src/client/stream/client.ts +0 -237
  168. package/src/client/types.ts +0 -73
  169. package/src/compiler/auth-emails.ts +0 -312
  170. package/src/compiler/config.ts +0 -369
  171. package/src/compiler/docs.ts +0 -127
  172. package/src/compiler/email-preview.ts +0 -314
  173. package/src/compiler/emails.ts +0 -404
  174. package/src/compiler/fonts.ts +0 -89
  175. package/src/compiler/generate.ts +0 -471
  176. package/src/compiler/image-blur.ts +0 -42
  177. package/src/compiler/image-report.ts +0 -88
  178. package/src/compiler/index.ts +0 -1362
  179. package/src/compiler/pages.ts +0 -49
  180. package/src/compiler/plugin.ts +0 -391
  181. package/src/compiler/prerender.ts +0 -263
  182. package/src/compiler/routes.ts +0 -170
  183. package/src/compiler/seo.ts +0 -415
  184. package/src/compiler/sri.ts +0 -144
  185. package/src/compiler/ssg.ts +0 -177
  186. package/src/compiler/ssr-codegen.ts +0 -85
  187. package/src/compiler/template-build.ts +0 -676
  188. package/src/compiler/template.ts +0 -262
  189. package/src/compiler/toil-docs.generated.ts +0 -77
  190. package/src/compiler/vite.ts +0 -245
  191. package/src/devserver/analytics/index.ts +0 -317
  192. package/src/devserver/config/dotenv.ts +0 -102
  193. package/src/devserver/config/env.ts +0 -30
  194. package/src/devserver/config/ratelimit.ts +0 -123
  195. package/src/devserver/daemon/catalog.ts +0 -120
  196. package/src/devserver/daemon/cron.ts +0 -87
  197. package/src/devserver/daemon/host.ts +0 -134
  198. package/src/devserver/daemon/index.ts +0 -369
  199. package/src/devserver/daemon/runtime.ts +0 -48
  200. package/src/devserver/db/catalog.ts +0 -109
  201. package/src/devserver/db/database.ts +0 -1834
  202. package/src/devserver/db/derives.ts +0 -121
  203. package/src/devserver/db/index.ts +0 -20
  204. package/src/devserver/db/routeKinds.ts +0 -191
  205. package/src/devserver/db/types.ts +0 -168
  206. package/src/devserver/email/caps.ts +0 -0
  207. package/src/devserver/email/config.ts +0 -141
  208. package/src/devserver/email/console.ts +0 -348
  209. package/src/devserver/email/index.ts +0 -155
  210. package/src/devserver/email/providers.ts +0 -131
  211. package/src/devserver/email/status.ts +0 -23
  212. package/src/devserver/email/validate.ts +0 -37
  213. package/src/devserver/email/wire.ts +0 -55
  214. package/src/devserver/http/cache.ts +0 -0
  215. package/src/devserver/http/envelope.ts +0 -157
  216. package/src/devserver/http/proxy.ts +0 -172
  217. package/src/devserver/http/runtime.ts +0 -387
  218. package/src/devserver/index.ts +0 -43
  219. package/src/devserver/production-ipc.ts +0 -63
  220. package/src/devserver/production-worker.ts +0 -83
  221. package/src/devserver/production.ts +0 -718
  222. package/src/devserver/runtime/crypto.ts +0 -587
  223. package/src/devserver/runtime/host.ts +0 -427
  224. package/src/devserver/runtime/module.ts +0 -442
  225. package/src/devserver/server.ts +0 -251
  226. package/src/devserver/ssr.ts +0 -208
  227. package/src/devserver/stream/catalog.ts +0 -106
  228. package/src/devserver/stream/host.ts +0 -42
  229. package/src/devserver/stream/index.ts +0 -301
  230. package/src/devserver/stream/manager.ts +0 -167
  231. package/src/devserver/stream/router.ts +0 -101
  232. package/src/devserver/stream/wire.ts +0 -58
  233. package/src/devserver/stream/ws.ts +0 -78
  234. package/src/devserver/wasm/sections.ts +0 -59
  235. package/src/devserver/wasm/surface.ts +0 -115
  236. package/src/io/FastMap.ts +0 -151
  237. package/src/io/FastSet.ts +0 -113
  238. package/src/io/codec.ts +0 -362
  239. package/src/io/index.ts +0 -10
  240. package/src/io/lengths.ts +0 -14
  241. package/src/io/types.ts +0 -19
  242. package/src/logger/index.ts +0 -22
  243. package/src/shared/index.ts +0 -46
  244. package/test/analytics-dev.test.ts +0 -113
  245. package/test/assembly/aspect-shim.ts +0 -33
  246. package/test/assembly/cookie.spec.ts +0 -303
  247. package/test/assembly/example.spec.ts +0 -22
  248. package/test/assembly/ssr.spec.ts +0 -95
  249. package/test/assembly.test.ts +0 -59
  250. package/test/auth-emails.test.ts +0 -118
  251. package/test/built-ssr.test.ts +0 -148
  252. package/test/channel.test.ts +0 -21
  253. package/test/config-host-port.test.ts +0 -59
  254. package/test/configure.test.ts +0 -94
  255. package/test/daemon-build.test.ts +0 -278
  256. package/test/daemon-catalog.test.ts +0 -349
  257. package/test/daemon-emulation.test.ts +0 -256
  258. package/test/db.test.ts +0 -0
  259. package/test/devserver-database.test.ts +0 -1102
  260. package/test/devserver-email.test.ts +0 -306
  261. package/test/devserver-pqauth.test.ts +0 -93
  262. package/test/devserver-secrets.test.ts +0 -63
  263. package/test/devserver.test.ts +0 -259
  264. package/test/doctor.test.ts +0 -298
  265. package/test/dom/Image.test.tsx +0 -144
  266. package/test/dom/Link.test.tsx +0 -67
  267. package/test/dom/NavLink.test.tsx +0 -37
  268. package/test/dom/Script.test.tsx +0 -48
  269. package/test/dom/action.test.tsx +0 -146
  270. package/test/dom/error-overlay.test.tsx +0 -44
  271. package/test/dom/loader.test.tsx +0 -121
  272. package/test/dom/navigation.test.ts +0 -59
  273. package/test/dom/revalidate.test.tsx +0 -38
  274. package/test/dom/route-head.test.tsx +0 -56
  275. package/test/dom/router-loading.test.tsx +0 -44
  276. package/test/dom/scroll.test.ts +0 -56
  277. package/test/dom/slot.test.tsx +0 -131
  278. package/test/dom/use-metadata.test.tsx +0 -58
  279. package/test/dom/view-transitions.test.tsx +0 -53
  280. package/test/dynamic-routing.test.ts +0 -132
  281. package/test/email-console.test.ts +0 -86
  282. package/test/email-preview.test.ts +0 -73
  283. package/test/emails.test.ts +0 -58
  284. package/test/errors.test.ts +0 -21
  285. package/test/example-guestbook.test.ts +0 -123
  286. package/test/features.test.ts +0 -149
  287. package/test/fixtures/bignum-wire/spec.ts +0 -25
  288. package/test/fixtures/daemon-app.ts +0 -65
  289. package/test/fixtures/stream-echo.ts +0 -26
  290. package/test/fixtures/stream-gate.ts +0 -28
  291. package/test/fixtures/stream-trap.ts +0 -18
  292. package/test/fixtures/stream-typed.ts +0 -41
  293. package/test/fonts.test.ts +0 -28
  294. package/test/global-setup.ts +0 -17
  295. package/test/head.test.ts +0 -42
  296. package/test/image-blur.test.ts +0 -50
  297. package/test/io.test.ts +0 -117
  298. package/test/metadata.test.ts +0 -40
  299. package/test/navlink.test.ts +0 -28
  300. package/test/pages.test.ts +0 -105
  301. package/test/placeholder.test.ts +0 -9
  302. package/test/pqauth-e2e.test.ts +0 -216
  303. package/test/pqauth-email.test.ts +0 -801
  304. package/test/prerender.test.ts +0 -116
  305. package/test/prettier-plugin.test.ts +0 -46
  306. package/test/routes.test.ts +0 -76
  307. package/test/rpc-bignum-wire.test.ts +0 -164
  308. package/test/rpc-dispatch.test.ts +0 -132
  309. package/test/rpc-kinds.test.ts +0 -18
  310. package/test/rpc.test.ts +0 -66
  311. package/test/search.test.ts +0 -114
  312. package/test/seo.test.ts +0 -175
  313. package/test/slot-layouts.test.ts +0 -69
  314. package/test/sri.test.ts +0 -129
  315. package/test/ssg.test.ts +0 -36
  316. package/test/ssr-hydration.test.tsx +0 -122
  317. package/test/ssr-render.test.ts +0 -197
  318. package/test/ssr-template.test.tsx +0 -482
  319. package/test/stream-emulation.test.ts +0 -479
  320. package/test/ui.test.ts +0 -40
  321. package/test/update.test.ts +0 -58
  322. package/test/validate.test.ts +0 -42
  323. package/test/version-check.test.ts +0 -130
  324. package/tests/data-parity/generated-parity.ts +0 -99
  325. package/tests/data-parity/parity.ts +0 -80
  326. 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;