toiljs 0.0.127 → 0.0.129

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 (145) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/assets/image-codec-LICENSES.txt +4599 -0
  3. package/assets/image-codec-build.json +10 -0
  4. package/assets/image-codec.wasm +0 -0
  5. package/build/backend/index.d.ts +1 -0
  6. package/build/backend/index.js +8 -3
  7. package/build/backend/security.d.ts +4 -0
  8. package/build/backend/security.js +31 -0
  9. package/build/cli/index.js +11 -39
  10. package/build/client/components/Script.js +28 -17
  11. package/build/client/files.d.ts +17 -0
  12. package/build/client/files.js +119 -0
  13. package/build/client/html.d.ts +1 -0
  14. package/build/client/html.js +8 -0
  15. package/build/client/index.d.ts +1 -0
  16. package/build/client/index.js +1 -0
  17. package/build/client/security.d.ts +4 -0
  18. package/build/client/security.js +55 -0
  19. package/build/client/ssr/markers.js +6 -1
  20. package/build/compiler/config.d.ts +2 -0
  21. package/build/compiler/config.js +1 -0
  22. package/build/compiler/generate.d.ts +1 -1
  23. package/build/compiler/generate.js +1 -37
  24. package/build/compiler/index.d.ts +1 -0
  25. package/build/compiler/index.js +56 -1
  26. package/build/compiler/security-deployment.d.ts +3 -0
  27. package/build/compiler/security-deployment.js +88 -0
  28. package/build/compiler/security.d.ts +7 -0
  29. package/build/compiler/security.js +74 -0
  30. package/build/compiler/sri.js +10 -3
  31. package/build/compiler/toil-docs.generated.js +35 -28
  32. package/build/compiler/vite.js +2 -0
  33. package/build/devserver/config/env.d.ts +6 -0
  34. package/build/devserver/config/env.js +10 -2
  35. package/build/devserver/daemon/catalog.d.ts +1 -0
  36. package/build/devserver/daemon/catalog.js +10 -4
  37. package/build/devserver/daemon/host.d.ts +5 -1
  38. package/build/devserver/daemon/host.js +8 -4
  39. package/build/devserver/daemon/http.d.ts +14 -0
  40. package/build/devserver/daemon/http.js +90 -0
  41. package/build/devserver/daemon/index.d.ts +21 -1
  42. package/build/devserver/daemon/index.js +109 -21
  43. package/build/devserver/db/atomic.d.ts +8 -0
  44. package/build/devserver/db/atomic.js +133 -0
  45. package/build/devserver/db/catalog.d.ts +7 -0
  46. package/build/devserver/db/catalog.js +17 -0
  47. package/build/devserver/db/changes.d.ts +5 -0
  48. package/build/devserver/db/changes.js +49 -0
  49. package/build/devserver/db/database.d.ts +7 -0
  50. package/build/devserver/db/database.js +251 -41
  51. package/build/devserver/db/derives.d.ts +4 -5
  52. package/build/devserver/db/derives.js +7 -76
  53. package/build/devserver/db/document-scan.d.ts +2 -0
  54. package/build/devserver/db/document-scan.js +123 -0
  55. package/build/devserver/db/limits.d.ts +16 -0
  56. package/build/devserver/db/limits.js +92 -14
  57. package/build/devserver/db/types.d.ts +15 -0
  58. package/build/devserver/db/types.js +9 -0
  59. package/build/devserver/files/dev.d.ts +3 -0
  60. package/build/devserver/files/dev.js +29 -0
  61. package/build/devserver/files/disk.d.ts +17 -0
  62. package/build/devserver/files/disk.js +369 -0
  63. package/build/devserver/files/signatures.d.ts +16 -0
  64. package/build/devserver/files/signatures.js +151 -0
  65. package/build/devserver/http/proxy.js +11 -3
  66. package/build/devserver/http/runtime.js +36 -9
  67. package/build/devserver/images/index.d.ts +9 -0
  68. package/build/devserver/images/index.js +87 -0
  69. package/build/devserver/images/worker.d.mts +1 -0
  70. package/build/devserver/images/worker.mjs +24 -0
  71. package/build/devserver/index.d.ts +3 -1
  72. package/build/devserver/production.js +5 -3
  73. package/build/devserver/runtime/host.d.ts +4 -0
  74. package/build/devserver/runtime/host.js +6 -2
  75. package/build/devserver/runtime/module.d.ts +15 -0
  76. package/build/devserver/runtime/module.js +105 -7
  77. package/build/devserver/server.js +13 -1
  78. package/build/devserver/stream/host.d.ts +2 -0
  79. package/build/devserver/stream/host.js +2 -1
  80. package/build/devserver/stream/index.js +2 -0
  81. package/build/io/derive-metadata.d.ts +7 -0
  82. package/build/io/derive-metadata.js +44 -0
  83. package/build/io/index.d.ts +1 -0
  84. package/build/io/index.js +1 -0
  85. package/build/shared/index.d.ts +1 -0
  86. package/build/shared/index.js +1 -0
  87. package/build/shared/security.d.ts +5 -0
  88. package/build/shared/security.js +80 -0
  89. package/docs/auth/vectors-v1.json +41 -0
  90. package/examples/basic/client/routes/rest.tsx +1 -1
  91. package/examples/basic/server/routes/Guestbook.ts +1 -1
  92. package/package.json +20 -7
  93. package/scripts/build-image-codec.mjs +79 -0
  94. package/scripts/gen-auth-vectors.mjs +132 -0
  95. package/scripts/gen-native-atomic-fixture.mjs +39 -0
  96. package/scripts/gen-native-blob-fixture.mjs +42 -0
  97. package/scripts/gen-native-image-fixture.mjs +65 -0
  98. package/scripts/gen-native-staging-fixture.mjs +41 -0
  99. package/scripts/gen-server-types.mjs +82 -0
  100. package/scripts/gen-toil-docs.mjs +19 -7
  101. package/server/auth/AuthController.ts +15 -234
  102. package/server/auth/AuthMaintenance.ts +177 -0
  103. package/server/auth/AuthStore.ts +198 -0
  104. package/server/auth/SessionEpochs.ts +38 -9
  105. package/server/globals/auth.ts +56 -0
  106. package/server/globals/userid.ts +4 -5
  107. package/server/globals.d.ts +37 -0
  108. package/server/runtime/envelope.ts +2 -1
  109. package/server/runtime/exports/index.ts +2 -1
  110. package/server/runtime/files/blobs.ts +341 -0
  111. package/server/runtime/files/images.ts +36 -0
  112. package/server/runtime/http/percent.ts +5 -4
  113. package/server/runtime/index.ts +5 -0
  114. package/server/runtime/response.ts +20 -0
  115. package/server/runtime/rest/RouteContext.ts +5 -4
  116. package/std/server/abort/abort.d.ts +25 -0
  117. package/std/server/env/Server.d.ts +47 -0
  118. package/std/server/envelope.d.ts +38 -0
  119. package/std/server/exports/index.d.ts +20 -0
  120. package/std/server/exports/render.d.ts +15 -0
  121. package/std/server/files/blobs.d.ts +50 -0
  122. package/std/server/files/images.d.ts +36 -0
  123. package/std/server/handlers/ToilHandler.d.ts +29 -0
  124. package/std/server/http/base64.d.ts +21 -0
  125. package/std/server/http/cookie.d.ts +127 -0
  126. package/std/server/http/cookies.d.ts +56 -0
  127. package/std/server/http/date.d.ts +17 -0
  128. package/std/server/http/percent.d.ts +19 -0
  129. package/std/server/http/securecookies.d.ts +55 -0
  130. package/std/server/index.d.ts +34 -0
  131. package/std/server/lang/Potential.d.ts +6 -0
  132. package/std/server/memory.d.ts +42 -0
  133. package/std/server/request.d.ts +47 -0
  134. package/std/server/response.d.ts +90 -0
  135. package/std/server/rest/Rest.d.ts +23 -0
  136. package/std/server/rest/RestHandler.d.ts +14 -0
  137. package/std/server/rest/RouteContext.d.ts +33 -0
  138. package/std/server/rest/match.d.ts +14 -0
  139. package/std/server/rpc/Rpc.d.ts +37 -0
  140. package/std/server/ssr/Ssr.d.ts +27 -0
  141. package/std/server/ssr/encode.d.ts +26 -0
  142. package/std/server/ssr/escape.d.ts +22 -0
  143. package/std/server/ssr/slots.d.ts +91 -0
  144. package/std/server/time.d.ts +24 -0
  145. package/tsconfig.json +11 -2
@@ -0,0 +1,41 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { mkdtempSync, readFileSync, writeFileSync, rmSync, mkdirSync, symlinkSync } from 'node:fs';
3
+ import { createHash } from 'node:crypto';
4
+ import { tmpdir } from 'node:os';
5
+ import { dirname, join, resolve } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
8
+ const backend = resolve(process.argv[2] ?? join(root, '../toil-backend'));
9
+ const directory = join(backend, 'tests/fixtures/native-staging');
10
+ const temporary = mkdtempSync(join(tmpdir(), 'toil-native-staging-'));
11
+ try {
12
+ mkdirSync(join(temporary, 'node_modules'));
13
+ symlinkSync(root, join(temporary, 'node_modules/toiljs'));
14
+ writeFileSync(join(temporary, 'app.ts'), readFileSync(join(directory, 'request_src.ts')));
15
+ const compiled = spawnSync(
16
+ process.execPath,
17
+ [
18
+ process.env.TOILSCRIPT_TEST_BIN ??
19
+ join(root, 'node_modules/toilscript/bin/toilscript.js'),
20
+ 'app.ts',
21
+ '-o',
22
+ join(directory, 'request.wasm'),
23
+ '--runtime',
24
+ 'stub',
25
+ '--memoryBase',
26
+ '65536',
27
+ ],
28
+ { cwd: temporary, encoding: 'utf8' },
29
+ );
30
+ if (compiled.status !== 0) throw new Error(compiled.stdout + compiled.stderr);
31
+ const hash = createHash('sha256')
32
+ .update(readFileSync(join(directory, 'request.wasm')))
33
+ .digest('hex');
34
+ writeFileSync(
35
+ join(directory, 'HOW_BUILT.txt'),
36
+ `Source: request_src.ts, using the public ToilScript SDK and toiljs server runtime.\nRegenerate from toiljs:\n TOILSCRIPT_TEST_BIN=/path/to/toilscript/bin/toilscript.js node scripts/gen-native-staging-fixture.mjs /path/to/toil-backend\nSHA256 request.wasm: ${hash}\n`,
37
+ );
38
+ console.log('Generated native staging fixture:', hash);
39
+ } finally {
40
+ rmSync(temporary, { recursive: true, force: true });
41
+ }
@@ -0,0 +1,82 @@
1
+ // Ship declarations separately from ToilScript source so a clean tree can be
2
+ // typechecked without asking tsc to understand the WebAssembly dialect.
3
+ import { spawnSync } from 'node:child_process';
4
+ import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
5
+ import { createRequire } from 'node:module';
6
+ import { tmpdir } from 'node:os';
7
+ import { dirname, join, relative, resolve } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
10
+ const sourceRoot = join(root, 'server/runtime');
11
+ const outRoot = join(root, 'std/server');
12
+ function sources(dir) {
13
+ return readdirSync(dir, { withFileTypes: true }).flatMap((entry) =>
14
+ entry.isDirectory()
15
+ ? sources(join(dir, entry.name))
16
+ : entry.name.endsWith('.ts') && !entry.name.endsWith('.d.ts')
17
+ ? [join(dir, entry.name)]
18
+ : [],
19
+ );
20
+ }
21
+ const require = createRequire(import.meta.url);
22
+ const assemblyTypes = join(
23
+ dirname(require.resolve('toilscript/package.json')),
24
+ 'std/types/assembly/index.d.ts',
25
+ );
26
+ const tmp = mkdtempSync(join(tmpdir(), 'toil-server-types-'));
27
+ try {
28
+ const config = join(tmp, 'tsconfig.json');
29
+ writeFileSync(
30
+ config,
31
+ JSON.stringify({
32
+ files: [...sources(sourceRoot), assemblyTypes],
33
+ compilerOptions: {
34
+ declaration: true,
35
+ emitDeclarationOnly: true,
36
+ noCheck: true,
37
+ skipLibCheck: true,
38
+ module: 'ESNext',
39
+ target: 'ESNext',
40
+ moduleResolution: 'bundler',
41
+ experimentalDecorators: true,
42
+ noLib: true,
43
+ types: [],
44
+ rootDir: root,
45
+ outDir: join(tmp, 'out'),
46
+ },
47
+ }),
48
+ );
49
+ const bin = join(dirname(require.resolve('typescript/package.json')), 'bin/tsc');
50
+ const emitted = spawnSync(process.execPath, [bin, '-p', config], {
51
+ cwd: root,
52
+ encoding: 'utf8',
53
+ });
54
+ if (emitted.status !== 0) throw new Error(emitted.stdout + emitted.stderr);
55
+ const emittedRoot = join(tmp, 'out/server/runtime');
56
+ rmSync(outRoot, { recursive: true, force: true });
57
+ function copy(dir) {
58
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
59
+ const file = join(dir, entry.name);
60
+ if (entry.isDirectory()) {
61
+ copy(file);
62
+ continue;
63
+ }
64
+ if (!entry.name.endsWith('.d.ts')) continue;
65
+ const rel = relative(emittedRoot, file);
66
+ const path = join(outRoot, rel);
67
+ mkdirSync(dirname(path), { recursive: true });
68
+ const prefix =
69
+ rel === 'index.d.ts' ? '/// <reference path="../../server/globals.d.ts" />\n' : '';
70
+ writeFileSync(
71
+ path,
72
+ '// Generated from server/runtime by scripts/gen-server-types.mjs.\n' +
73
+ prefix +
74
+ readFileSync(file, 'utf8'),
75
+ );
76
+ }
77
+ }
78
+ copy(emittedRoot);
79
+ readFileSync(join(outRoot, 'index.d.ts'));
80
+ } finally {
81
+ rmSync(tmp, { recursive: true, force: true });
82
+ }
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * Build-time generator: turns the human Markdown guides in `docs/` into the agent
4
- * documentation map (`TOIL_DOCS`) consumed by the compiler.
3
+ * Build-time generator: bundles the human Markdown guides and explicitly
4
+ * published resources in `docs/` into the compiler's `TOIL_DOCS` map.
5
5
  *
6
6
  * `docs/*.md` is the SINGLE SOURCE for both the human docs (the site) and the agent
7
7
  * docs written into a project's `.toil/docs/` on `toiljs dev` / `build` / `create`.
8
8
  * This script reads every published guide, builds `Record<filename, content>`, and
9
9
  * writes a generated TS module that `src/compiler/docs.ts` imports. The generated
10
10
  * file is gitignored and (re)created before `build:compiler`, so the shipped
11
- * compiler never reads the filesystem at a user's build time, and the npm package
12
- * does not need to carry `docs/`.
11
+ * compiler never reads the source docs at a user's build time. The npm package
12
+ * also carries the portable auth-vector JSON for direct consumers.
13
13
  *
14
14
  * Run: `node scripts/gen-toil-docs.mjs` (wired into `npm run build`).
15
15
  */
@@ -29,6 +29,9 @@ const outFile = path.join(repoRoot, 'src', 'compiler', 'toil-docs.generated.ts')
29
29
  */
30
30
  const EXCLUDE = new Set();
31
31
 
32
+ // Only explicitly published non-Markdown resources belong in generated docs.
33
+ const RESOURCES = new Set(['auth/vectors-v1.json']);
34
+
32
35
  /**
33
36
  * Stable order for the agent docs: the root landing page first, then every
34
37
  * other guide alphabetically by its repo-relative path (which naturally groups
@@ -42,10 +45,16 @@ function collect() {
42
45
  // repo-relative path (`auth/index.md`). Adding a `docs/**/*.md` is picked up automatically.
43
46
  const files = [];
44
47
  const walk = (dir, prefix) => {
45
- for (const ent of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
48
+ for (const ent of fs
49
+ .readdirSync(dir, { withFileTypes: true })
50
+ .sort((a, b) => a.name.localeCompare(b.name))) {
46
51
  if (ent.isDirectory()) {
47
52
  walk(path.join(dir, ent.name), prefix + ent.name + '/');
48
- } else if (ent.name.endsWith('.md') && !EXCLUDE.has(prefix + ent.name) && !EXCLUDE.has(ent.name)) {
53
+ } else if (
54
+ (ent.name.endsWith('.md') || RESOURCES.has(prefix + ent.name)) &&
55
+ !EXCLUDE.has(prefix + ent.name) &&
56
+ !EXCLUDE.has(ent.name)
57
+ ) {
49
58
  files.push(prefix + ent.name);
50
59
  }
51
60
  }
@@ -59,6 +68,9 @@ function collect() {
59
68
  for (const name of ordered) {
60
69
  out[name] = fs.readFileSync(path.join(docsDir, name), 'utf8');
61
70
  }
71
+ for (const name of RESOURCES) {
72
+ if (!(name in out)) throw new Error(`Missing published documentation resource: ${name}`);
73
+ }
62
74
  return out;
63
75
  }
64
76
 
@@ -72,7 +84,7 @@ function emit(map) {
72
84
  '// `docs/*.md` is the single source for both the human docs and these agent docs.\n' +
73
85
  '// Regenerate with `node scripts/gen-toil-docs.mjs` (runs before `build:compiler`).\n' +
74
86
  '\n' +
75
- '/** The framework guides written into `.toil/docs/`, keyed by filename, generated from `docs/`. */\n' +
87
+ '/** Framework guides and linked resources written into `.toil/docs/`, keyed by filename. */\n' +
76
88
  'export const TOIL_DOCS: Record<string, string> = {\n' +
77
89
  entries +
78
90
  '\n};\n'
@@ -1,3 +1,5 @@
1
+ import { Username, EmailKey, EmailOwner, TokenId, TokenRec, ChallengeId, AuthAccount, Challenge, TwoFaId, TwoFaChallenge, DeletedAccountKey, DeletedAccountMarker, AuthDb } from './AuthStore';
2
+ import { AuthMaintenance } from './AuthMaintenance';
1
3
  import { FactorRepository } from './FactorSettings';
2
4
  import { SessionEpochs } from './SessionEpochs';
3
5
  import { Response, RouteContext } from 'toiljs/server/runtime';
@@ -45,7 +47,7 @@ import { DataReader, DataWriter } from 'data';
45
47
  * token in the emailed link is usable), each carrying its own expiry (there is no
46
48
  * native TTL; expiry is checked against the clock, consume-before-validate). The
47
49
  * dev server emulates these `env.data.*` host imports in process; the production
48
- * edge backs the SAME API with ScyllaDB.
50
+ * edge backs the SAME API with persistent ToilDB.
49
51
  *
50
52
  * Wire: every body/response is binary (`DataWriter`/`DataReader`), never JSON.
51
53
  *
@@ -412,183 +414,6 @@ function isValidEmail(email: string): bool {
412
414
  return true;
413
415
  }
414
416
 
415
- // Every lookup KEY carries the tenant `host` (realm) as its FIRST field, so the
416
- // physical key includes the domain and the SAME logical name/email/id addresses a
417
- // DIFFERENT row per host (cross-domain isolation, on top of toildb's per-tenant
418
- // scoping). `host` is populated from `realm(ctx)` at every call site.
419
- @data
420
- class Username {
421
- host: string = '';
422
- name: string = '';
423
- constructor(host: string = '', name: string = '') {
424
- this.host = host;
425
- this.name = name;
426
- }
427
- }
428
-
429
- @data
430
- class EmailKey {
431
- host: string = '';
432
- email: string = '';
433
- constructor(host: string = '', email: string = '') {
434
- this.host = host;
435
- this.email = email;
436
- }
437
- }
438
-
439
- @data
440
- class EmailOwner {
441
- username: string = '';
442
- accountId: Uint8Array = new Uint8Array(0);
443
- constructor(username: string = '', accountId: Uint8Array = new Uint8Array(0)) {
444
- this.username = username;
445
- this.accountId = accountId;
446
- }
447
- }
448
-
449
- @data
450
- class TokenId {
451
- hash: Uint8Array = new Uint8Array(0);
452
- constructor(hash: Uint8Array = new Uint8Array(0)) {
453
- this.hash = hash;
454
- }
455
- }
456
-
457
- /** A one-time confirm/reset token record: which account it authorizes + its
458
- * absolute expiry (unix secs). Consumed with `getDelete`. */
459
- @data
460
- class TokenRec {
461
- username: string = '';
462
- exp: u64 = 0;
463
- accountId: Uint8Array = new Uint8Array(0);
464
- }
465
-
466
- @data
467
- class ChallengeId {
468
- host: string = '';
469
- cid: Uint8Array = new Uint8Array(0);
470
- constructor(host: string = '', cid: Uint8Array = new Uint8Array(0)) {
471
- this.host = host;
472
- this.cid = cid;
473
- }
474
- }
475
-
476
- @data
477
- class AuthAccount {
478
- // The original credential fields keep their byte positions; `email` +
479
- // `emailConfirmed` are APPENDED so this is a forward-compatible, append-only
480
- // @data change (an old row decodes with emailConfirmed=false, the strict/safe
481
- // default) rather than a breaking mid-struct reorder the deploy gate rejects.
482
- username: string = '';
483
- salt: Uint8Array = new Uint8Array(0);
484
- publicKey: Uint8Array = new Uint8Array(0);
485
- memKiB: u32 = 0;
486
- iterations: u32 = 0;
487
- parallelism: u32 = 0;
488
- email: string = '';
489
- emailConfirmed: bool = false;
490
- // APPENDED (append-only, forward-compatible like `email` above): the account's
491
- // second-factor method (see the TWOFA_* enum). An old row decodes as 0 =
492
- // TWOFA_NONE (2FA off), the safe default, so existing accounts stay logged in
493
- // by password alone until they opt in via /auth/2fa/setup.
494
- twoFactorMethod: u8 = 0;
495
- // Append-only: the STABLE ToilUserId, derived once at registration. Reset rotates
496
- // publicKey but leaves this, so the id is stable across a reset.
497
- toilUserId: Uint8Array = new Uint8Array(0);
498
- // Account incarnation: never reused, even when username/password are reused.
499
- accountId: Uint8Array = new Uint8Array(0);
500
- deleting: bool = false;
501
- registering: bool = false;
502
- legacyFactors: bool = false;
503
- }
504
-
505
- @data
506
- class Challenge {
507
- cid: Uint8Array = new Uint8Array(0);
508
- username: string = '';
509
- nonce: Uint8Array = new Uint8Array(0);
510
- iat: u64 = 0;
511
- exp: u64 = 0;
512
- sessionEpoch: u64 = 0;
513
- sessionVersion: u8 = 0;
514
- accountId: Uint8Array = new Uint8Array(0);
515
- }
516
-
517
- /** The lookup key for a login 2FA challenge: 16 random bytes minted per login.
518
- * Lives in its OWN collection (twoFaLogins), a SEPARATE NAMESPACE from
519
- * confirm/reset TokenId, so a confirm/reset token can never resolve here. */
520
- @data
521
- class TwoFaId {
522
- host: string = '';
523
- id: Uint8Array = new Uint8Array(0);
524
- constructor(host: string = '', id: Uint8Array = new Uint8Array(0)) {
525
- this.host = host;
526
- this.id = id;
527
- }
528
- }
529
-
530
- /**
531
- * A pending second-factor challenge (login OR setup). METHOD-AGNOSTIC lifecycle
532
- * fields (username / exp / attempts) plus the per-method `codeHash`; `method` is
533
- * which factor was delivered and `targetMethod` is used ONLY by the setup flow
534
- * (what to set `account.twoFactorMethod` to on success). Login challenges leave
535
- * `targetMethod` at 0. `codeHash = SHA-256(username || 0x00 || code)`; the
536
- * plaintext code is never stored.
537
- */
538
- @data
539
- class TwoFaChallenge {
540
- username: string = '';
541
- method: u8 = 0;
542
- codeHash: Uint8Array = new Uint8Array(0);
543
- exp: u64 = 0;
544
- attempts: u32 = 0;
545
- targetMethod: u8 = 0;
546
- sessionEpoch: u64 = 0;
547
- sessionVersion: u8 = 0;
548
- settingsRevision: u64 = 0;
549
- accountId: Uint8Array = new Uint8Array(0);
550
- }
551
-
552
- @data
553
- class DeletedAccountKey {
554
- host: string = '';
555
- incarnation: string = '';
556
- constructor(host: string = '', incarnation: string = '') {
557
- this.host = host;
558
- this.incarnation = incarnation;
559
- }
560
- }
561
-
562
- @data
563
- class DeletedAccountMarker {
564
- deleted: bool = true;
565
- }
566
-
567
- @database
568
- class AuthDb {
569
- @collection static accounts: Documents<Username, AuthAccount>;
570
- // Permanent opaque incarnation guards prevent a late replica/snapshot replay
571
- // of an old account row from enabling that deleted account again.
572
- @collection static deletedAccounts: Documents<DeletedAccountKey, DeletedAccountMarker>;
573
- @collection static emails: Documents<EmailKey, EmailOwner>; // email -> username (uniqueness index)
574
- @collection static challenges: Documents<ChallengeId, Challenge>;
575
- @collection static confirmTokens: Documents<TokenId, TokenRec>;
576
- @collection static resetTokens: Documents<TokenId, TokenRec>;
577
- // username -> its CURRENT outstanding confirm/reset token id, so minting a new
578
- // one can invalidate the previous: outstanding tokens stay bounded at one per
579
- // user per kind (O(users)), not one per request (unbounded storage-griefing).
580
- @collection static confirmTokenOf: Documents<Username, TokenId>;
581
- @collection static resetTokenOf: Documents<Username, TokenId>;
582
- // SECOND-FACTOR challenges live in their OWN collections, a namespace fully
583
- // disjoint from confirm/reset tokens (above). A reset/confirm token looked up
584
- // here finds nothing (wrong collection); a 2FA code/id looked up in the token
585
- // collections finds nothing. The separation is STRUCTURAL, not a purpose
586
- // string. `twoFaLogins` is keyed by a random per-login id; `twoFaSetup` is
587
- // keyed by username = one outstanding setup challenge per user.
588
- @collection static twoFaLogins: Documents<TwoFaId, TwoFaChallenge>;
589
- @collection static twoFaSetup: Documents<Username, TwoFaChallenge>;
590
- }
591
-
592
417
  @rest('auth')
593
418
  class Auth {
594
419
  /** POST /auth/register/start body: str(username) bytes(blinded)
@@ -692,6 +517,8 @@ class Auth {
692
517
  return Response.bytes(new DataWriter().writeU8(ST_EMAIL_TAKEN).toBytes());
693
518
  }
694
519
 
520
+ AuthMaintenance.index(h, a);
521
+ AuthService.__initializeRegistration(ToilUserId.fromBytes(a.toilUserId), username, email);
695
522
  a.registering = false;
696
523
  if (!AuthDb.accounts.compareExchangeSnapshot(accountKey, registering, a)) return fail();
697
524
  if (mustConfirm) {
@@ -1031,7 +858,10 @@ class Auth {
1031
858
  /** The account's STABLE ToilUserId, persisted at registration (so reset never
1032
859
  * changes it). An empty stored id is derived once, persisted, and indexed. */
1033
860
  private stableUserId(ctx: RouteContext, h: string, username: string, acct: AuthAccount, persist: bool = true): Uint8Array {
1034
- if (acct.toilUserId.length > 0) return acct.toilUserId;
861
+ if (acct.toilUserId.length > 0) {
862
+ if (persist && !acct.deleting) AuthMaintenance.index(h, acct);
863
+ return acct.toilUserId;
864
+ }
1035
865
  const uid = ToilUserId.derive(acct.publicKey, username, authDomain(ctx)).toBytes();
1036
866
  if (!persist || acct.deleting) return uid;
1037
867
  const key = new Username(h, username);
@@ -1041,12 +871,14 @@ class Auth {
1041
871
  throw new Error('Account identity temporarily unavailable');
1042
872
  if (observed.value.toilUserId.length != 0) {
1043
873
  acct.toilUserId = observed.value.toilUserId;
874
+ AuthMaintenance.index(h, acct);
1044
875
  return acct.toilUserId;
1045
876
  }
1046
877
  observed.value.toilUserId = uid;
1047
878
  if (!AuthDb.accounts.compareExchangeSnapshot(key, observed, observed.value))
1048
879
  throw new Error('Account identity changed; retry sign-in');
1049
880
  acct.toilUserId = uid;
881
+ AuthMaintenance.index(h, acct);
1050
882
  return uid;
1051
883
  }
1052
884
 
@@ -1085,23 +917,11 @@ class Auth {
1085
917
  }
1086
918
 
1087
919
  private wasDeleted(host: string, acct: AuthAccount): bool {
1088
- const marker = AuthDb.deletedAccounts.getCurrentSnapshot(new DeletedAccountKey(host, crypto.toHex(this.incarnation(acct))));
1089
- if (marker == null && Db.lastError() != DbError.None) throw new Error('Account deletion state temporarily unavailable');
1090
- if (marker != null) return true;
1091
- if (acct.accountId.length == 0 || acct.legacyFactors) {
1092
- // Older credentials predate an incarnation field. Their salt remains
1093
- // stable across resets, unlike the public key used in a legacy fallback.
1094
- const legacy = AuthDb.deletedAccounts.getCurrentSnapshot(new DeletedAccountKey(host, 'legacy:' + crypto.toHex(crypto.sha256(acct.salt))));
1095
- if (legacy == null && Db.lastError() != DbError.None) throw new Error('Account deletion state temporarily unavailable');
1096
- return legacy != null;
1097
- }
1098
- return false;
920
+ return AuthMaintenance.wasDeleted(host, acct);
1099
921
  }
1100
922
 
1101
923
  private incarnation(acct: AuthAccount): Uint8Array {
1102
- if (acct.accountId.length != 0) return acct.accountId;
1103
- // Legacy accounts have no incarnation. Preserve this identity across reset.
1104
- return crypto.sha256Text(crypto.toHex(acct.salt) + ':' + crypto.toHex(acct.publicKey));
924
+ return AuthMaintenance.incarnation(acct);
1105
925
  }
1106
926
 
1107
927
  private factorName(acct: AuthAccount): string {
@@ -1113,47 +933,8 @@ class Auth {
1113
933
  }
1114
934
 
1115
935
  private finishDeletion(ctx: RouteContext, key: Username, observed: DocumentSnapshot<AuthAccount>): bool {
1116
- const acct = observed.value;
1117
- if (!acct.deleting) return false;
1118
- const deletedKey = new DeletedAccountKey(key.host, crypto.toHex(this.incarnation(acct)));
1119
- if (!AuthDb.deletedAccounts.compareExchange(deletedKey, null, new DeletedAccountMarker()) && !this.wasDeleted(key.host, acct))
1120
- throw new Error('Account deletion state temporarily unavailable');
1121
- if (acct.accountId.length == 0 || acct.legacyFactors) {
1122
- const legacyKey = new DeletedAccountKey(key.host, 'legacy:' + crypto.toHex(crypto.sha256(acct.salt)));
1123
- if (!AuthDb.deletedAccounts.compareExchange(legacyKey, null, new DeletedAccountMarker())) {
1124
- const legacy = AuthDb.deletedAccounts.getCurrentSnapshot(legacyKey);
1125
- if (legacy == null) throw new Error('Legacy deletion state temporarily unavailable');
1126
- }
1127
- }
1128
- const emailKey = new EmailKey(key.host, acct.email);
1129
- const email = AuthDb.emails.getCurrentSnapshot(emailKey);
1130
- if (email == null && Db.lastError() != DbError.None) throw new Error('Email index temporarily unavailable');
1131
- if (email != null && email.value.username == acct.username &&
1132
- (email.value.accountId.length == 0 || ctEqual(email.value.accountId, this.incarnation(acct)))) {
1133
- AuthDb.emails.compareDeleteSnapshot(emailKey, email);
1134
- }
1135
- const secondary = this.secondaryKey(key.host, acct);
1136
- const confirm = AuthDb.confirmTokenOf.getDelete(secondary);
1137
- if (confirm == null && Db.lastError() != DbError.None) throw new Error('Confirmation token temporarily unavailable');
1138
- if (confirm != null) AuthDb.confirmTokens.delete(confirm);
1139
- const reset = AuthDb.resetTokenOf.getDelete(secondary);
1140
- if (reset == null && Db.lastError() != DbError.None) throw new Error('Reset token temporarily unavailable');
1141
- if (reset != null) AuthDb.resetTokens.delete(reset);
1142
- AuthDb.twoFaSetup.delete(secondary);
1143
- // Pre-incarnation heads use the plain username. New accounts never use
1144
- // these keys, so cleaning them cannot touch a later registration.
1145
- const legacy = new Username(key.host, acct.username);
1146
- const legacyConfirm = AuthDb.confirmTokenOf.getDelete(legacy);
1147
- if (legacyConfirm == null && Db.lastError() != DbError.None) throw new Error('Confirmation token temporarily unavailable');
1148
- if (legacyConfirm != null) AuthDb.confirmTokens.delete(legacyConfirm);
1149
- const legacyReset = AuthDb.resetTokenOf.getDelete(legacy);
1150
- if (legacyReset == null && Db.lastError() != DbError.None) throw new Error('Reset token temporarily unavailable');
1151
- if (legacyReset != null) AuthDb.resetTokens.delete(legacyReset);
1152
- AuthDb.twoFaSetup.delete(legacy);
1153
- // Security epochs intentionally remain so copied cookies and in-flight
1154
- // logins cannot become valid when the same identity signs up again.
1155
- AuthService.revokeUserSessions(__toilEncodeAuthUser(this.stableUserId(ctx, key.host, acct.username, acct), acct.username));
1156
- return AuthDb.accounts.compareDeleteSnapshot(key, observed);
936
+ return AuthMaintenance.finishDeletion(key, observed,
937
+ this.stableUserId(ctx, key.host, observed.value.username, observed.value, false));
1157
938
  }
1158
939
 
1159
940
  /** Delete the authenticated sign-in account, freeing username and email.