toiljs 0.0.127 → 0.0.128

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 (140) hide show
  1. package/CHANGELOG.md +22 -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 +54 -1
  26. package/build/compiler/security.d.ts +7 -0
  27. package/build/compiler/security.js +74 -0
  28. package/build/compiler/sri.js +10 -3
  29. package/build/compiler/toil-docs.generated.js +33 -27
  30. package/build/compiler/vite.js +2 -0
  31. package/build/devserver/config/env.d.ts +6 -0
  32. package/build/devserver/config/env.js +10 -2
  33. package/build/devserver/daemon/catalog.d.ts +1 -0
  34. package/build/devserver/daemon/catalog.js +10 -4
  35. package/build/devserver/daemon/host.d.ts +5 -1
  36. package/build/devserver/daemon/host.js +8 -4
  37. package/build/devserver/daemon/http.d.ts +14 -0
  38. package/build/devserver/daemon/http.js +90 -0
  39. package/build/devserver/daemon/index.d.ts +21 -1
  40. package/build/devserver/daemon/index.js +109 -21
  41. package/build/devserver/db/atomic.d.ts +8 -0
  42. package/build/devserver/db/atomic.js +133 -0
  43. package/build/devserver/db/catalog.d.ts +7 -0
  44. package/build/devserver/db/catalog.js +17 -0
  45. package/build/devserver/db/changes.d.ts +5 -0
  46. package/build/devserver/db/changes.js +49 -0
  47. package/build/devserver/db/database.d.ts +7 -0
  48. package/build/devserver/db/database.js +251 -41
  49. package/build/devserver/db/derives.d.ts +4 -5
  50. package/build/devserver/db/derives.js +7 -76
  51. package/build/devserver/db/document-scan.d.ts +2 -0
  52. package/build/devserver/db/document-scan.js +123 -0
  53. package/build/devserver/db/limits.d.ts +16 -0
  54. package/build/devserver/db/limits.js +92 -14
  55. package/build/devserver/db/types.d.ts +15 -0
  56. package/build/devserver/db/types.js +9 -0
  57. package/build/devserver/files/dev.d.ts +3 -0
  58. package/build/devserver/files/dev.js +29 -0
  59. package/build/devserver/files/disk.d.ts +17 -0
  60. package/build/devserver/files/disk.js +369 -0
  61. package/build/devserver/files/signatures.d.ts +16 -0
  62. package/build/devserver/files/signatures.js +151 -0
  63. package/build/devserver/http/proxy.js +11 -3
  64. package/build/devserver/http/runtime.js +36 -9
  65. package/build/devserver/images/index.d.ts +9 -0
  66. package/build/devserver/images/index.js +87 -0
  67. package/build/devserver/images/worker.d.mts +1 -0
  68. package/build/devserver/images/worker.mjs +24 -0
  69. package/build/devserver/index.d.ts +3 -1
  70. package/build/devserver/production.js +5 -3
  71. package/build/devserver/runtime/host.d.ts +4 -0
  72. package/build/devserver/runtime/host.js +6 -2
  73. package/build/devserver/runtime/module.d.ts +15 -0
  74. package/build/devserver/runtime/module.js +105 -7
  75. package/build/devserver/server.js +13 -1
  76. package/build/devserver/stream/host.d.ts +2 -0
  77. package/build/devserver/stream/host.js +2 -1
  78. package/build/devserver/stream/index.js +2 -0
  79. package/build/io/derive-metadata.d.ts +7 -0
  80. package/build/io/derive-metadata.js +44 -0
  81. package/build/io/index.d.ts +1 -0
  82. package/build/io/index.js +1 -0
  83. package/build/shared/index.d.ts +1 -0
  84. package/build/shared/index.js +1 -0
  85. package/build/shared/security.d.ts +5 -0
  86. package/build/shared/security.js +64 -0
  87. package/examples/basic/client/routes/rest.tsx +1 -1
  88. package/examples/basic/server/routes/Guestbook.ts +1 -1
  89. package/package.json +19 -7
  90. package/scripts/build-image-codec.mjs +79 -0
  91. package/scripts/gen-auth-vectors.mjs +132 -0
  92. package/scripts/gen-native-atomic-fixture.mjs +39 -0
  93. package/scripts/gen-native-blob-fixture.mjs +42 -0
  94. package/scripts/gen-native-image-fixture.mjs +65 -0
  95. package/scripts/gen-native-staging-fixture.mjs +41 -0
  96. package/scripts/gen-server-types.mjs +82 -0
  97. package/server/auth/AuthController.ts +15 -234
  98. package/server/auth/AuthMaintenance.ts +177 -0
  99. package/server/auth/AuthStore.ts +198 -0
  100. package/server/auth/SessionEpochs.ts +38 -9
  101. package/server/globals/auth.ts +56 -0
  102. package/server/globals.d.ts +37 -0
  103. package/server/runtime/envelope.ts +2 -1
  104. package/server/runtime/exports/index.ts +2 -1
  105. package/server/runtime/files/blobs.ts +341 -0
  106. package/server/runtime/files/images.ts +36 -0
  107. package/server/runtime/http/percent.ts +5 -4
  108. package/server/runtime/index.ts +5 -0
  109. package/server/runtime/response.ts +20 -0
  110. package/server/runtime/rest/RouteContext.ts +5 -4
  111. package/std/server/abort/abort.d.ts +25 -0
  112. package/std/server/env/Server.d.ts +47 -0
  113. package/std/server/envelope.d.ts +38 -0
  114. package/std/server/exports/index.d.ts +20 -0
  115. package/std/server/exports/render.d.ts +15 -0
  116. package/std/server/files/blobs.d.ts +50 -0
  117. package/std/server/files/images.d.ts +36 -0
  118. package/std/server/handlers/ToilHandler.d.ts +29 -0
  119. package/std/server/http/base64.d.ts +21 -0
  120. package/std/server/http/cookie.d.ts +127 -0
  121. package/std/server/http/cookies.d.ts +56 -0
  122. package/std/server/http/date.d.ts +17 -0
  123. package/std/server/http/percent.d.ts +19 -0
  124. package/std/server/http/securecookies.d.ts +55 -0
  125. package/std/server/index.d.ts +34 -0
  126. package/std/server/lang/Potential.d.ts +6 -0
  127. package/std/server/memory.d.ts +42 -0
  128. package/std/server/request.d.ts +47 -0
  129. package/std/server/response.d.ts +90 -0
  130. package/std/server/rest/Rest.d.ts +23 -0
  131. package/std/server/rest/RestHandler.d.ts +14 -0
  132. package/std/server/rest/RouteContext.d.ts +33 -0
  133. package/std/server/rest/match.d.ts +14 -0
  134. package/std/server/rpc/Rpc.d.ts +37 -0
  135. package/std/server/ssr/Ssr.d.ts +27 -0
  136. package/std/server/ssr/encode.d.ts +26 -0
  137. package/std/server/ssr/escape.d.ts +22 -0
  138. package/std/server/ssr/slots.d.ts +91 -0
  139. package/std/server/time.d.ts +24 -0
  140. package/tsconfig.json +11 -2
@@ -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.
@@ -0,0 +1,177 @@
1
+ import { AuthDb, AuthAccount, Username, EmailKey, DeletedAccountKey, DeletedAccountMarker,
2
+ AuthUserKey, AuthUserAccount, AuthUserAccounts } from './AuthStore';
3
+ import { SessionEpochs } from './SessionEpochs';
4
+
5
+ function sameBytes(a: Uint8Array, b: Uint8Array): bool {
6
+ if (a.length != b.length) return false;
7
+ let different: i32 = 0;
8
+ for (let i = 0; i < a.length; i++) different |= a[i] ^ b[i];
9
+ return different == 0;
10
+ }
11
+
12
+ /** Shared request/daemon account lifecycle. Storage types keep their original
13
+ * names and field order when moved out of the REST-only entry. */
14
+ export class AuthMaintenance {
15
+ static incarnation(acct: AuthAccount): Uint8Array {
16
+ return acct.accountId.length != 0 ? acct.accountId :
17
+ crypto.sha256Text(crypto.toHex(acct.salt) + ':' + crypto.toHex(acct.publicKey));
18
+ }
19
+ static wasDeleted(host: string, acct: AuthAccount): bool {
20
+ const marker = AuthDb.deletedAccounts.getCurrentSnapshot(new DeletedAccountKey(host, crypto.toHex(AuthMaintenance.incarnation(acct))));
21
+ if (marker == null && Db.lastError() != DbError.None) throw new Error('Account deletion state temporarily unavailable');
22
+ if (marker != null) return true;
23
+ if (acct.accountId.length == 0 || acct.legacyFactors) {
24
+ const legacy = AuthDb.deletedAccounts.getCurrentSnapshot(new DeletedAccountKey(host, 'legacy:' + crypto.toHex(crypto.sha256(acct.salt))));
25
+ if (legacy == null && Db.lastError() != DbError.None) throw new Error('Account deletion state temporarily unavailable');
26
+ return legacy != null;
27
+ }
28
+ return false;
29
+ }
30
+ static index(host: string, acct: AuthAccount): void {
31
+ if (acct.toilUserId.length != 32) throw new Error('Invalid account identity');
32
+ const key = new AuthUserKey(crypto.toHex(acct.toilUserId));
33
+ const incarnation = AuthMaintenance.incarnation(acct);
34
+ for (let attempt: i32 = 0; attempt < 4; attempt++) {
35
+ const observed = AuthDb.userAccounts.getCurrentSnapshot(key);
36
+ if (observed == null && Db.lastError() != DbError.None) throw new Error('Account index unavailable');
37
+ const next = observed == null ? new AuthUserAccounts() : observed.value;
38
+ let found = false;
39
+ for (let i = 0; i < next.accounts.length; i++) {
40
+ const owner = next.accounts[i];
41
+ if (owner.host != host || owner.username != acct.username) continue;
42
+ if (sameBytes(owner.accountId, incarnation)) return;
43
+ // Replacing an index pointer needs proof that its incarnation
44
+ // no longer owns the authoritative account row.
45
+ const current = AuthDb.accounts.getCurrentSnapshot(new Username(host, acct.username));
46
+ if (current == null && Db.lastError() != DbError.None) throw new Error('Account owner unavailable');
47
+ if (current == null || !sameBytes(AuthMaintenance.incarnation(current.value), incarnation))
48
+ throw new Error('Account index changed; retry');
49
+ next.accounts[i] = new AuthUserAccount(host, acct.username, incarnation);
50
+ found = true;
51
+ }
52
+ if (!found) {
53
+ if (next.accounts.length >= 16) throw new Error('Account identity has too many realms');
54
+ next.accounts.push(new AuthUserAccount(host, acct.username, incarnation));
55
+ }
56
+ if (AuthDb.userAccounts.compareExchangeSnapshot(key, observed, next)) return;
57
+ }
58
+ throw new Error('Account index conflicted; retry');
59
+ }
60
+ static deleteUser(id: ToilUserId, realm: string): bool {
61
+ const uid = id.toBytes();
62
+ const index = AuthDb.userAccounts.getCurrentSnapshot(new AuthUserKey(crypto.toHex(uid)));
63
+ if (index == null) {
64
+ if (Db.lastError() != DbError.None) throw new Error('Account index unavailable');
65
+ return false;
66
+ }
67
+ let selected: AuthUserAccount | null = null;
68
+ for (let i = 0; i < index.value.accounts.length; i++) {
69
+ const owner = index.value.accounts[i];
70
+ if (realm.length != 0 && owner.host != realm) continue;
71
+ if (selected != null) throw new Error('Ambiguous account realm; pass its normalized realm');
72
+ selected = owner;
73
+ }
74
+ if (selected == null) return false;
75
+ const key = new Username(selected.host, selected.username);
76
+ let observed = AuthDb.accounts.getCurrentSnapshot(key);
77
+ if (observed == null) {
78
+ if (Db.lastError() != DbError.None) throw new Error('Account unavailable');
79
+ AuthMaintenance.unindex(uid, selected.host, selected.username, selected.accountId);
80
+ return false;
81
+ }
82
+ if (!sameBytes(observed.value.toilUserId, uid) ||
83
+ !sameBytes(AuthMaintenance.incarnation(observed.value), selected.accountId)) {
84
+ AuthMaintenance.unindex(uid, selected.host, selected.username, selected.accountId);
85
+ return false;
86
+ }
87
+ if (!observed.value.deleting) {
88
+ observed.value.deleting = true;
89
+ if (!AuthDb.accounts.compareExchangeSnapshot(key, observed, observed.value)) throw new Error('Account changed; retry deletion');
90
+ observed = new DocumentSnapshot<AuthAccount>(observed.value, observed.value.encode());
91
+ }
92
+ if (!AuthMaintenance.finishDeletion(key, observed, uid)) throw new Error('Account changed; retry deletion');
93
+ return true;
94
+ }
95
+ private static unindex(uid: Uint8Array, host: string, username: string, incarnation: Uint8Array): void {
96
+ const key = new AuthUserKey(crypto.toHex(uid));
97
+ for (let attempt: i32 = 0; attempt < 4; attempt++) {
98
+ const observed = AuthDb.userAccounts.getCurrentSnapshot(key);
99
+ if (observed == null) {
100
+ if (Db.lastError() != DbError.None) throw new Error('Account index unavailable');
101
+ return;
102
+ }
103
+ const next = new AuthUserAccounts();
104
+ for (let i = 0; i < observed.value.accounts.length; i++) {
105
+ const owner = observed.value.accounts[i];
106
+ if (owner.host != host || owner.username != username || !sameBytes(owner.accountId, incarnation)) next.accounts.push(owner);
107
+ }
108
+ if (next.accounts.length == observed.value.accounts.length) return;
109
+ if (next.accounts.length == 0 ? AuthDb.userAccounts.compareDeleteSnapshot(key, observed) :
110
+ AuthDb.userAccounts.compareExchangeSnapshot(key, observed, next)) return;
111
+ }
112
+ throw new Error('Account index cleanup conflicted; retry');
113
+ }
114
+ static indexUsers(limit: i32, cursor: Uint8Array | null): Uint8Array | null {
115
+ if (limit < 1 || limit > 8) throw new Error('indexUsers limit must be 1..8');
116
+ const page = AuthDb.accounts.scan(limit, cursor);
117
+ for (let i = 0; i < page.entries.length; i++) {
118
+ const entry = page.entries[i];
119
+ const account = entry.value;
120
+ if (account.deleting || account.registering || AuthMaintenance.wasDeleted(entry.key.host, account)) continue;
121
+ if (account.toilUserId.length == 0) {
122
+ const domain = Environment.getSecure('TOIL_AUTH_DOMAIN');
123
+ if (domain == null || domain.length == 0) throw new Error('Legacy identity backfill requires the original TOIL_AUTH_DOMAIN');
124
+ account.toilUserId = ToilUserId.derive(account.publicKey, account.username, domain).toBytes();
125
+ if (!AuthDb.accounts.compareExchangeSnapshot(entry.key, entry.snapshot, account)) throw new Error('Account changed during backfill; retry this page');
126
+ }
127
+ AuthMaintenance.index(entry.key.host, account);
128
+ }
129
+ return page.cursor;
130
+ }
131
+ static finishDeletion(key: Username, observed: DocumentSnapshot<AuthAccount>, uid: Uint8Array): bool {
132
+ const acct = observed.value;
133
+ if (!acct.deleting) return false;
134
+ const deletedKey = new DeletedAccountKey(key.host, crypto.toHex(AuthMaintenance.incarnation(acct)));
135
+ if (!AuthDb.deletedAccounts.compareExchange(deletedKey, null, new DeletedAccountMarker()) && !AuthMaintenance.wasDeleted(key.host, acct))
136
+ throw new Error('Account deletion state temporarily unavailable');
137
+ if (acct.accountId.length == 0 || acct.legacyFactors) {
138
+ const legacyKey = new DeletedAccountKey(key.host, 'legacy:' + crypto.toHex(crypto.sha256(acct.salt)));
139
+ if (!AuthDb.deletedAccounts.compareExchange(legacyKey, null, new DeletedAccountMarker())) {
140
+ const legacy = AuthDb.deletedAccounts.getCurrentSnapshot(legacyKey);
141
+ if (legacy == null) throw new Error('Legacy deletion state temporarily unavailable');
142
+ }
143
+ }
144
+ const emailKey = new EmailKey(key.host, acct.email);
145
+ const email = AuthDb.emails.getCurrentSnapshot(emailKey);
146
+ if (email == null && Db.lastError() != DbError.None) throw new Error('Email index temporarily unavailable');
147
+ if (email != null && email.value.username == acct.username &&
148
+ (email.value.accountId.length == 0 || sameBytes(email.value.accountId, AuthMaintenance.incarnation(acct)))) {
149
+ AuthDb.emails.compareDeleteSnapshot(emailKey, email);
150
+ }
151
+ const secondary = new Username(key.host, acct.username + '\x00' + crypto.toHex(AuthMaintenance.incarnation(acct)));
152
+ const confirm = AuthDb.confirmTokenOf.getDelete(secondary);
153
+ if (confirm == null && Db.lastError() != DbError.None) throw new Error('Confirmation token temporarily unavailable');
154
+ if (confirm != null) AuthDb.confirmTokens.delete(confirm);
155
+ const reset = AuthDb.resetTokenOf.getDelete(secondary);
156
+ if (reset == null && Db.lastError() != DbError.None) throw new Error('Reset token temporarily unavailable');
157
+ if (reset != null) AuthDb.resetTokens.delete(reset);
158
+ AuthDb.twoFaSetup.delete(secondary);
159
+ // Pre-incarnation heads use the plain username. New accounts never use
160
+ // these keys, so cleaning them cannot touch a later registration.
161
+ const legacy = new Username(key.host, acct.username);
162
+ const legacyConfirm = AuthDb.confirmTokenOf.getDelete(legacy);
163
+ if (legacyConfirm == null && Db.lastError() != DbError.None) throw new Error('Confirmation token temporarily unavailable');
164
+ if (legacyConfirm != null) AuthDb.confirmTokens.delete(legacyConfirm);
165
+ const legacyReset = AuthDb.resetTokenOf.getDelete(legacy);
166
+ if (legacyReset == null && Db.lastError() != DbError.None) throw new Error('Reset token temporarily unavailable');
167
+ if (legacyReset != null) AuthDb.resetTokens.delete(legacyReset);
168
+ AuthDb.twoFaSetup.delete(legacy);
169
+ // Security epochs intentionally remain so copied cookies and in-flight
170
+ // logins cannot become valid when the same identity signs up again.
171
+ SessionEpochs.revokeId(crypto.toHex(uid));
172
+ if (!AuthDb.accounts.compareDeleteSnapshot(key, observed)) return false;
173
+ AuthMaintenance.unindex(uid, key.host, acct.username, AuthMaintenance.incarnation(acct));
174
+ return true;
175
+ }
176
+ }
177
+ AuthService.__installMaintenance(AuthMaintenance.deleteUser, AuthMaintenance.indexUsers);