toiljs 0.0.90 → 0.0.92

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.
@@ -39,6 +39,13 @@ function fromHex(hex: string): Uint8Array {
39
39
  return out;
40
40
  }
41
41
 
42
+ /** bytes -> lowercase-hex. */
43
+ function toHex(bytes: Uint8Array): string {
44
+ let s = '';
45
+ for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, '0');
46
+ return s;
47
+ }
48
+
42
49
  /**
43
50
  * The server's PINNED static ML-KEM-768 public key. The client encapsulates to
44
51
  * it; only the genuine server (holder of the matching secret key) can
@@ -353,17 +360,23 @@ export async function login(
353
360
  wipe(sharedSecret);
354
361
  throw new EmailNotConfirmedError();
355
362
  }
356
- if (loginStatus !== 0) {
363
+ // status 3 = 2FA required: the credential verified but the account has a second
364
+ // factor. The server ALSO returns its serverConfirm tag (so we still complete
365
+ // mutual auth below) but mints NO session/cookie. Both the success (0) and the
366
+ // 2FA (3) responses are `bytes(first) bytes(serverConfirm)` -- `first` is the
367
+ // session token on 0 and the twoFaId on 3.
368
+ if (loginStatus !== 0 && loginStatus !== 3) {
357
369
  wipe(sharedSecret);
358
370
  throw new Error('auth: login failed');
359
371
  }
360
- const session = res.readBytes();
372
+ const first = res.readBytes();
361
373
  const serverConfirm = res.readBytes();
362
374
 
363
375
  // 5. Mutual auth: derive the session key K = HMAC(sharedSecret, label || H(M)),
364
376
  // then check the server's tag = HMAC(K, label || H(M)). Only a server that
365
377
  // decapsulated correctly derives the same K, so a valid tag proves its
366
- // identity. Verify before returning the session.
378
+ // identity. Runs for BOTH statuses, so a 2FA prompt only ever appears AFTER
379
+ // the server has authenticated itself.
367
380
  const transcriptHash = await sha256Bytes(message);
368
381
  const sessionKey = await hmacSha256(
369
382
  sharedSecret,
@@ -376,7 +389,14 @@ export async function login(
376
389
  );
377
390
  if (!bytesEqual(expected, serverConfirm)) throw new Error('auth: server authentication failed');
378
391
 
379
- return session; // session token
392
+ if (loginStatus === 3) {
393
+ // The server authenticated itself, but a second factor is required. Surface
394
+ // the twoFaId (hex) so the caller can collect a code and call
395
+ // verifyTwoFactor. NO session exists yet.
396
+ throw new TwoFactorRequiredError(toHex(first));
397
+ }
398
+
399
+ return first; // session token
380
400
  }
381
401
 
382
402
  /** Thrown by {@link login} when the credential is valid but the account's email
@@ -389,6 +409,91 @@ export class EmailNotConfirmedError extends Error {
389
409
  }
390
410
  }
391
411
 
412
+ /** Thrown by {@link login} when the password verified AND the server authenticated
413
+ * itself (mutual auth passed) but the account requires a SECOND FACTOR. No session
414
+ * exists yet. Catch it, collect the delivered code, and call
415
+ * {@link verifyTwoFactor} with `err.twoFaId`. */
416
+ export class TwoFactorRequiredError extends Error {
417
+ /** The opaque login-challenge id (hex) to echo to {@link verifyTwoFactor}. */
418
+ readonly twoFaId: string;
419
+ constructor(twoFaId: string) {
420
+ super('auth: two-factor authentication required');
421
+ this.name = 'TwoFactorRequiredError';
422
+ this.twoFaId = twoFaId;
423
+ }
424
+ }
425
+
426
+ /** The 2FA method values, mirroring the server enum (append-only). */
427
+ export const TwoFactorMethod = { None: 0, Email: 1 } as const;
428
+
429
+ /**
430
+ * Complete a 2FA login: submit the delivered `code` for the challenge `twoFaId`
431
+ * (from {@link TwoFactorRequiredError}). On success the server mints the session
432
+ * (sets the cookies) and returns the opaque session token. Throws one generic
433
+ * error ("code invalid or expired") on any failure -- the code is single-use and
434
+ * attempt-limited server-side.
435
+ */
436
+ export async function verifyTwoFactor(
437
+ twoFaId: string,
438
+ code: string,
439
+ opts: AuthOptions = {},
440
+ ): Promise<Uint8Array> {
441
+ const baseUrl = opts.baseUrl ?? '/auth';
442
+ const res = await postBinary(
443
+ baseUrl,
444
+ '/2fa/verify',
445
+ new DataWriter().writeBytes(fromHex(twoFaId)).writeString(code).toBytes(),
446
+ );
447
+ if (res.readU8() !== 0) throw new Error('auth: two-factor code invalid or expired');
448
+ return res.readBytes(); // opaque session token
449
+ }
450
+
451
+ /**
452
+ * Begin enabling or disabling 2FA for the CURRENT session user. Pass a
453
+ * {@link TwoFactorMethod} value (`Email` to enable email 2FA, `None` to disable).
454
+ * The server delivers a proof code (to the new method when enabling, or the
455
+ * CURRENT method when disabling - anti-hijack); confirm it with
456
+ * {@link confirmTwoFactorSetup}. Requires a valid session.
457
+ */
458
+ export async function setupTwoFactor(method: number, opts: AuthOptions = {}): Promise<void> {
459
+ const baseUrl = opts.baseUrl ?? '/auth';
460
+ const res = await postBinary(
461
+ baseUrl,
462
+ '/2fa/setup',
463
+ new DataWriter().writeU8(method).toBytes(),
464
+ );
465
+ if (res.readU8() !== 0) throw new Error('auth: two-factor setup failed');
466
+ }
467
+
468
+ /**
469
+ * Confirm a pending {@link setupTwoFactor} by submitting the delivered `code`.
470
+ * On success the account's 2FA method is switched (enabled or disabled). Requires
471
+ * a valid session. Throws (generic) if the code is wrong or expired.
472
+ */
473
+ export async function confirmTwoFactorSetup(code: string, opts: AuthOptions = {}): Promise<void> {
474
+ const baseUrl = opts.baseUrl ?? '/auth';
475
+ const res = await postBinary(
476
+ baseUrl,
477
+ '/2fa/setup/verify',
478
+ new DataWriter().writeString(code).toBytes(),
479
+ );
480
+ if (res.readU8() !== 0) throw new Error('auth: two-factor setup confirmation failed');
481
+ }
482
+
483
+ /**
484
+ * The current session user's 2FA method (a {@link TwoFactorMethod} value; `0` =
485
+ * off). Requires a valid session. For the UI to reflect enabled/disabled state.
486
+ */
487
+ export async function twoFactorStatus(opts: AuthOptions = {}): Promise<number> {
488
+ const baseUrl = opts.baseUrl ?? '/auth';
489
+ const res = await fetch(baseUrl + '/2fa/status', {
490
+ method: 'GET',
491
+ credentials: 'same-origin',
492
+ });
493
+ if (!res.ok) throw new Error('auth: request failed');
494
+ return new DataReader(new Uint8Array(await res.arrayBuffer())).readU8();
495
+ }
496
+
392
497
  /** Confirm an account from the one-time token in the emailed link
393
498
  * (`/confirm?token=<hex>`). Throws if the token is invalid or expired. */
394
499
  export async function confirmEmail(token: string, opts: AuthOptions = {}): Promise<void> {
@@ -489,6 +594,11 @@ export const Auth = {
489
594
  resendConfirmation,
490
595
  requestPasswordReset,
491
596
  resetPassword,
597
+ verifyTwoFactor,
598
+ setupTwoFactor,
599
+ confirmTwoFactorSetup,
600
+ twoFactorStatus,
601
+ TwoFactorMethod,
492
602
  buildLoginMessage,
493
603
  LOGIN_CONTEXT,
494
604
  } as const;
@@ -24,7 +24,7 @@ import { __resetDbForTests } from '../src/devserver/db/index.js';
24
24
  import { __resetRatelimitForTests } from '../src/devserver/config/ratelimit.js';
25
25
  import { clearEnvCache } from '../src/devserver/config/dotenv.js';
26
26
  import { __sentEmails, __clearSentEmails } from '../src/devserver/email/index.js';
27
- import { Auth, EmailNotConfirmedError } from '../src/client/auth.js';
27
+ import { Auth, EmailNotConfirmedError, TwoFactorRequiredError } from '../src/client/auth.js';
28
28
  import { DataReader, DataWriter } from '../src/io/codec.js';
29
29
 
30
30
  const EXAMPLE_WASM = path.resolve(
@@ -40,17 +40,20 @@ function loadModule(): WasmServerModule {
40
40
  return m;
41
41
  }
42
42
 
43
- /** Route the client's `fetch(path, {body})` into the dev wasm dispatcher (with a cookie jar). */
43
+ /** Route the client's `fetch(path, {body})` into the dev wasm dispatcher (with a cookie jar).
44
+ * The Host header the client's requests carry is settable (`setHost`) so a test can drive
45
+ * the same client against DIFFERENT tenant domains and prove per-host auth isolation. */
44
46
  function installFetchShim(m: WasmServerModule): () => void {
45
47
  const original = globalThis.fetch;
46
48
  const jar = new Map<string, string>();
49
+ let host = 'localhost:3000';
47
50
  globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
48
51
  const url = typeof input === 'string' ? input : input.toString();
49
52
  const pathname = new URL(url, 'http://localhost').pathname;
50
53
  const bodyBytes =
51
54
  init?.body == null ? new Uint8Array(0) : new Uint8Array(init.body as ArrayBuffer);
52
55
  const headers: [string, string][] = [
53
- ['host', 'localhost:3000'],
56
+ ['host', host],
54
57
  ['content-type', 'application/octet-stream'],
55
58
  ];
56
59
  if (jar.size > 0)
@@ -80,6 +83,9 @@ function installFetchShim(m: WasmServerModule): () => void {
80
83
  globalThis.fetch = original;
81
84
  },
82
85
  jar,
86
+ setHost: (h: string) => {
87
+ host = h;
88
+ },
83
89
  };
84
90
  }
85
91
 
@@ -117,10 +123,26 @@ function tokenFromEmail(kind: 'confirm' | 'reset', to: string): string {
117
123
  );
118
124
  }
119
125
 
126
+ /** Pull the 6-digit code out of the most-recent captured 2FA email (purpose `2fa`) to `to`. */
127
+ function codeFromEmail(to: string): string {
128
+ for (let i = __sentEmails.length - 1; i >= 0; i--) {
129
+ const msg = __sentEmails[i];
130
+ if (msg.to !== to || msg.purpose !== '2fa') continue;
131
+ const hit = /\b(\d{6})\b/.exec(msg.text) ?? /\b(\d{6})\b/.exec(msg.html);
132
+ if (hit) return hit[1];
133
+ }
134
+ throw new Error(
135
+ `no 2fa code emailed to ${to}; captured=${JSON.stringify(
136
+ __sentEmails.map((e) => ({ to: e.to, purpose: e.purpose })),
137
+ )}`,
138
+ );
139
+ }
140
+
120
141
  describe.skipIf(!haveWasm)('built-in auth: email verification + password reset (client <-> example wasm)', () => {
121
142
  let restoreFetch: () => void;
122
143
  let mod: WasmServerModule;
123
144
  let jar: Map<string, string>;
145
+ let setHost: (h: string) => void;
124
146
 
125
147
  beforeEach(() => {
126
148
  __resetDbForTests();
@@ -133,6 +155,7 @@ describe.skipIf(!haveWasm)('built-in auth: email verification + password reset (
133
155
  const shim = installFetchShim(mod);
134
156
  restoreFetch = shim.restore;
135
157
  jar = shim.jar;
158
+ setHost = shim.setHost;
136
159
  });
137
160
  afterEach(() => {
138
161
  restoreFetch();
@@ -164,10 +187,13 @@ describe.skipIf(!haveWasm)('built-in auth: email verification + password reset (
164
187
  it(
165
188
  'reset link is NOT poisonable via a crafted Host header (#6 host-header reset-poisoning)',
166
189
  async () => {
190
+ // grace lives on the victim tenant (realm = normalized Host "victim.com").
191
+ setHost('victim.com');
167
192
  await Auth.register('grace', 'pw-grace-correct', 'grace@x.com');
168
193
  __clearSentEmails();
169
194
  // Attacker triggers reset/request with a Host that routes to the victim
170
- // (the edge strip_port -> "victim.com") but, dropped raw into a link,
195
+ // (the edge strip_port -> "victim.com", which is grace's realm, so the
196
+ // request DOES resolve her account) but, dropped raw into a link,
171
197
  // reparents the URL authority to attacker.com.
172
198
  const body = new DataWriter().writeString('grace@x.com').toBytes();
173
199
  const r = mod.dispatch({
@@ -330,4 +356,364 @@ describe.skipIf(!haveWasm)('built-in auth: email verification + password reset (
330
356
  },
331
357
  60_000,
332
358
  );
359
+
360
+ // ---- multi-method 2FA (email) ----
361
+
362
+ it(
363
+ '(a) full email-2FA login round-trip: enable, login requires a code, verify mints the session',
364
+ async () => {
365
+ await Auth.register('dave', 'dave-pw-strong', 'dave@x.com');
366
+ await Auth.login('dave', 'dave-pw-strong'); // 2FA off -> session
367
+
368
+ // Enable email 2FA: setup delivers a code, confirm switches the method on.
369
+ await Auth.setupTwoFactor(Auth.TwoFactorMethod.Email);
370
+ await Auth.confirmTwoFactorSetup(codeFromEmail('dave@x.com'));
371
+ expect(await Auth.twoFactorStatus()).toBe(Auth.TwoFactorMethod.Email);
372
+
373
+ __clearSentEmails();
374
+ jar.clear(); // drop the existing session so login is a clean 2FA challenge
375
+
376
+ // Login now demands a second factor: mutual auth still passes (login()
377
+ // verifies serverConfirm before throwing), but NO session is minted.
378
+ let err: unknown;
379
+ try {
380
+ await Auth.login('dave', 'dave-pw-strong');
381
+ } catch (e) {
382
+ err = e;
383
+ }
384
+ expect(err).toBeInstanceOf(TwoFactorRequiredError);
385
+ const twoFaId = (err as TwoFactorRequiredError).twoFaId;
386
+ expect(twoFaId.length).toBeGreaterThan(0);
387
+ expect(jar.get('toil_sess')).toBeUndefined(); // no session at login/finish
388
+
389
+ // Read the login code out of the captured email and verify -> session.
390
+ const session = await Auth.verifyTwoFactor(twoFaId, codeFromEmail('dave@x.com'));
391
+ expect(session.length).toBeGreaterThan(0);
392
+
393
+ // /auth/me now returns the user.
394
+ const meRes = await fetch('/auth/me');
395
+ expect(meRes.status).toBe(200);
396
+ const me = new DataReader(new Uint8Array(await meRes.arrayBuffer()));
397
+ expect(me.readBytes().length).toBeGreaterThan(0); // toilUserId
398
+ expect(me.readString()).toBe('dave');
399
+ },
400
+ 90_000,
401
+ );
402
+
403
+ it(
404
+ '(b) 2FA code security: wrong code rejected + attempt-limited to death, correct code single-use',
405
+ async () => {
406
+ await Auth.register('eve', 'eve-pw-strong', 'eve@x.com');
407
+ await Auth.login('eve', 'eve-pw-strong');
408
+ await Auth.setupTwoFactor(Auth.TwoFactorMethod.Email);
409
+ await Auth.confirmTwoFactorSetup(codeFromEmail('eve@x.com'));
410
+
411
+ // ---- wrong code is rejected, and after TWOFA_MAX_ATTEMPTS the challenge dies ----
412
+ __clearSentEmails();
413
+ jar.clear();
414
+ let err: unknown;
415
+ try {
416
+ await Auth.login('eve', 'eve-pw-strong');
417
+ } catch (e) {
418
+ err = e;
419
+ }
420
+ const twoFaId = (err as TwoFactorRequiredError).twoFaId;
421
+ const code = codeFromEmail('eve@x.com');
422
+ const wrong = code === '000000' ? '111111' : '000000';
423
+
424
+ // 5 (TWOFA_MAX_ATTEMPTS) wrong guesses. Reset the per-IP limiter between
425
+ // each so this exercises the CHALLENGE's own attempt cap, not @ratelimit.
426
+ for (let i = 0; i < 5; i++) {
427
+ __resetRatelimitForTests();
428
+ await expect(Auth.verifyTwoFactor(twoFaId, wrong)).rejects.toThrow();
429
+ }
430
+ // The challenge is now destroyed: even the CORRECT code fails.
431
+ __resetRatelimitForTests();
432
+ await expect(Auth.verifyTwoFactor(twoFaId, code)).rejects.toThrow();
433
+
434
+ // ---- a correct code is single-use: replay fails ----
435
+ __clearSentEmails();
436
+ jar.clear();
437
+ __resetRatelimitForTests();
438
+ let err2: unknown;
439
+ try {
440
+ await Auth.login('eve', 'eve-pw-strong');
441
+ } catch (e) {
442
+ err2 = e;
443
+ }
444
+ const twoFaId2 = (err2 as TwoFactorRequiredError).twoFaId;
445
+ const code2 = codeFromEmail('eve@x.com');
446
+ const session = await Auth.verifyTwoFactor(twoFaId2, code2); // consumes
447
+ expect(session.length).toBeGreaterThan(0);
448
+ __resetRatelimitForTests();
449
+ await expect(Auth.verifyTwoFactor(twoFaId2, code2)).rejects.toThrow(); // replay dead
450
+ },
451
+ 120_000,
452
+ );
453
+
454
+ it(
455
+ '(c) cross-flow: reset tokens and 2FA codes are NOT interchangeable (namespace separation)',
456
+ async () => {
457
+ await Auth.register('frank', 'frank-pw-strong', 'frank@x.com');
458
+
459
+ // ---- direction 1: a LIVE reset token is useless at /auth/2fa/verify ----
460
+ await Auth.requestPasswordReset('frank@x.com');
461
+ const resetToken = tokenFromEmail('reset', 'frank@x.com'); // live resetTokens entry
462
+ __resetRatelimitForTests();
463
+ // Present the reset token as BOTH the twoFaId AND the code: /2fa/verify
464
+ // looks in `twoFaLogins` (a different collection) -> nothing -> rejected.
465
+ await expect(Auth.verifyTwoFactor(resetToken, resetToken)).rejects.toThrow();
466
+
467
+ // ---- direction 2: a LIVE 2FA login challenge id is useless at /auth/reset/finish ----
468
+ await Auth.login('frank', 'frank-pw-strong'); // session (2FA still off here)
469
+ __clearSentEmails();
470
+ await Auth.setupTwoFactor(Auth.TwoFactorMethod.Email);
471
+ await Auth.confirmTwoFactorSetup(codeFromEmail('frank@x.com'));
472
+ __clearSentEmails();
473
+ jar.clear();
474
+ __resetRatelimitForTests();
475
+ let err: unknown;
476
+ try {
477
+ await Auth.login('frank', 'frank-pw-strong');
478
+ } catch (e) {
479
+ err = e;
480
+ }
481
+ const twoFaId = (err as TwoFactorRequiredError).twoFaId; // live twoFaLogins key
482
+ const loginCode = codeFromEmail('frank@x.com');
483
+
484
+ // Submit the live 2FA challenge id AND the live 2FA code to
485
+ // /auth/reset/finish as the reset token: reset/finish looks in
486
+ // `resetTokens` -> nothing -> non-200. A live 2FA challenge is NOT a
487
+ // reset token.
488
+ const probes: Uint8Array[] = [hexToBytes(twoFaId), new TextEncoder().encode(loginCode)];
489
+ for (const raw of probes) {
490
+ __resetRatelimitForTests();
491
+ const body = new DataWriter()
492
+ .writeBytes(raw)
493
+ .writeBytes(new Uint8Array(1312)) // valid-length pk (reach the consume step)
494
+ .writeBytes(new Uint8Array(2420)) // valid-length proof
495
+ .toBytes();
496
+ const r = mod.dispatch({
497
+ method: 'POST',
498
+ path: '/auth/reset/finish',
499
+ headers: [
500
+ ['host', 'localhost:3000'],
501
+ ['content-type', 'application/octet-stream'],
502
+ ],
503
+ body,
504
+ });
505
+ expect(r.status).not.toBe(200);
506
+ }
507
+
508
+ // The cross-flow probes touched NOTHING: the real 2FA login still
509
+ // completes with its real (twoFaId, code).
510
+ __resetRatelimitForTests();
511
+ const session = await Auth.verifyTwoFactor(twoFaId, loginCode);
512
+ expect(session.length).toBeGreaterThan(0);
513
+ },
514
+ 120_000,
515
+ );
516
+
517
+ it(
518
+ '(d) NO session cookie is set on the ST_TWOFA_REQUIRED login response',
519
+ async () => {
520
+ await Auth.register('gwen', 'gwen-pw-strong', 'gwen@x.com');
521
+ await Auth.login('gwen', 'gwen-pw-strong');
522
+ await Auth.setupTwoFactor(Auth.TwoFactorMethod.Email);
523
+ await Auth.confirmTwoFactorSetup(codeFromEmail('gwen@x.com'));
524
+
525
+ jar.clear(); // drop every cookie
526
+ __clearSentEmails();
527
+ __resetRatelimitForTests();
528
+
529
+ let err: unknown;
530
+ try {
531
+ await Auth.login('gwen', 'gwen-pw-strong');
532
+ } catch (e) {
533
+ err = e;
534
+ }
535
+ expect(err).toBeInstanceOf(TwoFactorRequiredError);
536
+ // The shim folds any Set-Cookie into the jar; login/finish set NONE.
537
+ expect(jar.get('toil_sess')).toBeUndefined();
538
+ expect(jar.get('toil_user')).toBeUndefined();
539
+ // With no session cookie, the @auth-gated /auth/me is 401.
540
+ const meRes = await fetch('/auth/me');
541
+ expect(meRes.status).toBe(401);
542
+ },
543
+ 60_000,
544
+ );
545
+
546
+ it(
547
+ '(e) login<->setup 2FA challenges are separate: a setup code cannot mint a login session, and setup/verify never silently disables 2FA',
548
+ async () => {
549
+ await Auth.register('ivy', 'ivy-pw-strong', 'ivy@x.com');
550
+ await Auth.login('ivy', 'ivy-pw-strong'); // session; 2FA still off
551
+
552
+ // Begin a 2FA SETUP: writes a challenge into `twoFaSetup` (keyed by
553
+ // username), NOT a login challenge into `twoFaLogins`.
554
+ __clearSentEmails();
555
+ __resetRatelimitForTests();
556
+ await Auth.setupTwoFactor(Auth.TwoFactorMethod.Email);
557
+ const setupCode = codeFromEmail('ivy@x.com');
558
+
559
+ // Present the LIVE setup code at /auth/2fa/verify with a fabricated
560
+ // twoFaId: /2fa/verify consults ONLY `twoFaLogins`, so the id misses and
561
+ // a setup code can never mint a login session.
562
+ __resetRatelimitForTests();
563
+ const fakeId = 'ab'.repeat(16); // 16-byte hex, not a real twoFaLogins key
564
+ await expect(Auth.verifyTwoFactor(fakeId, setupCode)).rejects.toThrow();
565
+
566
+ // The probe consumed NOTHING: the real setup still completes with the code.
567
+ __resetRatelimitForTests();
568
+ await Auth.confirmTwoFactorSetup(setupCode);
569
+ expect(await Auth.twoFactorStatus()).toBe(Auth.TwoFactorMethod.Email);
570
+
571
+ // With 2FA now ON but NO pending setup challenge, /auth/2fa/setup/verify is
572
+ // a no-op: a stray code cannot flip (disable) the method. A login challenge
573
+ // (targetMethod=NONE) has no wire path here and can never be routed in to
574
+ // silently disable 2FA.
575
+ __resetRatelimitForTests();
576
+ await expect(Auth.confirmTwoFactorSetup('000000')).rejects.toThrow();
577
+ expect(await Auth.twoFactorStatus()).toBe(Auth.TwoFactorMethod.Email);
578
+ },
579
+ 120_000,
580
+ );
581
+
582
+ it(
583
+ '(f) cross-flow: confirm tokens and 2FA codes are NOT interchangeable (namespace separation)',
584
+ async () => {
585
+ setConfirmation(true);
586
+ await Auth.register('jade', 'jade-pw-strong', 'jade@x.com'); // unconfirmed -> confirm token emailed
587
+ const confirmToken = tokenFromEmail('confirm', 'jade@x.com'); // live confirmTokens entry
588
+
589
+ // ---- direction 1: a LIVE confirm token is useless at /auth/2fa/verify ----
590
+ __resetRatelimitForTests();
591
+ // Present the confirm token as BOTH the twoFaId AND the code: /2fa/verify
592
+ // reads `twoFaLogins` (a different collection) -> nothing -> rejected.
593
+ await expect(Auth.verifyTwoFactor(confirmToken, confirmToken)).rejects.toThrow();
594
+
595
+ // The probe consumed NOTHING: the confirm token still confirms the account,
596
+ // and login then succeeds (email now confirmed).
597
+ __resetRatelimitForTests();
598
+ await Auth.confirmEmail(confirmToken);
599
+ __resetRatelimitForTests();
600
+ expect((await Auth.login('jade', 'jade-pw-strong')).length).toBeGreaterThan(0);
601
+
602
+ // ---- direction 2: a LIVE 2FA login id/code is useless at /auth/confirm ----
603
+ // Enable 2FA (jade is confirmed + has a session from the login above).
604
+ __clearSentEmails();
605
+ __resetRatelimitForTests();
606
+ await Auth.setupTwoFactor(Auth.TwoFactorMethod.Email);
607
+ await Auth.confirmTwoFactorSetup(codeFromEmail('jade@x.com'));
608
+
609
+ // Fresh login -> a live `twoFaLogins` challenge (id + emailed code).
610
+ __clearSentEmails();
611
+ jar.clear();
612
+ __resetRatelimitForTests();
613
+ let err: unknown;
614
+ try {
615
+ await Auth.login('jade', 'jade-pw-strong');
616
+ } catch (e) {
617
+ err = e;
618
+ }
619
+ const twoFaId = (err as TwoFactorRequiredError).twoFaId;
620
+ const loginCode = codeFromEmail('jade@x.com');
621
+
622
+ // Submit the live 2FA id AND the live code to /auth/confirm as the confirm
623
+ // token: /auth/confirm consumes from `confirmTokens` (sha256(raw)) -> nothing
624
+ // -> non-200. A 2FA credential is NOT a confirm token.
625
+ const probes: Uint8Array[] = [hexToBytes(twoFaId), new TextEncoder().encode(loginCode)];
626
+ for (const raw of probes) {
627
+ __resetRatelimitForTests();
628
+ const body = new DataWriter().writeBytes(raw).toBytes();
629
+ const r = mod.dispatch({
630
+ method: 'POST',
631
+ path: '/auth/confirm',
632
+ headers: [
633
+ ['host', 'localhost:3000'],
634
+ ['content-type', 'application/octet-stream'],
635
+ ],
636
+ body,
637
+ });
638
+ expect(r.status).not.toBe(200);
639
+ }
640
+
641
+ // The probes touched NOTHING: the real 2FA login still completes.
642
+ __resetRatelimitForTests();
643
+ const session = await Auth.verifyTwoFactor(twoFaId, loginCode);
644
+ expect(session.length).toBeGreaterThan(0);
645
+ },
646
+ 120_000,
647
+ );
648
+
649
+ it(
650
+ '(g) per-domain isolation: a confirm/reset/2FA code minted on domain A is USELESS on domain B',
651
+ async () => {
652
+ const A = 'a.example.com';
653
+ const B = 'b.example.com';
654
+
655
+ // ---- confirm token: minted on A, unredeemable on B ----
656
+ setConfirmation(true);
657
+ setHost(A);
658
+ await Auth.register('mia', 'mia-pw-strong', 'mia@x.com'); // realm A + confirm token emailed
659
+ const confirmTok = tokenFromEmail('confirm', 'mia@x.com');
660
+
661
+ setHost(B);
662
+ __resetRatelimitForTests();
663
+ // Same raw token, different realm -> tokenId(B, raw) is a different key -> miss.
664
+ await expect(Auth.confirmEmail(confirmTok)).rejects.toThrow();
665
+
666
+ setHost(A);
667
+ __resetRatelimitForTests();
668
+ await Auth.confirmEmail(confirmTok); // realm A -> confirms
669
+ setConfirmation(false);
670
+
671
+ // ---- reset token: minted on A, unredeemable on B ----
672
+ setHost(A);
673
+ __clearSentEmails();
674
+ __resetRatelimitForTests();
675
+ await Auth.requestPasswordReset('mia@x.com');
676
+ const resetTok = tokenFromEmail('reset', 'mia@x.com');
677
+
678
+ setHost(B);
679
+ __resetRatelimitForTests();
680
+ await expect(Auth.resetPassword(resetTok, 'mia-pw-new')).rejects.toThrow(); // realm B miss
681
+
682
+ setHost(A);
683
+ __resetRatelimitForTests();
684
+ await Auth.resetPassword(resetTok, 'mia-pw-new'); // realm A -> resets
685
+
686
+ // ---- 2FA login code: minted on A, unusable on B ----
687
+ setHost(A);
688
+ __resetRatelimitForTests();
689
+ await Auth.login('mia', 'mia-pw-new'); // session on A (2FA still off)
690
+ __clearSentEmails();
691
+ await Auth.setupTwoFactor(Auth.TwoFactorMethod.Email);
692
+ await Auth.confirmTwoFactorSetup(codeFromEmail('mia@x.com')); // 2FA enabled on A
693
+
694
+ __clearSentEmails();
695
+ jar.clear();
696
+ __resetRatelimitForTests();
697
+ let err: unknown;
698
+ try {
699
+ await Auth.login('mia', 'mia-pw-new'); // -> 2FA challenge (twoFaId + code, realm A)
700
+ } catch (e) {
701
+ err = e;
702
+ }
703
+ const twoFaId = (err as TwoFactorRequiredError).twoFaId;
704
+ const loginCode = codeFromEmail('mia@x.com');
705
+
706
+ setHost(B);
707
+ __resetRatelimitForTests();
708
+ // The twoFaId lives in twoFaLogins under realm A; on B its key (and the
709
+ // realm-bound codeHash) miss -> a code from A cannot mint a session on B.
710
+ await expect(Auth.verifyTwoFactor(twoFaId, loginCode)).rejects.toThrow();
711
+
712
+ setHost(A);
713
+ __resetRatelimitForTests();
714
+ const session = await Auth.verifyTwoFactor(twoFaId, loginCode); // realm A -> mints
715
+ expect(session.length).toBeGreaterThan(0);
716
+ },
717
+ 180_000,
718
+ );
333
719
  });