toiljs 0.0.131 → 0.0.134

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 (53) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/build/backend/security.js +4 -2
  3. package/build/cli/index.js +9 -9
  4. package/build/client/auth.d.ts +14 -0
  5. package/build/client/auth.js +31 -4
  6. package/build/client/components/GoogleSignIn.d.ts +8 -0
  7. package/build/client/components/GoogleSignIn.js +57 -0
  8. package/build/client/index.d.ts +3 -1
  9. package/build/client/index.js +2 -1
  10. package/build/compiler/config.d.ts +3 -1
  11. package/build/compiler/config.js +3 -0
  12. package/build/compiler/security.d.ts +4 -3
  13. package/build/compiler/security.js +8 -7
  14. package/build/compiler/sri.js +2 -2
  15. package/build/compiler/toil-docs.generated.js +3 -1
  16. package/build/compiler/vite.js +1 -1
  17. package/build/devserver/http/runtime.d.ts +1 -1
  18. package/build/devserver/http/runtime.js +5 -5
  19. package/build/devserver/production.js +3 -3
  20. package/build/devserver/runtime/base64.d.ts +2 -0
  21. package/build/devserver/runtime/base64.js +39 -0
  22. package/build/devserver/runtime/crypto.d.ts +1 -1
  23. package/build/devserver/runtime/crypto.js +24 -0
  24. package/build/devserver/runtime/google.d.ts +9 -0
  25. package/build/devserver/runtime/google.js +157 -0
  26. package/build/devserver/runtime/host.js +6 -0
  27. package/build/devserver/runtime/module.d.ts +2 -0
  28. package/build/devserver/runtime/module.js +19 -0
  29. package/build/shared/index.d.ts +2 -1
  30. package/build/shared/index.js +1 -1
  31. package/build/shared/security.d.ts +4 -2
  32. package/build/shared/security.js +6 -2
  33. package/examples/basic/client/routes/google-login.tsx +132 -0
  34. package/package.json +19 -19
  35. package/server/auth/AuthController.ts +201 -61
  36. package/server/auth/AuthMaintenance.ts +1 -1
  37. package/server/auth/AuthRealm.ts +22 -0
  38. package/server/auth/AuthStateDb.ts +14 -0
  39. package/server/auth/AuthStore.ts +4 -0
  40. package/server/auth/Authenticator.ts +93 -0
  41. package/server/auth/FactorSettings.ts +9 -8
  42. package/server/auth/GoogleIdentity.ts +63 -0
  43. package/server/auth/SessionEpochs.ts +54 -12
  44. package/server/globals/auth.ts +51 -20
  45. package/server/globals.d.ts +6 -0
  46. package/server/runtime/envelope.ts +9 -7
  47. package/server/runtime/http/base64.ts +18 -98
  48. package/server/runtime/http/percent.ts +4 -0
  49. package/server/runtime/http/securecookies.ts +1 -1
  50. package/server/runtime/request.ts +3 -0
  51. package/std/server/http/base64.d.ts +2 -18
  52. package/std/server/http/securecookies.d.ts +1 -1
  53. package/std/server/request.d.ts +3 -0
@@ -1,8 +1,11 @@
1
+ import { AuthRealm } from 'toiljs/server/auth/AuthRealm';
1
2
  import { Username, EmailKey, EmailOwner, TokenId, TokenRec, ChallengeId, AuthAccount, Challenge, TwoFaId, TwoFaChallenge, DeletedAccountKey, DeletedAccountMarker, AuthDb } from './AuthStore';
2
3
  import { AuthMaintenance } from './AuthMaintenance';
4
+ import { GoogleIdentity } from './GoogleIdentity';
5
+ import { Authenticator } from './Authenticator';
3
6
  import { FactorRepository } from './FactorSettings';
4
7
  import { SessionEpochs } from './SessionEpochs';
5
- import { Response, RouteContext } from 'toiljs/server/runtime';
8
+ import { Response, RouteContext, base64UrlEncode } from 'toiljs/server/runtime';
6
9
  import { DataReader, DataWriter } from 'data';
7
10
 
8
11
  /**
@@ -84,7 +87,7 @@ const ST_TWOFA_REQUIRED: u8 = 3;
84
87
  // the challenge lifecycle and the login wiring do NOT change.
85
88
  const TWOFA_NONE: u8 = 0;
86
89
  const TWOFA_EMAIL: u8 = 1;
87
- // Future (reserved, not yet implemented): TWOFA_TOTP: u8 = 2; TWOFA_SMS: u8 = 3;
90
+ const TWOFA_TOTP: u8 = 2;
88
91
 
89
92
  // 2FA challenge tuning. The code is single-use, TTL'd, and attempt-limited (all
90
93
  // enforced against the stored challenge, independent of the per-IP @ratelimit).
@@ -107,6 +110,7 @@ const TWOFA_DIGITS: i32 = 6; // digits in an emailed numeric code
107
110
  // collide with the `@ratelimit` decorator's monotonic-from-0 routeIds.
108
111
  const TWOFA_VERIFY_RL_ROUTE: i32 = 2147483001;
109
112
  const TWOFA_SETUP_RL_ROUTE: i32 = 2147483002;
113
+ const TOTP_ACCOUNT_RL_ROUTE: i32 = 2147483003;
110
114
  // The host strategy tag for SlidingWindow (matches `RateLimit.SlidingWindow` and
111
115
  // what the @ratelimit decorator lowers to). Used as a raw int because `RateLimit`
112
116
  // is a type-only ambient enum with no runtime backing in a handler body.
@@ -157,19 +161,7 @@ function authDomain(ctx: RouteContext): string {
157
161
  */
158
162
  function realm(ctx: RouteContext): string {
159
163
  const raw = ctx.request.header('host');
160
- if (raw == null) return '';
161
- let h = raw.toLowerCase();
162
- if (h.startsWith('[')) {
163
- // IPv6 literal `[addr]`(:port): keep through the closing bracket, drop the
164
- // port. Bracket-aware so `[::1]` is not sliced to `[:` (which would collapse
165
- // distinct IPv6 tenants). Mirrors the edge strip_port + the session tag.
166
- const close = h.indexOf(']');
167
- if (close >= 0) h = h.slice(0, close + 1);
168
- } else {
169
- const colon = h.lastIndexOf(':');
170
- if (colon > 0) h = h.slice(0, colon); // drop :port
171
- }
172
- return h;
164
+ return raw == null ? '' : AuthRealm.normalize(raw);
173
165
  }
174
166
 
175
167
  /** A lenient truthy read of a plain env var, ALIGNED with the edge's HostConfig
@@ -382,7 +374,7 @@ function ctEqual(a: Uint8Array, b: Uint8Array): bool {
382
374
  /** Whether `m` is a 2FA method this build understands (TWOFA_NONE or a supported
383
375
  * method). ADD A METHOD: also accept its enum value here. */
384
376
  function isKnownTwoFaMethod(m: u8): bool {
385
- return m == TWOFA_NONE || m == TWOFA_EMAIL;
377
+ return m == TWOFA_NONE || m == TWOFA_EMAIL || m == TWOFA_TOTP;
386
378
  // >>> e.g. `|| m == TWOFA_TOTP || m == TWOFA_SMS` <<<
387
379
  }
388
380
 
@@ -416,6 +408,96 @@ function isValidEmail(email: string): bool {
416
408
 
417
409
  @rest('auth')
418
410
  class Auth {
411
+ /** GIS initialization: public client id + nonce, with an HttpOnly browser binding. */
412
+ @ratelimit(RateLimit.SlidingWindow, 10, 60)
413
+ @post('/google/start')
414
+ public googleStart(ctx: RouteContext): Response {
415
+ const id = GoogleIdentity.clientId();
416
+ if (id.length == 0) return fail();
417
+ const nonce = crypto.toHex(randomBytes(32));
418
+ const response = Response.bytes(new DataWriter().writeString(id).writeString(nonce).toBytes());
419
+ response.setCookie(GoogleIdentity.start(ctx, realm(ctx), nonce));
420
+ response.setHeader('cache-control', 'no-store');
421
+ return response;
422
+ }
423
+
424
+ /** Verify signature/claims before any account I/O; never link accounts by email. */
425
+ @ratelimit(RateLimit.SlidingWindow, 10, 60)
426
+ @post('/google/login')
427
+ public googleLogin(ctx: RouteContext): Response {
428
+ if (ctx.request.body.length > 16388) return fail();
429
+ const r = new DataReader(ctx.request.body);
430
+ const token = r.readBytes();
431
+ if (!r.ok) return fail();
432
+ const h = realm(ctx);
433
+ const claims = GoogleIdentity.verify(ctx, h, token);
434
+ if (claims == null || !isValidEmail(claims.email)) return fail();
435
+ const username = claims.sub.length <= 55 ? 'google_s_' + claims.sub :
436
+ 'google_h_' + base64UrlEncode(crypto.sha256Text(claims.sub));
437
+ const key = new Username(h, username);
438
+ let observed = AuthDb.accounts.getCurrentSnapshot(key);
439
+ if (observed == null && Db.lastError() != DbError.None) return fail();
440
+ let acct: AuthAccount;
441
+ const fresh = observed == null;
442
+ if (observed == null) {
443
+ acct = new AuthAccount();
444
+ acct.username = username; acct.accountId = randomBytes(32); acct.registering = true;
445
+ acct.email = claims.email; acct.emailConfirmed = claims.emailAuthoritative; acct.googleSubject = claims.sub;
446
+ acct.toilUserId = ToilUserId.derive(crypto.sha256Text('google:' + claims.sub), username, authDomain(ctx)).toBytes();
447
+ if (!AuthDb.accounts.compareExchange(key, null, acct)) return fail();
448
+ observed = new DocumentSnapshot<AuthAccount>(acct, acct.encode());
449
+ } else acct = observed.value;
450
+ if (acct.deleting || (!fresh && this.wasDeleted(h, acct)) || acct.googleSubject != claims.sub) return fail();
451
+ const finishingRegistration = acct.registering;
452
+ if (acct.registering) {
453
+ if (!this.reserveEmail(new EmailKey(h, acct.email), acct)) {
454
+ AuthDb.accounts.compareDeleteSnapshot(key, observed);
455
+ return fail();
456
+ }
457
+ AuthMaintenance.index(h, acct);
458
+ AuthService.__initializeRegistration(ToilUserId.fromBytes(acct.toilUserId), username, acct.email);
459
+ acct.registering = false;
460
+ }
461
+ // Bounded replay protection: one account CAS, no nonce/token collection or per-login rows.
462
+ if (claims.issuedAt < acct.googleIssuedAt) return fail();
463
+ if (claims.issuedAt > acct.googleIssuedAt) acct.googleNonces = new Array<string>();
464
+ if (acct.googleNonces.includes(claims.nonce) || acct.googleNonces.length >= 16) return fail();
465
+ acct.googleIssuedAt = claims.issuedAt; acct.googleNonces.push(claims.nonce);
466
+ if (claims.emailAuthoritative && claims.email == acct.email) acct.emailConfirmed = true;
467
+ if (!AuthDb.accounts.compareExchangeSnapshot(key, observed, acct)) return fail();
468
+ if (requireConfirmation() && !acct.emailConfirmed) {
469
+ if (finishingRegistration) this.issueConfirmation(h, ctx, username, acct.email, acct);
470
+ const response = Response.bytes(new DataWriter().writeU8(ST_UNCONFIRMED).toBytes());
471
+ response.setCookie(GoogleIdentity.cookie(ctx, '', 0));
472
+ response.setHeader('cache-control', 'no-store');
473
+ return response;
474
+ }
475
+ const userData = __toilEncodeAuthUser(acct.toilUserId, username);
476
+ const state = SessionEpochs.read(SessionEpochs.key(userData));
477
+ const epoch = state.revision;
478
+ const settings = FactorRepository.read(h, this.factorName(acct), acct.twoFactorMethod, state);
479
+ const w = new DataWriter();
480
+ if (settings.method != TWOFA_NONE) {
481
+ const raw = randomBytes(16);
482
+ const ch = new TwoFaChallenge();
483
+ ch.username = username; ch.accountId = acct.accountId; ch.method = settings.method;
484
+ ch.settingsRevision = settings.revision; ch.encryptedSecret = settings.encryptedSecret;
485
+ ch.exp = nowSecs() + TWOFA_TTL_SECS; ch.sessionVersion = 3; ch.sessionEpoch = epoch;
486
+ ch.codeHash = settings.method == TWOFA_TOTP ? new Uint8Array(1) :
487
+ this.twoFaDeliver(h, settings.method, username, acct.email, 'Your login code', 'sign in');
488
+ if (ch.codeHash.length == 0 || !AuthDb.twoFaLogins.create(new TwoFaId(h, raw), ch)) return fail();
489
+ w.writeU8(ST_TWOFA_REQUIRED).writeBytes(raw);
490
+ } else w.writeU8(ST_OK).writeBytes(userData);
491
+ const response = Response.bytes(w.toBytes());
492
+ if (settings.method == TWOFA_NONE) {
493
+ response.setCookie(AuthService.mintSession(userData, AuthService.DEFAULT_SESSION_TTL_SECS, epoch));
494
+ response.setCookie(AuthService.userCookie(userData));
495
+ }
496
+ response.setCookie(GoogleIdentity.cookie(ctx, '', 0));
497
+ response.setHeader('cache-control', 'no-store');
498
+ return response;
499
+ }
500
+
419
501
  /** POST /auth/register/start body: str(username) bytes(blinded)
420
502
  * resp: u8(status=0) u32(mem) u32(iters) u32(par) bytes(salt) bytes(evaluated)
421
503
  * No taken-oracle: always succeeds; register/finish rejects a duplicate.
@@ -456,7 +538,7 @@ class Auth {
456
538
  const proof = r.readBytes();
457
539
  if (!r.ok) return fail();
458
540
  if (pk.length != AuthService.PUBLIC_KEY_LEN) return fail();
459
- if (username.length == 0 || username.length > 64) return fail();
541
+ if (username.length == 0 || username.length > 64 || username.startsWith('google_')) return fail();
460
542
  if (!isValidEmail(email)) return fail(); // format + length; a bypassing client stores nothing garbage
461
543
 
462
544
  // Proof-of-possession FIRST (before any existence check): the client
@@ -610,7 +692,7 @@ class Auth {
610
692
  c.exp = exp;
611
693
  const account = known;
612
694
  c.sessionEpoch = SessionEpochs.current(__toilEncodeAuthUser(this.stableUserId(ctx, h, username, account), username));
613
- c.sessionVersion = 2;
695
+ c.sessionVersion = 3;
614
696
  c.accountId = this.incarnation(account);
615
697
  AuthDb.challenges.create(new ChallengeId(h, cid), c);
616
698
  }
@@ -646,7 +728,7 @@ class Auth {
646
728
  // The challenge is realm-keyed, so one minted on another domain misses.
647
729
  const ch = AuthDb.challenges.getDelete(new ChallengeId(h, cid));
648
730
  if (ch == null) return fail();
649
- if (ch.sessionVersion != 2) return fail();
731
+ if (ch.sessionVersion != 3) return fail();
650
732
  if (nowSecs() >= ch.exp) return fail();
651
733
 
652
734
  // 2. Rebuild the message from OUR stored values + the client's ct (and
@@ -694,10 +776,12 @@ class Auth {
694
776
  // never resetTokens/confirmTokens). This runs AFTER the signature
695
777
  // verify above, so it is not an oracle, and the login `Challenge` was
696
778
  // already consumed (getDelete) at the top of this handler.
697
- const factorMethod = FactorRepository.read(h, this.factorName(acct), acct.twoFactorMethod).method;
779
+ const loginSettings = FactorRepository.read(h, this.factorName(acct), acct.twoFactorMethod,
780
+ SessionEpochs.read(crypto.toHex(this.stableUserId(ctx, h, ch.username, acct, false))));
781
+ const factorMethod = loginSettings.method;
698
782
  if (factorMethod != TWOFA_NONE) {
699
783
  const raw = randomBytes(16); // the twoFaId the client echoes to /2fa/verify
700
- const codeHash = this.twoFaDeliver(
784
+ const codeHash = factorMethod == TWOFA_TOTP ? new Uint8Array(1) : this.twoFaDeliver(
701
785
  h,
702
786
  factorMethod,
703
787
  ch.username,
@@ -710,11 +794,13 @@ class Auth {
710
794
  c2.username = ch.username;
711
795
  c2.accountId = ch.accountId;
712
796
  c2.method = factorMethod;
797
+ c2.settingsRevision = loginSettings.revision;
798
+ c2.encryptedSecret = loginSettings.encryptedSecret;
713
799
  c2.codeHash = codeHash;
714
800
  c2.exp = nowSecs() + TWOFA_TTL_SECS;
715
801
  c2.attempts = 0;
716
802
  c2.sessionEpoch = ch.sessionEpoch;
717
- c2.sessionVersion = 2;
803
+ c2.sessionVersion = 3;
718
804
  c2.targetMethod = TWOFA_NONE; // a LOGIN challenge changes no method on success
719
805
  AuthDb.twoFaLogins.create(new TwoFaId(h, raw), c2);
720
806
 
@@ -755,7 +841,7 @@ class Auth {
755
841
  const h = realm(ctx);
756
842
  const owner = AuthDb.emails.get(new EmailKey(h, email));
757
843
  const resetAccount: AuthAccount | null = owner == null ? null : this.account(new Username(h, owner.username));
758
- if (owner != null && resetAccount != null && resetAccount.email == email) {
844
+ if (owner != null && resetAccount != null && resetAccount.email == email && resetAccount.googleSubject.length == 0) {
759
845
  // Invalidate this user's previous reset token (bound to one outstanding).
760
846
  const prev = AuthDb.resetTokenOf.getDelete(this.secondaryKey(h, resetAccount));
761
847
  if (prev != null) AuthDb.resetTokens.delete(prev);
@@ -925,6 +1011,7 @@ class Auth {
925
1011
  }
926
1012
 
927
1013
  private factorName(acct: AuthAccount): string {
1014
+ if (acct.googleSubject.length != 0) return 'google:' + base64UrlEncode(acct.accountId);
928
1015
  return acct.accountId.length == 0 || acct.legacyFactors ? acct.username : acct.username + '\x00' + crypto.toHex(acct.accountId);
929
1016
  }
930
1017
 
@@ -1008,12 +1095,26 @@ class Auth {
1008
1095
  @ratelimit(RateLimit.SlidingWindow, 5, 60)
1009
1096
  @post('/2fa/verify')
1010
1097
  public twoFaVerify(ctx: RouteContext): Response {
1098
+ if (ctx.request.body.length > 128) return fail();
1011
1099
  const r = new DataReader(ctx.request.body);
1012
1100
  const id = r.readBytes();
1013
1101
  const code = r.readString();
1014
- if (!r.ok || id.length == 0) return fail();
1102
+ if (!r.ok || id.length != 16) return fail();
1015
1103
  const h = realm(ctx);
1016
1104
 
1105
+ const key = new TwoFaId(h, id);
1106
+ // PEEK (not consume): a wrong guess must NOT burn the challenge (a typo
1107
+ // would otherwise lock the user out) until the attempt cap is reached.
1108
+ const observed = AuthDb.twoFaLogins.getCurrentSnapshot(key);
1109
+ if (observed == null) return fail();
1110
+ const ch = observed.value;
1111
+ if (ch.sessionVersion != 3) return fail(); // reject pre-upgrade pending logins
1112
+ if (nowSecs() >= ch.exp || ch.attempts >= TWOFA_MAX_ATTEMPTS) {
1113
+ AuthDb.twoFaLogins.compareDeleteSnapshot(key, observed); // never delete a replacement
1114
+ return fail();
1115
+ }
1116
+ // Only extant, unexpired challenges allocate a keyed limiter entry.
1117
+ // Random identifiers must not populate persistent limiter state.
1017
1118
  // RACE-FREE attempt cap: count this guess against a host-side EXACT
1018
1119
  // limiter keyed on THIS challenge (the twoFaId), not the peer IP. Unlike
1019
1120
  // the `ch.attempts` get+patch below, this is atomic across all workers,
@@ -1030,31 +1131,33 @@ class Auth {
1030
1131
  );
1031
1132
  if (rl != null) return rl;
1032
1133
 
1033
- const key = new TwoFaId(h, id);
1034
- // PEEK (not consume): a wrong guess must NOT burn the challenge (a typo
1035
- // would otherwise lock the user out) until the attempt cap is reached.
1036
- const ch = AuthDb.twoFaLogins.get(key);
1037
- if (ch == null) return fail();
1038
- if (ch.sessionVersion != 2) return fail(); // reject pre-upgrade pending logins
1039
- if (nowSecs() >= ch.exp || ch.attempts >= TWOFA_MAX_ATTEMPTS) {
1040
- AuthDb.twoFaLogins.delete(key); // burn an expired / exhausted challenge
1041
- return fail();
1134
+ if (ch.method == TWOFA_TOTP) {
1135
+ // Bound guesses across every pending login, even when source IPs differ.
1136
+ const accountLimit = RateLimitService.guardKeyed(TOTP_ACCOUNT_RL_ROUTE, TWOFA_RL_STRATEGY,
1137
+ 5, 60, h + '\x00' + base64UrlEncode(ch.accountId));
1138
+ if (accountLimit != null) return accountLimit;
1042
1139
  }
1043
- if (!this.twoFaVerifyCode(h, ch.username, code, ch)) {
1140
+ const step = ch.method == TWOFA_TOTP ? Authenticator.match(this.totpBinding(h, ch.accountId), ch.encryptedSecret, code) : 0;
1141
+ if (ch.method == TWOFA_TOTP ? step == 0 : !this.twoFaVerifyCode(h, ch.username, code, ch)) {
1044
1142
  // Wrong code: count the attempt; delete the challenge once the cap is
1045
1143
  // hit so a burned-out challenge cannot be ground further.
1046
1144
  ch.attempts = ch.attempts + 1;
1047
- if (ch.attempts >= TWOFA_MAX_ATTEMPTS) AuthDb.twoFaLogins.delete(key);
1048
- else AuthDb.twoFaLogins.patch(key, ch);
1145
+ if (ch.attempts >= TWOFA_MAX_ATTEMPTS) AuthDb.twoFaLogins.compareDeleteSnapshot(key, observed);
1146
+ else AuthDb.twoFaLogins.compareExchangeSnapshot(key, observed, ch);
1049
1147
  return fail();
1050
1148
  }
1051
1149
 
1052
1150
  // SUCCESS: consume-once, then mint the session EXACTLY like login/finish.
1053
- const consumed = AuthDb.twoFaLogins.getDelete(key);
1054
- if (consumed == null) return fail();
1151
+ if (ch.method == TWOFA_TOTP && !Authenticator.consume(h, ch.encryptedSecret, step)) return fail();
1152
+ if (!AuthDb.twoFaLogins.compareDeleteSnapshot(key, observed)) return fail();
1153
+ const consumed = ch;
1055
1154
  const acct = this.account(new Username(h, ch.username));
1056
1155
  if (acct == null || !ctEqual(consumed.accountId, this.incarnation(acct))) return fail();
1057
1156
  const toilUserId = this.stableUserId(ctx, h, ch.username, acct);
1157
+ const state = SessionEpochs.read(crypto.toHex(toilUserId));
1158
+ const currentSettings = FactorRepository.read(h, this.factorName(acct), acct.twoFactorMethod, state);
1159
+ if (currentSettings.revision != consumed.settingsRevision || currentSettings.method != consumed.method ||
1160
+ state.revision != ch.sessionEpoch) return fail();
1058
1161
  const userData = __toilEncodeAuthUser(toilUserId, ch.username);
1059
1162
  const w = new DataWriter();
1060
1163
  w.writeU8(ST_OK);
@@ -1076,6 +1179,7 @@ class Auth {
1076
1179
  @ratelimit(RateLimit.SlidingWindow, 5, 60)
1077
1180
  @post('/2fa/setup')
1078
1181
  public twoFaSetup(_ctx: RouteContext): Response {
1182
+ if (_ctx.request.body.length > 128) return fail();
1079
1183
  const r = new DataReader(_ctx.request.body);
1080
1184
  const targetMethod = r.readU8();
1081
1185
  if (!r.ok) return fail();
@@ -1086,7 +1190,18 @@ class Auth {
1086
1190
  const acct = this.account(new Username(h, u.username));
1087
1191
  if (acct == null) return fail();
1088
1192
 
1089
- const settings = FactorRepository.read(h, this.factorName(acct), acct.twoFactorMethod);
1193
+ const settings = FactorRepository.read(h, this.factorName(acct), acct.twoFactorMethod, AuthService.__sessionState());
1194
+ // Switching an enabled factor also requires its proof; a stolen session is insufficient.
1195
+ if (targetMethod != TWOFA_NONE && settings.method != TWOFA_NONE) {
1196
+ const currentCode = r.readString();
1197
+ if (settings.method == TWOFA_TOTP) {
1198
+ const accountLimit = RateLimitService.guardKeyed(TOTP_ACCOUNT_RL_ROUTE, TWOFA_RL_STRATEGY,
1199
+ 5, 60, h + '\x00' + base64UrlEncode(this.incarnation(acct)));
1200
+ if (accountLimit != null) return accountLimit;
1201
+ }
1202
+ if (!r.ok || settings.method != TWOFA_TOTP || !Authenticator.consume(h, settings.encryptedSecret,
1203
+ Authenticator.match(this.totpBinding(h, this.incarnation(acct)), settings.encryptedSecret, currentCode))) return fail();
1204
+ }
1090
1205
  // Disabling when 2FA is already off: nothing to prove; generic ST_OK.
1091
1206
  if (targetMethod == TWOFA_NONE && settings.method == TWOFA_NONE) {
1092
1207
  return Response.bytes(new DataWriter().writeU8(ST_OK).toBytes());
@@ -1103,7 +1218,7 @@ class Auth {
1103
1218
  targetMethod != TWOFA_NONE
1104
1219
  ? 'enable two-factor authentication'
1105
1220
  : 'turn off two-factor authentication';
1106
- const codeHash = this.twoFaDeliver(
1221
+ const codeHash = deliverMethod == TWOFA_TOTP ? new Uint8Array(1) : this.twoFaDeliver(
1107
1222
  h,
1108
1223
  deliverMethod,
1109
1224
  u.username,
@@ -1117,17 +1232,27 @@ class Auth {
1117
1232
  c.username = u.username;
1118
1233
  c.accountId = this.incarnation(acct);
1119
1234
  c.settingsRevision = settings.revision;
1120
- c.sessionVersion = 2;
1121
- c.sessionEpoch = SessionEpochs.current(AuthService.getSessionBytes()!);
1235
+ c.sessionVersion = 3;
1236
+ c.sessionEpoch = AuthService.__sessionGeneration();
1122
1237
  c.method = deliverMethod;
1238
+ let enrollmentSecret = '';
1239
+ if (deliverMethod == TWOFA_TOTP) {
1240
+ if (targetMethod == TWOFA_TOTP) {
1241
+ const secret = randomBytes(20);
1242
+ enrollmentSecret = Authenticator.base32(secret);
1243
+ c.encryptedSecret = Authenticator.seal(this.totpBinding(h, c.accountId), secret);
1244
+ secret.fill(0);
1245
+ } else c.encryptedSecret = settings.encryptedSecret;
1246
+ }
1123
1247
  c.codeHash = codeHash;
1124
1248
  c.exp = nowSecs() + TWOFA_TTL_SECS;
1125
1249
  c.attempts = 0;
1126
1250
  c.targetMethod = targetMethod; // what to set account.twoFactorMethod to on success
1127
1251
  // One outstanding setup challenge per user: overwrite any prior.
1128
- AuthDb.twoFaSetup.delete(this.secondaryKey(h, acct));
1129
- AuthDb.twoFaSetup.create(this.secondaryKey(h, acct), c);
1130
- return Response.bytes(new DataWriter().writeU8(ST_OK).toBytes());
1252
+ AuthDb.twoFaSetup.upsert(this.secondaryKey(h, acct), c);
1253
+ const response = Response.bytes(new DataWriter().writeU8(ST_OK).writeString(enrollmentSecret).toBytes());
1254
+ response.setHeader('cache-control', 'no-store');
1255
+ return response;
1131
1256
  }
1132
1257
 
1133
1258
  /** POST /auth/2fa/setup/verify (@auth) body: str(code) resp: u8(ST_OK)
@@ -1139,6 +1264,7 @@ class Auth {
1139
1264
  @ratelimit(RateLimit.SlidingWindow, 5, 60)
1140
1265
  @post('/2fa/setup/verify')
1141
1266
  public twoFaSetupVerify(_ctx: RouteContext): Response {
1267
+ if (_ctx.request.body.length > 128) return fail();
1142
1268
  const r = new DataReader(_ctx.request.body);
1143
1269
  const code = r.readString();
1144
1270
  if (!r.ok) return fail();
@@ -1163,27 +1289,34 @@ class Auth {
1163
1289
  const current = this.account(accountKey);
1164
1290
  if (current == null) return fail();
1165
1291
  const key = this.secondaryKey(h, current);
1166
- const ch = AuthDb.twoFaSetup.get(key);
1167
- if (ch == null || ch.sessionVersion != 2 || !SessionEpochs.allowed(AuthService.getSessionBytes()!, ch.sessionEpoch)) return fail();
1292
+ const observed = AuthDb.twoFaSetup.getCurrentSnapshot(key);
1293
+ if (observed == null) return fail();
1294
+ const ch = observed.value;
1295
+ if (ch.sessionVersion != 3 || AuthService.__sessionGeneration() != ch.sessionEpoch) return fail();
1168
1296
  if (nowSecs() >= ch.exp || ch.attempts >= TWOFA_MAX_ATTEMPTS) {
1169
- AuthDb.twoFaSetup.delete(key);
1297
+ AuthDb.twoFaSetup.compareDeleteSnapshot(key, observed);
1170
1298
  return fail();
1171
1299
  }
1172
- if (!this.twoFaVerifyCode(h, ch.username, code, ch)) {
1300
+ const step = ch.method == TWOFA_TOTP ? Authenticator.match(this.totpBinding(h, ch.accountId), ch.encryptedSecret, code) : 0;
1301
+ if (ch.method == TWOFA_TOTP ? step == 0 : !this.twoFaVerifyCode(h, ch.username, code, ch)) {
1173
1302
  ch.attempts = ch.attempts + 1;
1174
- if (ch.attempts >= TWOFA_MAX_ATTEMPTS) AuthDb.twoFaSetup.delete(key);
1175
- else AuthDb.twoFaSetup.patch(key, ch);
1303
+ if (ch.attempts >= TWOFA_MAX_ATTEMPTS) AuthDb.twoFaSetup.compareDeleteSnapshot(key, observed);
1304
+ else AuthDb.twoFaSetup.compareExchangeSnapshot(key, observed, ch);
1176
1305
  return fail();
1177
1306
  }
1178
1307
 
1179
1308
  // SUCCESS: consume-once + apply the method change.
1180
- const consumed = AuthDb.twoFaSetup.getDelete(key);
1181
- if (consumed == null || nowSecs() >= consumed.exp || !this.twoFaVerifyCode(h, consumed.username, code, consumed)) return fail();
1182
- const acct = this.account(accountKey);
1183
- if (acct == null || !ctEqual(consumed.accountId, this.incarnation(acct))) return fail();
1184
- if (!FactorRepository.save(h, this.factorName(acct), consumed.targetMethod, consumed.settingsRevision)) return fail();
1185
- const userData = __toilEncodeAuthUser(this.stableUserId(_ctx, h, u.username, acct), u.username);
1186
- AuthService.revokeUserSessions(userData);
1309
+ if (ch.method == TWOFA_TOTP) {
1310
+ const accepted = ch.targetMethod == TWOFA_TOTP ? Authenticator.initialize(h, ch.encryptedSecret, step) :
1311
+ Authenticator.consume(h, ch.encryptedSecret, step);
1312
+ if (!accepted) return fail();
1313
+ }
1314
+ if (!AuthDb.twoFaSetup.compareDeleteSnapshot(key, observed)) return fail();
1315
+ const consumed = ch;
1316
+ const acct = current;
1317
+ if (!ctEqual(consumed.accountId, this.incarnation(acct))) return fail();
1318
+ if (!AuthService.__changeFactor(h, this.factorName(acct), consumed.settingsRevision, consumed.targetMethod,
1319
+ consumed.targetMethod == TWOFA_TOTP ? consumed.encryptedSecret : new Uint8Array(0))) return fail();
1187
1320
  const response = Response.bytes(new DataWriter().writeU8(ST_OK).toBytes());
1188
1321
  response.setCookie(AuthService.clearSession());
1189
1322
  response.setCookie(AuthService.clearUserCookie());
@@ -1200,7 +1333,7 @@ class Auth {
1200
1333
  const h = realm(_ctx);
1201
1334
  const acct = this.account(new Username(h, u.username));
1202
1335
  if (acct == null) return fail();
1203
- return Response.bytes(new DataWriter().writeU8(FactorRepository.read(h, this.factorName(acct), acct.twoFactorMethod).method).toBytes());
1336
+ return Response.bytes(new DataWriter().writeU8(FactorRepository.read(h, this.factorName(acct), acct.twoFactorMethod, AuthService.__sessionState()).method).toBytes());
1204
1337
  }
1205
1338
 
1206
1339
  /**
@@ -1214,6 +1347,12 @@ class Auth {
1214
1347
  * and pairs with a `case TWOFA_TOTP` in {@link twoFaVerifyCode}. The
1215
1348
  * lifecycle and the login/setup wiring do NOT change. <<<
1216
1349
  */
1350
+ private totpBinding(host: string, accountId: Uint8Array): Uint8Array {
1351
+ const prefix = Uint8Array.wrap(String.UTF8.encode('toil-totp-v1:' + host + '\x00'));
1352
+ const binding = new Uint8Array(prefix.length + accountId.length);
1353
+ binding.set(prefix); binding.set(accountId, prefix.length); return binding;
1354
+ }
1355
+
1217
1356
  private twoFaDeliver(
1218
1357
  host: string,
1219
1358
  method: u8,
@@ -1233,7 +1372,7 @@ class Auth {
1233
1372
  AuthEmail.twofa(email, code, subject, action);
1234
1373
  return twoFaCodeHash(host, username, code);
1235
1374
  }
1236
- // >>> case TWOFA_TOTP: { return twoFaSecretBinding(username); } <<<
1375
+ // Authenticator challenges carry an encrypted secret rather than a delivered code hash.
1237
1376
  default:
1238
1377
  return new Uint8Array(0);
1239
1378
  }
@@ -1257,7 +1396,8 @@ class Auth {
1257
1396
  case TWOFA_EMAIL:
1258
1397
  // Constant-time compare of the two 32-byte SHA-256 hashes.
1259
1398
  return ctEqual(twoFaCodeHash(host, username, code), challenge.codeHash);
1260
- // >>> case TWOFA_TOTP: return totpVerify(challenge.codeHash, code); <<<
1399
+ case TWOFA_TOTP:
1400
+ return Authenticator.match(this.totpBinding(host, challenge.accountId), challenge.encryptedSecret, code) != 0;
1261
1401
  default:
1262
1402
  return false;
1263
1403
  }
@@ -168,7 +168,7 @@ export class AuthMaintenance {
168
168
  AuthDb.twoFaSetup.delete(legacy);
169
169
  // Security epochs intentionally remain so copied cookies and in-flight
170
170
  // logins cannot become valid when the same identity signs up again.
171
- SessionEpochs.revokeId(crypto.toHex(uid));
171
+ SessionEpochs.revokeId(crypto.toHex(uid), key.host);
172
172
  if (!AuthDb.accounts.compareDeleteSnapshot(key, observed)) return false;
173
173
  AuthMaintenance.unindex(uid, key.host, acct.username, AuthMaintenance.incarnation(acct));
174
174
  return true;
@@ -0,0 +1,22 @@
1
+ import { Server } from 'toiljs/server/runtime';
2
+
3
+ /** The routed Host, normalized identically for cookies and authentication storage. */
4
+ export class AuthRealm {
5
+ static normalize(raw: string): string {
6
+ let host = raw.toLowerCase();
7
+ if (host.startsWith('[')) {
8
+ const close = host.indexOf(']');
9
+ if (close >= 0) host = host.slice(0, close + 1);
10
+ } else {
11
+ const colon = host.lastIndexOf(':');
12
+ if (colon > 0) host = host.slice(0, colon);
13
+ }
14
+ return host;
15
+ }
16
+ static current(): string {
17
+ const req = Server.currentRequest;
18
+ if (req == null) return '';
19
+ const raw = req.header('host');
20
+ return raw == null ? '' : AuthRealm.normalize(raw);
21
+ }
22
+ }
@@ -12,6 +12,14 @@ export class SessionEpochKey {
12
12
  @data
13
13
  export class SessionEpoch {
14
14
  revision: u64 = 0;
15
+ claimNonce: Uint8Array = new Uint8Array(0);
16
+ // Factor changes and session fencing share this immutable commit.
17
+ // The account incarnation in factorName prevents inheritance after recreation.
18
+ factorHost: string = '';
19
+ factorName: string = '';
20
+ factorMethod: u8 = 0;
21
+ factorRevision: u64 = 0;
22
+ factorSecret: Uint8Array = new Uint8Array(0);
15
23
  }
16
24
  @data
17
25
  export class FactorKey {
@@ -30,6 +38,11 @@ export class FactorRevision {
30
38
  export class FactorSettings {
31
39
  method: u8 = 0;
32
40
  revision: u64 = 0;
41
+ encryptedSecret: Uint8Array = new Uint8Array(0);
42
+ }
43
+ @data
44
+ export class TotpCounter {
45
+ step: u64 = 0;
33
46
  }
34
47
  @data
35
48
  export class SessionDigest {
@@ -46,6 +59,7 @@ export class AuthStateDb {
46
59
  @collection static revokedSessions: Unique<SessionDigest, RevokedSession>;
47
60
  @collection static epochHeads: Documents<SessionUserKey, SessionEpoch>;
48
61
  @collection static epochRevisions: Unique<SessionEpochKey, SessionEpoch>;
62
+ @collection static totpCounters: Documents<FactorKey, TotpCounter>;
49
63
  @collection static factorHeads: Documents<FactorKey, FactorSettings>;
50
64
  @collection static factorRevisions: Unique<FactorRevision, FactorSettings>;
51
65
  }
@@ -86,6 +86,9 @@ export class AuthAccount {
86
86
  deleting: bool = false;
87
87
  registering: bool = false;
88
88
  legacyFactors: bool = false;
89
+ googleSubject: string = '';
90
+ googleIssuedAt: u64 = 0;
91
+ googleNonces: string[] = new Array<string>();
89
92
  }
90
93
 
91
94
  @data
@@ -132,6 +135,7 @@ export class TwoFaChallenge {
132
135
  sessionEpoch: u64 = 0;
133
136
  sessionVersion: u8 = 0;
134
137
  settingsRevision: u64 = 0;
138
+ encryptedSecret: Uint8Array = new Uint8Array(0);
135
139
  accountId: Uint8Array = new Uint8Array(0);
136
140
  }
137
141
 
@@ -0,0 +1,93 @@
1
+ import { base64UrlEncode } from 'toiljs/server/runtime';
2
+ import { HmacImportParams, HmacParams, ALG_SHA_1, FMT_RAW, USAGE_SIGN, CryptoKey, AlgorithmParams, AesGcmParams, ALG_AES_GCM, USAGE_ENCRYPT, USAGE_DECRYPT } from 'crypto';
3
+ import { DataWriter } from 'data';
4
+ import { webcrypto } from 'bindings/webcrypto';
5
+ import { AuthStateDb, FactorKey, TotpCounter } from './AuthStateDb';
6
+
7
+ @external('env', 'crypto.totp_verify')
8
+ declare function verifyTotp(secret: usize, size: i32, code: usize, length: i32, step: i64): i64;
9
+
10
+ class AesImport extends AlgorithmParams {
11
+ serialize(w: DataWriter): void { w.writeI32(ALG_AES_GCM); w.writeI32(0); }
12
+ }
13
+
14
+ /** RFC 6238: Google Authenticator's SHA1 / 6 digits / 30 seconds profile. */
15
+ export class Authenticator {
16
+ static base32(bytes: Uint8Array): string {
17
+ const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
18
+ let bits: i32 = 0, value: u32 = 0;
19
+ let result = '';
20
+ for (let i = 0; i < bytes.length; i++) {
21
+ value = (value << 8) | bytes[i]; bits += 8;
22
+ while (bits >= 5) { bits -= 5; result += alphabet.charAt((value >> bits) & 31); }
23
+ }
24
+ if (bits > 0) result += alphabet.charAt((value << (5 - bits)) & 31);
25
+ return result;
26
+ }
27
+ private static key(): CryptoKey {
28
+ const value = Environment.getSecure('AUTH_SESSION_SECRET');
29
+ if (value == null || value.length < 32) throw new Error('Authenticator requires AUTH_SESSION_SECRET');
30
+ const key = crypto.sha256Text('toil-totp-encryption-v1\x00' + value);
31
+ return crypto.subtle.importKey(FMT_RAW, key, new AesImport(), false, USAGE_ENCRYPT | USAGE_DECRYPT);
32
+ }
33
+ static seal(binding: Uint8Array, secret: Uint8Array): Uint8Array {
34
+ const iv = new Uint8Array(12); crypto.getRandomValues(iv);
35
+ const aad = binding;
36
+ const ciphertext = crypto.subtle.encrypt(new AesGcmParams(iv, aad, 128), Authenticator.key(), secret);
37
+ const sealed = new Uint8Array(12 + ciphertext.length);
38
+ sealed.set(iv); sealed.set(ciphertext, 12); return sealed;
39
+ }
40
+ static open(binding: Uint8Array, sealed: Uint8Array): Uint8Array | null {
41
+ if (sealed.length != 48) return null;
42
+ const aad = binding;
43
+ const params = new AesGcmParams(sealed.subarray(0, 12), aad, 128).pack();
44
+ const data = sealed.subarray(12);
45
+ const size = webcrypto.decrypt(Authenticator.key().handle, params.dataStart, params.length, data.dataStart, data.length);
46
+ if (size != 20) return null;
47
+ const secret = new Uint8Array(size); webcrypto.takeResult(secret.dataStart, size); return secret;
48
+ }
49
+ static code(secret: Uint8Array, step: u64): string {
50
+ const bytes = new Uint8Array(8);
51
+ for (let i = 7; i >= 0; i--) { bytes[i] = <u8>step; step >>= 8; }
52
+ const key = crypto.subtle.importKey(FMT_RAW, secret, new HmacImportParams(ALG_SHA_1), false, USAGE_SIGN);
53
+ const hash = crypto.subtle.sign(new HmacParams(), key, bytes);
54
+ const o = hash[19] & 15;
55
+ const n = ((<u32>hash[o] & 127) << 24) | (<u32>hash[o + 1] << 16) | (<u32>hash[o + 2] << 8) | hash[o + 3];
56
+ let code = (n % 1000000).toString();
57
+ while (code.length < 6) code = '0' + code;
58
+ return code;
59
+ }
60
+ static match(binding: Uint8Array, sealed: Uint8Array, code: string): u64 {
61
+ if (code.length != 6) return 0;
62
+ for (let i = 0; i < 6; i++) if (code.charCodeAt(i) < 48 || code.charCodeAt(i) > 57) return 0;
63
+ const secret = Authenticator.open(binding, sealed);
64
+ if (secret == null) return 0;
65
+ const bytes = Uint8Array.wrap(String.UTF8.encode(code));
66
+ const matched = verifyTotp(secret.dataStart, secret.length, bytes.dataStart, bytes.length, <i64>(Date.now() / 30000));
67
+ secret.fill(0);
68
+ return matched > 0 ? <u64>matched : 0;
69
+ }
70
+
71
+ // An authenticated, randomized 256-bit ciphertext prefix identifies the enrollment.
72
+ // No extra hash or per-verification token row is needed.
73
+
74
+ /** Fresh randomized enrollment ciphertext: reserve its first step without a preceding read. */
75
+ static initialize(host: string, sealed: Uint8Array, step: u64): bool {
76
+ if (step == 0) return false;
77
+ const key = new FactorKey(host, base64UrlEncode(sealed.subarray(12, 44)));
78
+ const next = new TotpCounter(); next.step = step;
79
+ return AuthStateDb.totpCounters.compareExchange(key, null, next);
80
+ }
81
+
82
+ /** One linearizable monotonic counter per enrollment, never one row per code. */
83
+ static consume(host: string, sealed: Uint8Array, step: u64): bool {
84
+ if (step == 0) return false;
85
+ const key = new FactorKey(host, base64UrlEncode(sealed.subarray(12, 44)));
86
+ const observed = AuthStateDb.totpCounters.getCurrentSnapshot(key);
87
+ if (observed == null && Db.lastError() != DbError.None) throw new Error('Authenticator state unavailable');
88
+ if (observed != null && observed.value.step >= step) return false;
89
+ const next = new TotpCounter(); next.step = step;
90
+ return observed == null ? AuthStateDb.totpCounters.compareExchange(key, null, next) :
91
+ AuthStateDb.totpCounters.compareExchangeSnapshot(key, observed, next);
92
+ }
93
+ }