toiljs 0.0.94 → 0.0.96

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.
@@ -196,7 +196,7 @@ async function postBinary(baseUrl: string, path: string, body: Uint8Array): Prom
196
196
  body: body as BodyInit,
197
197
  credentials: 'same-origin',
198
198
  });
199
- if (!res.ok) throw new Error('auth: request failed');
199
+ if (!res.ok) throw new AuthError(AuthErrorCode.RequestFailed, 'The auth request failed.');
200
200
  return new DataReader(new Uint8Array(await res.arrayBuffer()));
201
201
  }
202
202
 
@@ -230,7 +230,8 @@ export async function register(
230
230
  new DataWriter().writeString(username).writeBytes(blinded).toBytes(),
231
231
  );
232
232
  const status = start.readU8();
233
- if (status !== 0) throw new Error('auth: registration unavailable');
233
+ if (status !== 0)
234
+ throw new AuthError(AuthErrorCode.RequestFailed, 'Registration is unavailable right now.');
234
235
  const kdf = decodeKdf(start);
235
236
  const evaluated = start.readBytes();
236
237
 
@@ -253,7 +254,8 @@ export async function register(
253
254
  } finally {
254
255
  wipe(seed);
255
256
  }
256
- if (publicKey.length !== PUBLIC_KEY_LEN) throw new Error('auth: bad public key length');
257
+ if (publicKey.length !== PUBLIC_KEY_LEN)
258
+ throw new AuthError(AuthErrorCode.ProtocolError, 'Server returned a bad public key length.');
257
259
 
258
260
  // 3. Submit the username + email + public key + proof-of-possession.
259
261
  const finish = await postBinary(
@@ -267,9 +269,10 @@ export async function register(
267
269
  .toBytes(),
268
270
  );
269
271
  const finishStatus = finish.readU8();
270
- if (finishStatus === 1) throw new Error('auth: username already registered (log in instead)');
271
- if (finishStatus === 2) throw new Error('auth: email already in use');
272
- if (finishStatus !== 0) throw new Error('auth: registration rejected');
272
+ if (finishStatus === 1) throw new UsernameTakenError();
273
+ if (finishStatus === 2) throw new EmailInUseError();
274
+ if (finishStatus !== 0)
275
+ throw new AuthError(AuthErrorCode.RegistrationRejected, 'Registration was rejected.');
273
276
  }
274
277
 
275
278
  /**
@@ -310,7 +313,8 @@ export async function login(
310
313
  const exp = r.readU64();
311
314
  const evaluated = r.readBytes();
312
315
  // Client-side fast-fail only; the server re-checks expiry authoritatively.
313
- if (BigInt(Math.floor(Date.now() / 1000)) >= exp) throw new Error('auth: challenge expired');
316
+ if (BigInt(Math.floor(Date.now() / 1000)) >= exp)
317
+ throw new AuthError(AuthErrorCode.ProtocolError, 'The login challenge expired; retry.');
314
318
 
315
319
  // 2. OPRF -> keyed salt -> seed.
316
320
  const oprfOutput = oprf.finalize(pw, blind, evaluated);
@@ -344,7 +348,8 @@ export async function login(
344
348
  } finally {
345
349
  wipe(seed);
346
350
  }
347
- if (signature.length !== SIGNATURE_LEN) throw new Error('auth: bad signature length');
351
+ if (signature.length !== SIGNATURE_LEN)
352
+ throw new AuthError(AuthErrorCode.ProtocolError, 'Computed a bad signature length.');
348
353
 
349
354
  // 4. Submit {cid, ct, signature}.
350
355
  const res = await postBinary(
@@ -367,7 +372,7 @@ export async function login(
367
372
  // session token on 0 and the twoFaId on 3.
368
373
  if (loginStatus !== 0 && loginStatus !== 3) {
369
374
  wipe(sharedSecret);
370
- throw new Error('auth: login failed');
375
+ throw new InvalidCredentialsError();
371
376
  }
372
377
  const first = res.readBytes();
373
378
  const serverConfirm = res.readBytes();
@@ -387,7 +392,7 @@ export async function login(
387
392
  sessionKey,
388
393
  concatBytes(utf8(SERVER_CONFIRM_LABEL), transcriptHash),
389
394
  );
390
- if (!bytesEqual(expected, serverConfirm)) throw new Error('auth: server authentication failed');
395
+ if (!bytesEqual(expected, serverConfirm)) throw new ServerAuthFailedError();
391
396
 
392
397
  if (loginStatus === 3) {
393
398
  // The server authenticated itself, but a second factor is required. Surface
@@ -399,30 +404,150 @@ export async function login(
399
404
  return first; // session token
400
405
  }
401
406
 
402
- /** Thrown by {@link login} when the credential is valid but the account's email
403
- * is not confirmed and the domain requires confirmation. Catch it to prompt the
404
- * user to confirm (and offer {@link resendConfirmation}). */
405
- export class EmailNotConfirmedError extends Error {
407
+ /**
408
+ * The STABLE, typed discriminant carried by every auth error as `err.code`. Branch
409
+ * on THIS (or on the error class via `instanceof`), never on `err.message` (human
410
+ * facing, may change) nor `err.name` (a bare string, mangled by minifiers). Each
411
+ * value maps 1:1 to an {@link AuthError} subclass below.
412
+ *
413
+ * ```ts
414
+ * try { await Auth.login(email, password); }
415
+ * catch (err) {
416
+ * if (err instanceof Auth.EmailNotConfirmedError) return promptConfirm();
417
+ * if (err instanceof Auth.TwoFactorRequiredError) return promptCode(err.twoFaId);
418
+ * if (err instanceof Auth.AuthError && err.code === Auth.AuthErrorCode.InvalidCredentials)
419
+ * return setError('Incorrect email or password.');
420
+ * throw err;
421
+ * }
422
+ * ```
423
+ */
424
+ export enum AuthErrorCode {
425
+ /** Network failure or a non-2xx / malformed response from the auth endpoint. */
426
+ RequestFailed = 'request_failed',
427
+ /** A client/server protocol mismatch (bad key or signature length, expired challenge). */
428
+ ProtocolError = 'protocol_error',
429
+ /** register: the username is already registered. */
430
+ UsernameTaken = 'username_taken',
431
+ /** register: the email is already in use. */
432
+ EmailInUse = 'email_in_use',
433
+ /** register: rejected for another reason (e.g. failed proof-of-possession). */
434
+ RegistrationRejected = 'registration_rejected',
435
+ /** login: wrong username/password. Deliberately indistinguishable from "no such user". */
436
+ InvalidCredentials = 'invalid_credentials',
437
+ /** login: the credential is valid but the account's email is not confirmed. */
438
+ EmailNotConfirmed = 'email_not_confirmed',
439
+ /** login: password + server auth OK, but a second factor is required (no session yet). */
440
+ TwoFactorRequired = 'two_factor_required',
441
+ /** login/2fa: the SERVER failed to authenticate itself (mutual-auth mismatch) -> possible MITM. */
442
+ ServerAuthFailed = 'server_auth_failed',
443
+ /** 2fa: the submitted code was wrong, expired, or already used. */
444
+ TwoFactorCodeInvalid = 'two_factor_code_invalid',
445
+ /** 2fa setup: enabling/disabling the second factor failed. */
446
+ TwoFactorSetupFailed = 'two_factor_setup_failed',
447
+ /** confirm: the email-confirmation link was invalid or expired. */
448
+ ConfirmationInvalid = 'confirmation_invalid',
449
+ /** reset: the password-reset link was invalid or expired. */
450
+ PasswordResetInvalid = 'password_reset_invalid',
451
+ }
452
+
453
+ /**
454
+ * Base class for EVERY error thrown by the auth client. Always carries a typed
455
+ * {@link AuthErrorCode} as `err.code`, so `err instanceof AuthError` narrows the
456
+ * whole family and `err.code` discriminates within it. The specific subclasses
457
+ * below are sugar for the common branches; any error is still an `AuthError`.
458
+ */
459
+ export class AuthError extends Error {
460
+ /** The stable machine-readable discriminant. Prefer this over `message`/`name`. */
461
+ readonly code: AuthErrorCode;
462
+ constructor(code: AuthErrorCode, message: string) {
463
+ super(message);
464
+ this.name = 'AuthError';
465
+ this.code = code;
466
+ }
467
+ }
468
+
469
+ /** register: the username is already registered ({@link AuthErrorCode.UsernameTaken}). */
470
+ export class UsernameTakenError extends AuthError {
471
+ constructor() {
472
+ super(AuthErrorCode.UsernameTaken, 'That username is already registered.');
473
+ this.name = 'UsernameTakenError';
474
+ }
475
+ }
476
+
477
+ /** register: the email is already in use ({@link AuthErrorCode.EmailInUse}). */
478
+ export class EmailInUseError extends AuthError {
479
+ constructor() {
480
+ super(AuthErrorCode.EmailInUse, 'That email is already in use.');
481
+ this.name = 'EmailInUseError';
482
+ }
483
+ }
484
+
485
+ /** login: wrong username/password, or no such account ({@link AuthErrorCode.InvalidCredentials}). */
486
+ export class InvalidCredentialsError extends AuthError {
487
+ constructor() {
488
+ super(AuthErrorCode.InvalidCredentials, 'Incorrect username or password.');
489
+ this.name = 'InvalidCredentialsError';
490
+ }
491
+ }
492
+
493
+ /** login: the credential is valid but the account's email is not confirmed and the
494
+ * domain requires confirmation. Catch it to prompt the user to confirm (and offer
495
+ * {@link resendConfirmation}). {@link AuthErrorCode.EmailNotConfirmed}. */
496
+ export class EmailNotConfirmedError extends AuthError {
406
497
  constructor() {
407
- super('auth: email not confirmed');
498
+ super(AuthErrorCode.EmailNotConfirmed, 'Your email address is not confirmed yet.');
408
499
  this.name = 'EmailNotConfirmedError';
409
500
  }
410
501
  }
411
502
 
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 {
503
+ /** login: the password verified AND the server authenticated itself (mutual auth
504
+ * passed) but the account requires a SECOND FACTOR. No session exists yet. Catch it,
505
+ * collect the delivered code, and call {@link verifyTwoFactor} with `err.twoFaId`.
506
+ * {@link AuthErrorCode.TwoFactorRequired}. */
507
+ export class TwoFactorRequiredError extends AuthError {
417
508
  /** The opaque login-challenge id (hex) to echo to {@link verifyTwoFactor}. */
418
509
  readonly twoFaId: string;
419
510
  constructor(twoFaId: string) {
420
- super('auth: two-factor authentication required');
511
+ super(AuthErrorCode.TwoFactorRequired, 'A second factor is required to sign in.');
421
512
  this.name = 'TwoFactorRequiredError';
422
513
  this.twoFaId = twoFaId;
423
514
  }
424
515
  }
425
516
 
517
+ /** login/2fa: the SERVER failed to prove its identity (mutual-auth tag mismatch).
518
+ * Treat as hostile: a genuine server always authenticates. Possible MITM / wrong
519
+ * pinned KEM key. {@link AuthErrorCode.ServerAuthFailed}. */
520
+ export class ServerAuthFailedError extends AuthError {
521
+ constructor() {
522
+ super(AuthErrorCode.ServerAuthFailed, 'Server authentication failed (possible MITM).');
523
+ this.name = 'ServerAuthFailedError';
524
+ }
525
+ }
526
+
527
+ /** 2fa: the submitted code was wrong, expired, or already used ({@link AuthErrorCode.TwoFactorCodeInvalid}). */
528
+ export class TwoFactorCodeError extends AuthError {
529
+ constructor() {
530
+ super(AuthErrorCode.TwoFactorCodeInvalid, 'The verification code is invalid or expired.');
531
+ this.name = 'TwoFactorCodeError';
532
+ }
533
+ }
534
+
535
+ /** confirm: the email-confirmation link was invalid or expired ({@link AuthErrorCode.ConfirmationInvalid}). */
536
+ export class ConfirmationInvalidError extends AuthError {
537
+ constructor() {
538
+ super(AuthErrorCode.ConfirmationInvalid, 'This confirmation link is invalid or has expired.');
539
+ this.name = 'ConfirmationInvalidError';
540
+ }
541
+ }
542
+
543
+ /** reset: the password-reset link was invalid or expired ({@link AuthErrorCode.PasswordResetInvalid}). */
544
+ export class PasswordResetInvalidError extends AuthError {
545
+ constructor() {
546
+ super(AuthErrorCode.PasswordResetInvalid, 'This password-reset link is invalid or has expired.');
547
+ this.name = 'PasswordResetInvalidError';
548
+ }
549
+ }
550
+
426
551
  /** The 2FA method values, mirroring the server enum (append-only). */
427
552
  export const TwoFactorMethod = { None: 0, Email: 1 } as const;
428
553
 
@@ -444,7 +569,7 @@ export async function verifyTwoFactor(
444
569
  '/2fa/verify',
445
570
  new DataWriter().writeBytes(fromHex(twoFaId)).writeString(code).toBytes(),
446
571
  );
447
- if (res.readU8() !== 0) throw new Error('auth: two-factor code invalid or expired');
572
+ if (res.readU8() !== 0) throw new TwoFactorCodeError();
448
573
  return res.readBytes(); // opaque session token
449
574
  }
450
575
 
@@ -462,7 +587,8 @@ export async function setupTwoFactor(method: number, opts: AuthOptions = {}): Pr
462
587
  '/2fa/setup',
463
588
  new DataWriter().writeU8(method).toBytes(),
464
589
  );
465
- if (res.readU8() !== 0) throw new Error('auth: two-factor setup failed');
590
+ if (res.readU8() !== 0)
591
+ throw new AuthError(AuthErrorCode.TwoFactorSetupFailed, 'Enabling or disabling two-factor failed.');
466
592
  }
467
593
 
468
594
  /**
@@ -477,7 +603,8 @@ export async function confirmTwoFactorSetup(code: string, opts: AuthOptions = {}
477
603
  '/2fa/setup/verify',
478
604
  new DataWriter().writeString(code).toBytes(),
479
605
  );
480
- if (res.readU8() !== 0) throw new Error('auth: two-factor setup confirmation failed');
606
+ if (res.readU8() !== 0)
607
+ throw new AuthError(AuthErrorCode.TwoFactorSetupFailed, 'Confirming the two-factor setup failed.');
481
608
  }
482
609
 
483
610
  /**
@@ -490,7 +617,7 @@ export async function twoFactorStatus(opts: AuthOptions = {}): Promise<number> {
490
617
  method: 'GET',
491
618
  credentials: 'same-origin',
492
619
  });
493
- if (!res.ok) throw new Error('auth: request failed');
620
+ if (!res.ok) throw new AuthError(AuthErrorCode.RequestFailed, 'The auth request failed.');
494
621
  return new DataReader(new Uint8Array(await res.arrayBuffer())).readU8();
495
622
  }
496
623
 
@@ -503,7 +630,7 @@ export async function confirmEmail(token: string, opts: AuthOptions = {}): Promi
503
630
  '/confirm',
504
631
  new DataWriter().writeBytes(fromHex(token)).toBytes(),
505
632
  );
506
- if (res.readU8() !== 0) throw new Error('auth: confirmation link invalid or expired');
633
+ if (res.readU8() !== 0) throw new ConfirmationInvalidError();
507
634
  }
508
635
 
509
636
  /** Ask the server to re-send the confirmation email. Resolves regardless of
@@ -551,7 +678,7 @@ export async function resetPassword(
551
678
  '/reset/start',
552
679
  new DataWriter().writeBytes(rawToken).writeBytes(blinded).toBytes(),
553
680
  );
554
- if (start.readU8() !== 0) throw new Error('auth: reset link invalid or expired');
681
+ if (start.readU8() !== 0) throw new PasswordResetInvalidError();
555
682
  const username = start.readString();
556
683
  const kdf = decodeKdf(start);
557
684
  const evaluated = start.readBytes();
@@ -575,7 +702,8 @@ export async function resetPassword(
575
702
  } finally {
576
703
  wipe(seed);
577
704
  }
578
- if (publicKey.length !== PUBLIC_KEY_LEN) throw new Error('auth: bad public key length');
705
+ if (publicKey.length !== PUBLIC_KEY_LEN)
706
+ throw new AuthError(AuthErrorCode.ProtocolError, 'Server returned a bad public key length.');
579
707
 
580
708
  // 3. Consume the token + overwrite the stored login key.
581
709
  const finish = await postBinary(
@@ -583,7 +711,7 @@ export async function resetPassword(
583
711
  '/reset/finish',
584
712
  new DataWriter().writeBytes(rawToken).writeBytes(publicKey).writeBytes(regProof).toBytes(),
585
713
  );
586
- if (finish.readU8() !== 0) throw new Error('auth: password reset rejected');
714
+ if (finish.readU8() !== 0) throw new PasswordResetInvalidError();
587
715
  }
588
716
 
589
717
  /** The client auth surface, grouped for `Auth.register` / `Auth.login` use. */
@@ -601,4 +729,16 @@ export const Auth = {
601
729
  TwoFactorMethod,
602
730
  buildLoginMessage,
603
731
  LOGIN_CONTEXT,
732
+ // Typed error surface: branch on `Auth.AuthErrorCode` or `instanceof Auth.<X>Error`.
733
+ AuthError,
734
+ AuthErrorCode,
735
+ UsernameTakenError,
736
+ EmailInUseError,
737
+ InvalidCredentialsError,
738
+ EmailNotConfirmedError,
739
+ TwoFactorRequiredError,
740
+ ServerAuthFailedError,
741
+ TwoFactorCodeError,
742
+ ConfirmationInvalidError,
743
+ PasswordResetInvalidError,
604
744
  } as const;
@@ -16,6 +16,19 @@ export {
16
16
  login as authLogin,
17
17
  buildLoginMessage,
18
18
  LOGIN_CONTEXT,
19
+ // Typed auth errors + the discriminant enum: catch `AuthError` (or a specific
20
+ // subclass) and branch on `err.code === AuthErrorCode.*`, never on `err.name`.
21
+ AuthError,
22
+ AuthErrorCode,
23
+ UsernameTakenError,
24
+ EmailInUseError,
25
+ InvalidCredentialsError,
26
+ EmailNotConfirmedError,
27
+ TwoFactorRequiredError,
28
+ ServerAuthFailedError,
29
+ TwoFactorCodeError,
30
+ ConfirmationInvalidError,
31
+ PasswordResetInvalidError,
19
32
  } from './auth.js';
20
33
  export type { KdfParams, AuthOptions } from './auth.js';
21
34
  export { Link } from './navigation/Link.js';
@@ -24,7 +24,13 @@ 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, TwoFactorRequiredError } from '../src/client/auth.js';
27
+ import {
28
+ Auth,
29
+ AuthErrorCode,
30
+ EmailInUseError,
31
+ EmailNotConfirmedError,
32
+ TwoFactorRequiredError,
33
+ } from '../src/client/auth.js';
28
34
  import { DataReader, DataWriter } from '../src/io/codec.js';
29
35
 
30
36
  const EXAMPLE_WASM = path.resolve(
@@ -291,9 +297,13 @@ describe.skipIf(!haveWasm)('built-in auth: email verification + password reset (
291
297
  'duplicate email is rejected at registration (distinct "email already in use")',
292
298
  async () => {
293
299
  await Auth.register('carol', 'carol-pw-strong', 'dupe@x.com');
294
- await expect(Auth.register('dave', 'dave-pw-strong', 'dupe@x.com')).rejects.toThrow(
295
- /email already in use/,
300
+ // Typed error: a distinct EmailInUseError carrying the stable code, so a UI can
301
+ // branch reliably (never on the message/name string).
302
+ const err = await Auth.register('dave', 'dave-pw-strong', 'dupe@x.com').catch(
303
+ (e: unknown) => e,
296
304
  );
305
+ expect(err).toBeInstanceOf(EmailInUseError);
306
+ expect((err as EmailInUseError).code).toBe(AuthErrorCode.EmailInUse);
297
307
  },
298
308
  60_000,
299
309
  );