@bymax-one/nest-auth 1.5.7 → 1.5.9

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.
@@ -318,6 +318,16 @@ function validateApiKeyTuning(group) {
318
318
  }
319
319
  __name(validateApiKeyTuning, "validateApiKeyTuning");
320
320
 
321
+ // src/server/config/describe-received.ts
322
+ function describeReceived(value) {
323
+ if (typeof value === "number") return String(value);
324
+ if (value === null || value === void 0) return String(value);
325
+ if (Array.isArray(value)) return "an array";
326
+ const kind = typeof value;
327
+ return `${kind === "object" ? "an" : "a"} ${kind}`;
328
+ }
329
+ __name(describeReceived, "describeReceived");
330
+
321
331
  // src/server/config/duration.ts
322
332
  var DURATION_UNIT_SECONDS = {
323
333
  ms: 1e-3,
@@ -362,6 +372,426 @@ function durationToSeconds(value) {
362
372
  return amount * seconds;
363
373
  }
364
374
  __name(durationToSeconds, "durationToSeconds");
375
+ var TOTP_STEP_SECONDS = 30;
376
+ var TOTP_DIGITS = 6;
377
+ var BASE32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
378
+ var MIN_SECRET_BYTES = 20;
379
+ function toBase32(input) {
380
+ let bits = 0;
381
+ let value = 0;
382
+ let output = "";
383
+ for (let i = 0; i < input.length; i++) {
384
+ value = value << 8 | input.readUInt8(i);
385
+ bits += 8;
386
+ while (bits >= 5) {
387
+ bits -= 5;
388
+ output += BASE32_ALPHABET[value >>> bits & 31];
389
+ }
390
+ }
391
+ if (bits > 0) {
392
+ output += BASE32_ALPHABET[value << 5 - bits & 31];
393
+ }
394
+ return output;
395
+ }
396
+ __name(toBase32, "toBase32");
397
+ function fromBase32(input) {
398
+ const normalized = input.toUpperCase().replace(/[\s=-]/g, "");
399
+ let bits = 0;
400
+ let value = 0;
401
+ const output = [];
402
+ for (const char of normalized) {
403
+ const idx = BASE32_ALPHABET.indexOf(char);
404
+ if (idx === -1) {
405
+ throw new Error(`[totp] Invalid Base32 character: ${JSON.stringify(char)}`);
406
+ }
407
+ value = value << 5 | idx;
408
+ bits += 5;
409
+ if (bits >= 8) {
410
+ bits -= 8;
411
+ output.push(value >>> bits & 255);
412
+ }
413
+ }
414
+ return Buffer.from(output);
415
+ }
416
+ __name(fromBase32, "fromBase32");
417
+ function generateTotpSecret() {
418
+ const raw = randomBytes(MIN_SECRET_BYTES);
419
+ return {
420
+ raw,
421
+ base32: toBase32(raw)
422
+ };
423
+ }
424
+ __name(generateTotpSecret, "generateTotpSecret");
425
+ function buildTotpUri(secretBase32, accountEmail, issuer) {
426
+ if (!secretBase32 || secretBase32.length < 32) {
427
+ throw new Error("[totp] secretBase32 must encode at least 20 bytes (minimum 32 base32 characters)");
428
+ }
429
+ if (!issuer) {
430
+ throw new Error("[totp] issuer must not be empty");
431
+ }
432
+ if (!accountEmail) {
433
+ throw new Error("[totp] accountEmail must not be empty");
434
+ }
435
+ const label = `${encodeURIComponent(issuer)}:${encodeURIComponent(accountEmail)}`;
436
+ const qs = [
437
+ `secret=${encodeURIComponent(secretBase32)}`,
438
+ `issuer=${encodeURIComponent(issuer)}`,
439
+ `algorithm=SHA1`,
440
+ `digits=${String(TOTP_DIGITS)}`,
441
+ `period=${String(TOTP_STEP_SECONDS)}`
442
+ ].join("&");
443
+ return `otpauth://totp/${label}?${qs}`;
444
+ }
445
+ __name(buildTotpUri, "buildTotpUri");
446
+ function generateHotp(secretBase32, counter) {
447
+ const key = fromBase32(secretBase32);
448
+ if (key.length < MIN_SECRET_BYTES) {
449
+ throw new Error(`[totp] Secret too short: ${key.length} bytes (minimum ${MIN_SECRET_BYTES}). Generate secrets with generateTotpSecret().`);
450
+ }
451
+ if (!Number.isInteger(counter) || counter < 0 || counter > Number.MAX_SAFE_INTEGER) {
452
+ throw new Error(`[totp] Counter must be a non-negative safe integer (got ${counter}).`);
453
+ }
454
+ const counterBuffer = Buffer.allocUnsafe(8);
455
+ const hi = Math.floor(counter / 4294967296);
456
+ const lo = counter >>> 0;
457
+ counterBuffer.writeUInt32BE(hi, 0);
458
+ counterBuffer.writeUInt32BE(lo, 4);
459
+ const hmac = createHmac("sha1", key).update(counterBuffer).digest();
460
+ const offset = hmac.readUInt8(hmac.length - 1) & 15;
461
+ const truncated = (hmac.readUInt8(offset) & 127) << 24 | (hmac.readUInt8(offset + 1) & 255) << 16 | (hmac.readUInt8(offset + 2) & 255) << 8 | hmac.readUInt8(offset + 3);
462
+ const mod = 10 ** TOTP_DIGITS;
463
+ return String(truncated % mod).padStart(TOTP_DIGITS, "0");
464
+ }
465
+ __name(generateHotp, "generateHotp");
466
+ var MAX_VERIFY_WINDOW = 2;
467
+ function verifyTotp(secretBase32, code, window = 1) {
468
+ if (!/^\d{6}$/.test(code)) return false;
469
+ const currentStep = Math.floor(Date.now() / 1e3 / TOTP_STEP_SECONDS);
470
+ const effective = Math.min(Math.max(window, 0), MAX_VERIFY_WINDOW);
471
+ for (let delta = -effective; delta <= effective; delta++) {
472
+ const expected = generateHotp(secretBase32, currentStep + delta);
473
+ const expectedBuf = Buffer.from(expected, "utf8");
474
+ const codeBuf = Buffer.from(code, "utf8");
475
+ if (expectedBuf.length === codeBuf.length && timingSafeEqual(expectedBuf, codeBuf)) {
476
+ return true;
477
+ }
478
+ }
479
+ return false;
480
+ }
481
+ __name(verifyTotp, "verifyTotp");
482
+
483
+ // src/server/config/numeric-options.ts
484
+ var MAX_USER_STATUS_CACHE_TTL_SECONDS = 3600;
485
+ var MAX_REDIS_TTL_SECONDS = 31536e4;
486
+ var MAX_COOKIE_MAX_AGE_MS = MAX_REDIS_TTL_SECONDS * 1e3;
487
+ var MAX_SESSIONS_PER_USER = 1e3;
488
+ var MAX_LIFETIME_DAYS = 3650;
489
+ var MIN_ABSOLUTE_LIFETIME_DAYS = 1 / 24;
490
+ var MAX_SCRYPT_PARALLELIZATION = 16;
491
+ var MAX_BRUTE_FORCE_WINDOW_SECONDS = 604800;
492
+ function assertWholeNumber(path, value, min, max, why) {
493
+ if (value === void 0) return;
494
+ if (Number.isSafeInteger(value) && value >= min && value <= max) return;
495
+ throw new Error(`[BymaxAuthModule] ${path} must be a whole number between ${min} and ${max} inclusive (received ${describeReceived(value)}). ${why}`);
496
+ }
497
+ __name(assertWholeNumber, "assertWholeNumber");
498
+ function validateWholeNumberOptions(userOptions) {
499
+ assertWholeNumber("jwt.accessCookieMaxAgeMs", userOptions.jwt.accessCookieMaxAgeMs, 1e3, MAX_COOKIE_MAX_AGE_MS, "It is the cookie Max-Age in milliseconds, sent in whole seconds: under 1000 it becomes Max-Age=0, which deletes the cookie, and NaN is ignored by the browser, so the session would end with the tab.");
500
+ assertWholeNumber("sessions.defaultMaxSessions", userOptions.sessions?.defaultMaxSessions, 1, MAX_SESSIONS_PER_USER, "It caps concurrent sessions per user, counted in whole sessions: NaN evicts no session, zero or a negative value evicts them all, a fraction cannot be counted, and a value above 1000 is no cap.");
501
+ assertWholeNumber("bruteForce.windowSeconds", userOptions.bruteForce?.windowSeconds, 1, MAX_BRUTE_FORCE_WINDOW_SECONDS, "It is the Redis expiry of each failure counter: Redis deletes a key on `EXPIRE key 0`, so a zero or negative window destroys each counter as it is created and the lockout never engages, silently; a window past a week locks an account for a month over a few typos.");
502
+ assertWholeNumber("userStatusCacheTtlSeconds", userOptions.userStatusCacheTtlSeconds, 1, MAX_USER_STATUS_CACHE_TTL_SECONDS, "It is how long a suspended account keeps passing the dashboard guards, so it has a ceiling.");
503
+ }
504
+ __name(validateWholeNumberOptions, "validateWholeNumberOptions");
505
+ function validateRedisTtls(userOptions) {
506
+ const ttls = [
507
+ [
508
+ "passwordReset.tokenTtlSeconds",
509
+ userOptions.passwordReset?.tokenTtlSeconds
510
+ ],
511
+ [
512
+ "passwordReset.otpTtlSeconds",
513
+ userOptions.passwordReset?.otpTtlSeconds
514
+ ],
515
+ [
516
+ "emailVerification.otpTtlSeconds",
517
+ userOptions.emailVerification?.otpTtlSeconds
518
+ ],
519
+ [
520
+ "emailChange.tokenTtlSeconds",
521
+ userOptions.emailChange?.tokenTtlSeconds
522
+ ],
523
+ [
524
+ "invitations.tokenTtlSeconds",
525
+ userOptions.invitations?.tokenTtlSeconds
526
+ ]
527
+ ];
528
+ for (const [path, value] of ttls) {
529
+ assertWholeNumber(path, value, 1, MAX_REDIS_TTL_SECONDS, "It is a Redis expiry in seconds: zero or a negative deletes the record as it is written, and NaN, a fraction, Infinity or a value past what Redis can hold is refused by Redis on every request.");
530
+ }
531
+ }
532
+ __name(validateRedisTtls, "validateRedisTtls");
533
+ function validateAbsoluteSessionLifetime(jwt) {
534
+ const days = jwt.absoluteSessionLifetimeDays;
535
+ if (days === void 0 || days === 0 || Number.isFinite(days) && days >= MIN_ABSOLUTE_LIFETIME_DAYS && days <= MAX_LIFETIME_DAYS) {
536
+ return;
537
+ }
538
+ throw new Error(`[BymaxAuthModule] jwt.absoluteSessionLifetimeDays must be 0 or between ${MIN_ABSOLUTE_LIFETIME_DAYS.toFixed(4)} and ${MAX_LIFETIME_DAYS} days (received ${describeReceived(days)}). Only 0 switches the cap off; NaN, a negative or a value so large that its length in milliseconds overflows would skip it without being asked to, and a value under an hour ends every session at its first rotation after that age, minutes after login. Set 0 to accept unbounded sessions deliberately.`);
539
+ }
540
+ __name(validateAbsoluteSessionLifetime, "validateAbsoluteSessionLifetime");
541
+ function validatePasswordResetOtpLength(passwordReset) {
542
+ const otpLength = passwordReset?.otpLength;
543
+ if (otpLength === void 0) return;
544
+ if (!Number.isInteger(otpLength) || otpLength < 4 || otpLength > 8) {
545
+ throw new Error(`[BymaxAuthModule] passwordReset.otpLength must be between 4 and 8 inclusive (received ${describeReceived(otpLength)}). Values below 4 are too easily guessable; values above 8 are not required for security and degrade user experience. The value must also be a whole number: a comparison with NaN is false both ways, so a bound written as a range alone lets it through.`);
546
+ }
547
+ }
548
+ __name(validatePasswordResetOtpLength, "validatePasswordResetOtpLength");
549
+ function validateMfaVerificationParameters(mfa) {
550
+ const totpWindow = mfa?.totpWindow;
551
+ if (totpWindow !== void 0 && (!Number.isInteger(totpWindow) || totpWindow < 0 || totpWindow > MAX_VERIFY_WINDOW)) {
552
+ throw new Error(`[BymaxAuthModule] mfa.totpWindow must be between 0 and ${MAX_VERIFY_WINDOW} inclusive (received ${describeReceived(totpWindow)}). The window is counted in 30-second steps on either side of the current time, so ${typeof totpWindow === "number" ? 2 * totpWindow + 1 : "2N + 1"} codes would be valid at once. RFC 6238 \xA75.2 recommends at most one step of tolerance; the default of 1 accepts three codes. The bound matches the drift window the verifier actually applies, so a configured value means what it says and is never silently clamped. It must be a whole number.`);
553
+ }
554
+ const recoveryCodeCount = mfa?.recoveryCodeCount;
555
+ if (recoveryCodeCount !== void 0 && (!Number.isInteger(recoveryCodeCount) || recoveryCodeCount < 1 || recoveryCodeCount > 50)) {
556
+ throw new Error(`[BymaxAuthModule] mfa.recoveryCodeCount must be between 1 and 50 inclusive (received ${describeReceived(recoveryCodeCount)}). Zero enrols an account with no way back if the authenticator is lost. The count must be a whole number.`);
557
+ }
558
+ }
559
+ __name(validateMfaVerificationParameters, "validateMfaVerificationParameters");
560
+ var MAX_REFRESH_GRACE_WINDOW_SECONDS = 300;
561
+ function validateRefreshGraceWindow(jwt) {
562
+ const graceSeconds = jwt.refreshGraceWindowSeconds ?? DEFAULT_OPTIONS.jwt.refreshGraceWindowSeconds;
563
+ const refreshExpiresInDays = jwt.refreshExpiresInDays ?? DEFAULT_OPTIONS.jwt.refreshExpiresInDays;
564
+ const refreshLifetimeSeconds = typeof refreshExpiresInDays === "number" ? refreshExpiresInDays * 86400 : Number.NaN;
565
+ const isGraceNumber = typeof graceSeconds === "number";
566
+ if (!Number.isFinite(refreshExpiresInDays) || refreshExpiresInDays <= 0 || refreshExpiresInDays > MAX_LIFETIME_DAYS || !Number.isInteger(refreshLifetimeSeconds)) {
567
+ throw new Error(`[BymaxAuthModule] jwt.refreshExpiresInDays must be a positive finite number. It received ${describeReceived(refreshExpiresInDays)}. Zero, negative, NaN, and Infinity are all rejected \u2014 any of these would produce an invalid Redis TTL and cause all token rotations to fail at runtime. It is at most ${MAX_LIFETIME_DAYS} days, and days \xD7 86400 must be a whole number of seconds, because Redis takes an integer expiry: 1.5 and 0.25 are, 1.1 is not.`);
568
+ }
569
+ if (isGraceNumber && graceSeconds >= refreshLifetimeSeconds) {
570
+ throw new Error(`[BymaxAuthModule] jwt.refreshGraceWindowSeconds (${graceSeconds} s) must be less than the refresh token lifetime jwt.refreshExpiresInDays * 86400 (${refreshLifetimeSeconds} s). A grace window equal to or longer than the token lifetime would allow grace pointers to outlive the refresh session they protect.`);
571
+ }
572
+ if (!isGraceNumber || !Number.isInteger(graceSeconds) || graceSeconds < 0 || graceSeconds > MAX_REFRESH_GRACE_WINDOW_SECONDS) {
573
+ throw new Error(`[BymaxAuthModule] jwt.refreshGraceWindowSeconds must be between 0 and ${MAX_REFRESH_GRACE_WINDOW_SECONDS} inclusive (received ${describeReceived(graceSeconds)}). The window is how long an already-consumed refresh token recovers a session, so it is exactly the replay window for a stolen one. It covers a client that rotated but never received the response \u2014 a retry, not a policy. 0 disables grace recovery entirely. The value must be a whole number: Redis takes an integer expiry, so a fraction or NaN would fail every rotation.`);
574
+ }
575
+ }
576
+ __name(validateRefreshGraceWindow, "validateRefreshGraceWindow");
577
+ function validateScryptParallelizationCeiling(password) {
578
+ const parallelization = password?.parallelization;
579
+ if (parallelization === void 0 || !Number.isFinite(parallelization) || parallelization <= MAX_SCRYPT_PARALLELIZATION) {
580
+ return;
581
+ }
582
+ throw new Error(`[BymaxAuthModule] password.parallelization must be at most ${MAX_SCRYPT_PARALLELIZATION} (received ${describeReceived(parallelization)}). scrypt's CPU cost grows linearly with it and an unauthenticated login derives a hash even for an address that does not exist.`);
583
+ }
584
+ __name(validateScryptParallelizationCeiling, "validateScryptParallelizationCeiling");
585
+ function validateNumericOptions(userOptions) {
586
+ validatePasswordResetOtpLength(userOptions.passwordReset);
587
+ validateMfaVerificationParameters(userOptions.mfa);
588
+ validateRefreshGraceWindow(userOptions.jwt);
589
+ validateAbsoluteSessionLifetime(userOptions.jwt);
590
+ validateScryptParallelizationCeiling(userOptions.password);
591
+ validateWholeNumberOptions(userOptions);
592
+ validateRedisTtls(userOptions);
593
+ }
594
+ __name(validateNumericOptions, "validateNumericOptions");
595
+
596
+ // src/server/config/shape-checks.ts
597
+ function assertObject(label, value) {
598
+ if (Object(value) === value) return;
599
+ throw new Error(`[BymaxAuthModule] ${label} must be an object (received ${describeReceived(value)}).`);
600
+ }
601
+ __name(assertObject, "assertObject");
602
+ function assertArray(label, value) {
603
+ if (Array.isArray(value)) return;
604
+ throw new Error(`[BymaxAuthModule] ${label} must be an array (received ${describeReceived(value)}).`);
605
+ }
606
+ __name(assertArray, "assertArray");
607
+
608
+ // src/server/config/unset-options.ts
609
+ var TOP_KEYS = {
610
+ identifierKey: true,
611
+ jwt: true,
612
+ password: true,
613
+ tokenDelivery: true,
614
+ environment: true,
615
+ secureCookies: true,
616
+ cookies: true,
617
+ rateLimit: true,
618
+ mfa: true,
619
+ sessions: true,
620
+ bruteForce: true,
621
+ passwordReset: true,
622
+ emailVerification: true,
623
+ platform: true,
624
+ emailChange: true,
625
+ invitations: true,
626
+ apiKeys: true,
627
+ roles: true,
628
+ blockedStatuses: true,
629
+ redisNamespace: true,
630
+ oauth: true,
631
+ workspaces: true,
632
+ registration: true,
633
+ routePrefix: true,
634
+ tenantIdResolver: true,
635
+ enforceTenantBinding: true,
636
+ isTrustedProxy: true,
637
+ controllers: true,
638
+ userStatusCacheTtlSeconds: true
639
+ };
640
+ var GROUP_KEYS = {
641
+ jwt: {
642
+ secret: true,
643
+ previousSecrets: true,
644
+ accessExpiresIn: true,
645
+ accessCookieMaxAgeMs: true,
646
+ refreshExpiresInDays: true,
647
+ absoluteSessionLifetimeDays: true,
648
+ algorithm: true,
649
+ issuer: true,
650
+ audience: true,
651
+ refreshGraceWindowSeconds: true
652
+ },
653
+ password: {
654
+ costFactor: true,
655
+ minLength: true,
656
+ blockSize: true,
657
+ parallelization: true,
658
+ blocklist: true
659
+ },
660
+ cookies: {
661
+ accessTokenName: true,
662
+ refreshTokenName: true,
663
+ sessionSignalName: true,
664
+ refreshCookiePath: true,
665
+ mfaTempCookiePath: true,
666
+ resolveDomains: true,
667
+ sameSite: true,
668
+ trustedOrigins: true
669
+ },
670
+ sessions: {
671
+ enabled: true,
672
+ defaultMaxSessions: true,
673
+ maxSessionsResolver: true
674
+ },
675
+ bruteForce: {
676
+ maxAttempts: true,
677
+ windowSeconds: true
678
+ },
679
+ passwordReset: {
680
+ method: true,
681
+ tokenTtlSeconds: true,
682
+ otpTtlSeconds: true,
683
+ otpLength: true
684
+ },
685
+ emailVerification: {
686
+ required: true,
687
+ otpTtlSeconds: true
688
+ },
689
+ platform: {
690
+ enabled: true
691
+ },
692
+ invitations: {
693
+ enabled: true,
694
+ tokenTtlSeconds: true
695
+ },
696
+ emailChange: {
697
+ tokenTtlSeconds: true
698
+ },
699
+ controllers: {
700
+ auth: true,
701
+ mfa: true,
702
+ passwordReset: true,
703
+ sessions: true,
704
+ platform: true,
705
+ oauth: true,
706
+ invitations: true,
707
+ emailChange: true,
708
+ workspaces: true,
709
+ workspaceInvitations: true
710
+ },
711
+ rateLimit: {
712
+ enabled: true,
713
+ clientIpSource: true
714
+ },
715
+ mfa: {
716
+ encryptionKey: true,
717
+ previousEncryptionKeys: true,
718
+ issuer: true,
719
+ recoveryCodeCount: true,
720
+ totpWindow: true
721
+ },
722
+ apiKeys: {
723
+ enabled: true,
724
+ pepper: true,
725
+ scopes: true,
726
+ header: true,
727
+ prefix: true,
728
+ lastUsedFlushSeconds: true,
729
+ auditMode: true
730
+ },
731
+ workspaces: {
732
+ enabled: true,
733
+ roles: true,
734
+ permissions: true,
735
+ allowCreate: true,
736
+ maxWorkspacesPerUser: true,
737
+ invitationTtlSeconds: true,
738
+ maxPendingInvitationsPerWorkspace: true,
739
+ membershipCacheTtlSeconds: true,
740
+ deletionGraceDays: true,
741
+ accessDeniedEvents: true,
742
+ resolveRequestWorkspace: true,
743
+ resolveWsWorkspace: true
744
+ }
745
+ };
746
+ var WORKSPACE_SUBGROUP_KEYS = {
747
+ accessDeniedEvents: [
748
+ "max",
749
+ "windowSeconds"
750
+ ]
751
+ };
752
+ function isObjectGroup(value) {
753
+ return Object(value) === value && typeof value !== "function" && !Array.isArray(value);
754
+ }
755
+ __name(isObjectGroup, "isObjectGroup");
756
+ function readSetKeys(group, keys) {
757
+ const out = {};
758
+ for (const key of /* @__PURE__ */ new Set([
759
+ ...keys,
760
+ ...Object.keys(group)
761
+ ])) {
762
+ const entry = Reflect.get(group, key);
763
+ if (entry !== void 0 && entry !== null) out[key] = entry;
764
+ }
765
+ return out;
766
+ }
767
+ __name(readSetKeys, "readSetKeys");
768
+ function dropUnsetKeys(value) {
769
+ const copy = {
770
+ ...value
771
+ };
772
+ for (const [key, entry] of Object.entries(copy)) {
773
+ if (entry === void 0 || entry === null) Reflect.deleteProperty(copy, key);
774
+ }
775
+ return copy;
776
+ }
777
+ __name(dropUnsetKeys, "dropUnsetKeys");
778
+ function dropUnset(options) {
779
+ const copy = readSetKeys(options, Object.keys(TOP_KEYS));
780
+ for (const [name, keys] of Object.entries(GROUP_KEYS)) {
781
+ const entry = copy[name];
782
+ if (!isObjectGroup(entry)) continue;
783
+ const group = readSetKeys(entry, Object.keys(keys));
784
+ if (name === "workspaces") {
785
+ for (const [sub, subKeys] of Object.entries(WORKSPACE_SUBGROUP_KEYS)) {
786
+ const inner = group[sub];
787
+ if (isObjectGroup(inner)) group[sub] = readSetKeys(inner, subKeys);
788
+ }
789
+ }
790
+ copy[name] = group;
791
+ }
792
+ return Object.assign({}, copy);
793
+ }
794
+ __name(dropUnset, "dropUnset");
365
795
 
366
796
  // src/server/constants/workspace-roles.ts
367
797
  var ANY_WORKSPACE_MEMBER = /* @__PURE__ */ Symbol("ANY_WORKSPACE_MEMBER");
@@ -516,6 +946,7 @@ __name(validateWorkspaceRoles, "validateWorkspaceRoles");
516
946
  function validateWorkspacePermissions(permissions, roles) {
517
947
  for (const [action, list] of Object.entries(permissions ?? {})) {
518
948
  if (list === void 0) continue;
949
+ assertArray(`workspaces.permissions.${action}`, list);
519
950
  for (const role of list) {
520
951
  const known = roles.has(role);
521
952
  if (!known && !(action === "viewMembers" && role === ANY_WORKSPACE_MEMBER)) {
@@ -666,113 +1097,6 @@ __name(assertWorkspaceProviders, "assertWorkspaceProviders");
666
1097
 
667
1098
  // src/server/constants/token-epoch.ts
668
1099
  var TOKEN_EPOCH_RETENTION_SECONDS = 30 * 24 * 60 * 60;
669
- var TOTP_STEP_SECONDS = 30;
670
- var TOTP_DIGITS = 6;
671
- var BASE32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
672
- var MIN_SECRET_BYTES = 20;
673
- function toBase32(input) {
674
- let bits = 0;
675
- let value = 0;
676
- let output = "";
677
- for (let i = 0; i < input.length; i++) {
678
- value = value << 8 | input.readUInt8(i);
679
- bits += 8;
680
- while (bits >= 5) {
681
- bits -= 5;
682
- output += BASE32_ALPHABET[value >>> bits & 31];
683
- }
684
- }
685
- if (bits > 0) {
686
- output += BASE32_ALPHABET[value << 5 - bits & 31];
687
- }
688
- return output;
689
- }
690
- __name(toBase32, "toBase32");
691
- function fromBase32(input) {
692
- const normalized = input.toUpperCase().replace(/[\s=-]/g, "");
693
- let bits = 0;
694
- let value = 0;
695
- const output = [];
696
- for (const char of normalized) {
697
- const idx = BASE32_ALPHABET.indexOf(char);
698
- if (idx === -1) {
699
- throw new Error(`[totp] Invalid Base32 character: ${JSON.stringify(char)}`);
700
- }
701
- value = value << 5 | idx;
702
- bits += 5;
703
- if (bits >= 8) {
704
- bits -= 8;
705
- output.push(value >>> bits & 255);
706
- }
707
- }
708
- return Buffer.from(output);
709
- }
710
- __name(fromBase32, "fromBase32");
711
- function generateTotpSecret() {
712
- const raw = randomBytes(MIN_SECRET_BYTES);
713
- return {
714
- raw,
715
- base32: toBase32(raw)
716
- };
717
- }
718
- __name(generateTotpSecret, "generateTotpSecret");
719
- function buildTotpUri(secretBase32, accountEmail, issuer) {
720
- if (!secretBase32 || secretBase32.length < 32) {
721
- throw new Error("[totp] secretBase32 must encode at least 20 bytes (minimum 32 base32 characters)");
722
- }
723
- if (!issuer) {
724
- throw new Error("[totp] issuer must not be empty");
725
- }
726
- if (!accountEmail) {
727
- throw new Error("[totp] accountEmail must not be empty");
728
- }
729
- const label = `${encodeURIComponent(issuer)}:${encodeURIComponent(accountEmail)}`;
730
- const qs = [
731
- `secret=${encodeURIComponent(secretBase32)}`,
732
- `issuer=${encodeURIComponent(issuer)}`,
733
- `algorithm=SHA1`,
734
- `digits=${String(TOTP_DIGITS)}`,
735
- `period=${String(TOTP_STEP_SECONDS)}`
736
- ].join("&");
737
- return `otpauth://totp/${label}?${qs}`;
738
- }
739
- __name(buildTotpUri, "buildTotpUri");
740
- function generateHotp(secretBase32, counter) {
741
- const key = fromBase32(secretBase32);
742
- if (key.length < MIN_SECRET_BYTES) {
743
- throw new Error(`[totp] Secret too short: ${key.length} bytes (minimum ${MIN_SECRET_BYTES}). Generate secrets with generateTotpSecret().`);
744
- }
745
- if (!Number.isInteger(counter) || counter < 0 || counter > Number.MAX_SAFE_INTEGER) {
746
- throw new Error(`[totp] Counter must be a non-negative safe integer (got ${counter}).`);
747
- }
748
- const counterBuffer = Buffer.allocUnsafe(8);
749
- const hi = Math.floor(counter / 4294967296);
750
- const lo = counter >>> 0;
751
- counterBuffer.writeUInt32BE(hi, 0);
752
- counterBuffer.writeUInt32BE(lo, 4);
753
- const hmac = createHmac("sha1", key).update(counterBuffer).digest();
754
- const offset = hmac.readUInt8(hmac.length - 1) & 15;
755
- const truncated = (hmac.readUInt8(offset) & 127) << 24 | (hmac.readUInt8(offset + 1) & 255) << 16 | (hmac.readUInt8(offset + 2) & 255) << 8 | hmac.readUInt8(offset + 3);
756
- const mod = 10 ** TOTP_DIGITS;
757
- return String(truncated % mod).padStart(TOTP_DIGITS, "0");
758
- }
759
- __name(generateHotp, "generateHotp");
760
- var MAX_VERIFY_WINDOW = 2;
761
- function verifyTotp(secretBase32, code, window = 1) {
762
- if (!/^\d{6}$/.test(code)) return false;
763
- const currentStep = Math.floor(Date.now() / 1e3 / TOTP_STEP_SECONDS);
764
- const effective = Math.min(Math.max(window, 0), MAX_VERIFY_WINDOW);
765
- for (let delta = -effective; delta <= effective; delta++) {
766
- const expected = generateHotp(secretBase32, currentStep + delta);
767
- const expectedBuf = Buffer.from(expected, "utf8");
768
- const codeBuf = Buffer.from(code, "utf8");
769
- if (expectedBuf.length === codeBuf.length && timingSafeEqual(expectedBuf, codeBuf)) {
770
- return true;
771
- }
772
- }
773
- return false;
774
- }
775
- __name(verifyTotp, "verifyTotp");
776
1100
 
777
1101
  // src/server/config/resolved-options.ts
778
1102
  var HMAC_KEY_DERIVATION_LABEL = "bymax-auth:hmac-key:v1";
@@ -784,17 +1108,17 @@ function isProductionDeployment(userOptions) {
784
1108
  return (userOptions.environment ?? "production") === "production";
785
1109
  }
786
1110
  __name(isProductionDeployment, "isProductionDeployment");
787
- function resolveOptions(userOptions) {
1111
+ function resolveOptions(given) {
1112
+ const userOptions = dropUnset(given);
788
1113
  validateJwt(userOptions.jwt);
789
1114
  validateIdentifierKey(userOptions.identifierKey);
790
1115
  validateMfaEncryptionKey(userOptions.mfa);
791
1116
  validateRolesHierarchy(userOptions.roles);
792
1117
  validatePlatformAdmin(userOptions.platform, userOptions.roles);
793
- validatePasswordResetOtpLength(userOptions.passwordReset);
1118
+ validateNumericOptions(userOptions);
794
1119
  validatePasswordMinLength(userOptions.password);
795
1120
  validatePasswordCostFactor(userOptions.password);
796
1121
  validatePasswordMemoryParameters(userOptions.password);
797
- validateMfaVerificationParameters(userOptions.mfa);
798
1122
  validateBruteForce(userOptions.bruteForce);
799
1123
  validateOAuthProviders(userOptions.oauth, isProductionDeployment(userOptions));
800
1124
  validateClientIpSource(userOptions.rateLimit);
@@ -810,7 +1134,6 @@ function resolveOptions(userOptions) {
810
1134
  validateProductionCookiesAreSecure(userOptions);
811
1135
  validateCookiePrefixes(userOptions);
812
1136
  validateTrustedOrigins(userOptions);
813
- validateRefreshGraceWindow(userOptions.jwt);
814
1137
  validateAccessLifetimeAgainstEpochRetention(userOptions.jwt);
815
1138
  const { mfa: _mfa, identifierKey: _identifierKey, workspaces: _workspaces, ...userOptionsWithoutMfa } = userOptions;
816
1139
  const resolved = {
@@ -884,16 +1207,14 @@ function resolveOptions(userOptions) {
884
1207
  userStatusCacheTtlSeconds: userOptions.userStatusCacheTtlSeconds ?? DEFAULT_OPTIONS.userStatusCacheTtlSeconds,
885
1208
  // Evaluated once at startup — not re-evaluated per request.
886
1209
  //
887
- // `clientIpSource` has no default and `validateClientIpSource` has already refused a
888
- // deployment that left it unset with limiting on. The fallback here is reached only when
889
- // limiting is OFF, where the value is never read; `'peer'` is the inert choice because it
890
- // consults no request header at all.
1210
+ // `clientIpSource` has no default and `validateClientIpSource` refused a deployment that left it
1211
+ // unset with limiting on. The fallback is reached only when limiting is OFF, where the value is
1212
+ // never read; `'peer'` is the inert choice because it consults no request header at all.
891
1213
  rateLimit: {
892
1214
  ...DEFAULT_OPTIONS.rateLimit,
893
1215
  ...userOptions.rateLimit,
894
- // Stryker disable next-line OptionalChaining: unreachable — `validateClientIpSource` has
895
- // already run, and it only returns without throwing when `rateLimit` is an object (either
896
- // naming a source or disabling limiting), so `rateLimit` is never undefined here
1216
+ // Stryker disable next-line OptionalChaining: unreachable — `validateClientIpSource` has run, and
1217
+ // it returns only when `rateLimit` is an object (naming a source or disabling limiting)
897
1218
  clientIpSource: userOptions.rateLimit?.clientIpSource ?? "peer"
898
1219
  },
899
1220
  environment: userOptions.environment ?? "production",
@@ -958,7 +1279,7 @@ function validateClientIpSource(rateLimit) {
958
1279
  if (rateLimit?.clientIpSource === "peer" || rateLimit?.clientIpSource === "trusted-proxy") {
959
1280
  return;
960
1281
  }
961
- throw new Error(`[BymaxAuthModule] rateLimit.clientIpSource must be 'peer' or 'trusted-proxy' when rate limiting is enabled (current: ${JSON.stringify(rateLimit?.clientIpSource)}). Set 'peer' when the application is directly exposed (the limit keys on the socket address), or 'trusted-proxy' when it runs behind a proxy and 'trust proxy' is configured for the real hop count (the limit keys on the forwarded client address). There is no default: 'peer' behind a proxy puts every client in ONE bucket, so one caller can rate-limit your whole user base, and 'trusted-proxy' without a proxy lets the caller choose their own key. Both look like a working limiter. Pass rateLimit.enabled: false if the limits are enforced at the edge instead.`);
1282
+ throw new Error(`[BymaxAuthModule] rateLimit.clientIpSource must be 'peer' or 'trusted-proxy' when rate limiting is enabled (received ${describeReceived(rateLimit?.clientIpSource)}). Set 'peer' when the application is directly exposed (the limit keys on the socket address), or 'trusted-proxy' when it runs behind a proxy and 'trust proxy' is configured for the real hop count (the limit keys on the forwarded client address). There is no default: 'peer' behind a proxy puts every client in ONE bucket, so one caller can rate-limit your whole user base, and 'trusted-proxy' without a proxy lets the caller choose their own key. Both look like a working limiter. Pass rateLimit.enabled: false if the limits are enforced at the edge instead.`);
962
1283
  }
963
1284
  __name(validateClientIpSource, "validateClientIpSource");
964
1285
  function validateTenantBinding(userOptions) {
@@ -1065,6 +1386,7 @@ function validateRolesHierarchy(roles) {
1065
1386
  }
1066
1387
  const allRoles = new Set(Object.keys(roles.hierarchy));
1067
1388
  for (const [role, children] of Object.entries(roles.hierarchy)) {
1389
+ assertArray(`roles.hierarchy['${role}']`, children);
1068
1390
  for (const child of children) {
1069
1391
  if (!allRoles.has(child)) {
1070
1392
  throw new Error(`[BymaxAuthModule] roles.hierarchy['${role}'] references unknown role '${child}'. All roles referenced as children must be declared as keys in the hierarchy.`);
@@ -1079,24 +1401,16 @@ function validatePlatformAdmin(platform, roles) {
1079
1401
  }
1080
1402
  }
1081
1403
  __name(validatePlatformAdmin, "validatePlatformAdmin");
1082
- function validatePasswordResetOtpLength(passwordReset) {
1083
- const otpLength = passwordReset?.otpLength;
1084
- if (otpLength === void 0) return;
1085
- if (otpLength < 4 || otpLength > 8) {
1086
- throw new Error(`[BymaxAuthModule] passwordReset.otpLength must be between 4 and 8 inclusive (current: ${otpLength}). Values below 4 are too easily guessable; values above 8 are not required for security and degrade user experience.`);
1087
- }
1088
- }
1089
- __name(validatePasswordResetOtpLength, "validatePasswordResetOtpLength");
1090
1404
  function assertIntegralScryptParameter(name, value) {
1091
1405
  if (value === void 0 || Number.isInteger(value)) return;
1092
- throw new Error(`[BymaxAuthModule] password.${name} must be an integer (current: ${value}). Node's crypto.scrypt rejects a non-integral cost parameter, and it does so on the first derivation \u2014 which is the first login after deploy, not at startup.`);
1406
+ throw new Error(`[BymaxAuthModule] password.${name} must be an integer (received ${describeReceived(value)}). Node's crypto.scrypt rejects a non-integral cost parameter, and it does so on the first derivation \u2014 which is the first login after deploy, not at startup.`);
1093
1407
  }
1094
1408
  __name(assertIntegralScryptParameter, "assertIntegralScryptParameter");
1095
1409
  function validatePasswordMinLength(password) {
1096
1410
  const minLength = password?.minLength;
1097
1411
  if (minLength === void 0) return;
1098
1412
  if (!Number.isInteger(minLength) || minLength < 8 || minLength > 128) {
1099
- throw new Error(`[BymaxAuthModule] password.minLength must be an integer between 8 and 128 (current: ${String(minLength)}). NIST SP 800-63B-4 \xA73.1.1.1 allows 8 only for a password used as part of multi-factor authentication and requires 15 for one used as a single factor; 128 is the maximum the password DTOs accept, so a higher policy would reject every password that reaches this service.`);
1413
+ throw new Error(`[BymaxAuthModule] password.minLength must be an integer between 8 and 128 (received ${describeReceived(minLength)}). NIST SP 800-63B-4 \xA73.1.1.1 allows 8 only for a password used as part of multi-factor authentication and requires 15 for one used as a single factor; 128 is the maximum the password DTOs accept, so a higher policy would reject every password that reaches this service.`);
1100
1414
  }
1101
1415
  }
1102
1416
  __name(validatePasswordMinLength, "validatePasswordMinLength");
@@ -1105,24 +1419,20 @@ function validatePasswordCostFactor(password) {
1105
1419
  if (costFactor === void 0) return;
1106
1420
  assertIntegralScryptParameter("costFactor", costFactor);
1107
1421
  if (costFactor < 16384) {
1108
- throw new Error(`[BymaxAuthModule] password.costFactor must be at least 16384 (2^14) (current: ${costFactor}). Lower values produce hashes vulnerable to brute-force attacks. The recommended minimum for production is 32768 (2^15).`);
1422
+ throw new Error(`[BymaxAuthModule] password.costFactor must be at least 16384 (2^14) (received ${describeReceived(costFactor)}). Lower values produce hashes vulnerable to brute-force attacks. The recommended minimum for production is 32768 (2^15).`);
1109
1423
  }
1110
1424
  if ((costFactor & costFactor - 1) !== 0) {
1111
- throw new Error(`[BymaxAuthModule] password.costFactor must be a power of 2 (current: ${costFactor}).`);
1425
+ throw new Error(`[BymaxAuthModule] password.costFactor must be a power of 2 (received ${describeReceived(costFactor)}).`);
1112
1426
  }
1113
1427
  }
1114
1428
  __name(validatePasswordCostFactor, "validatePasswordCostFactor");
1115
1429
  function validateBruteForce(bruteForce) {
1116
- const windowSeconds = bruteForce?.windowSeconds;
1117
- if (windowSeconds !== void 0 && (!Number.isInteger(windowSeconds) || windowSeconds < 1)) {
1118
- throw new Error(`[BymaxAuthModule] bruteForce.windowSeconds must be a whole number of at least 1 (current: ${windowSeconds}). Redis deletes a key on \`EXPIRE key 0\`, so a zero or negative window destroys each failure counter as it is created and the account lockout never engages \u2014 silently, with the configuration still reading as enabled.`);
1119
- }
1120
1430
  const maxAttempts = bruteForce?.maxAttempts;
1121
1431
  if (maxAttempts !== void 0 && (!Number.isInteger(maxAttempts) || maxAttempts < 1)) {
1122
- throw new Error(`[BymaxAuthModule] bruteForce.maxAttempts must be a whole number of at least 1 (current: ${maxAttempts}). Zero locks out every account permanently, because a freshly created counter already satisfies "attempts >= 0".`);
1432
+ throw new Error(`[BymaxAuthModule] bruteForce.maxAttempts must be a whole number of at least 1 (received ${describeReceived(maxAttempts)}). Zero locks out every account permanently, because a freshly created counter already satisfies "attempts >= 0".`);
1123
1433
  }
1124
1434
  if (maxAttempts !== void 0 && maxAttempts > MAX_BRUTE_FORCE_ATTEMPTS) {
1125
- throw new Error(`[BymaxAuthModule] bruteForce.maxAttempts must not exceed ${MAX_BRUTE_FORCE_ATTEMPTS} (current: ${maxAttempts}). A threshold this high disables the lockout as effectively as switching it off, while the configuration still reads as enabled.`);
1435
+ throw new Error(`[BymaxAuthModule] bruteForce.maxAttempts must not exceed ${MAX_BRUTE_FORCE_ATTEMPTS} (received ${describeReceived(maxAttempts)}). A threshold this high disables the lockout as effectively as switching it off, while the configuration still reads as enabled.`);
1126
1436
  }
1127
1437
  }
1128
1438
  __name(validateBruteForce, "validateBruteForce");
@@ -1132,12 +1442,12 @@ function validatePasswordMemoryParameters(password) {
1132
1442
  const blockSize = password?.blockSize;
1133
1443
  assertIntegralScryptParameter("blockSize", blockSize);
1134
1444
  if (blockSize !== void 0 && blockSize < 8) {
1135
- throw new Error(`[BymaxAuthModule] password.blockSize must be at least 8 (current: ${blockSize}). scrypt's memory cost is 128 * N * r, so a smaller block size divides the memory hardness that password.costFactor's floor exists to guarantee.`);
1445
+ throw new Error(`[BymaxAuthModule] password.blockSize must be at least 8 (received ${describeReceived(blockSize)}). scrypt's memory cost is 128 * N * r, so a smaller block size divides the memory hardness that password.costFactor's floor exists to guarantee.`);
1136
1446
  }
1137
1447
  const parallelization = password?.parallelization;
1138
1448
  assertIntegralScryptParameter("parallelization", parallelization);
1139
1449
  if (parallelization !== void 0 && parallelization < 1) {
1140
- throw new Error(`[BymaxAuthModule] password.parallelization must be at least 1 (current: ${parallelization}).`);
1450
+ throw new Error(`[BymaxAuthModule] password.parallelization must be at least 1 (received ${describeReceived(parallelization)}).`);
1141
1451
  }
1142
1452
  const effectiveN = password?.costFactor ?? DEFAULT_OPTIONS.password.costFactor;
1143
1453
  const effectiveR = password?.blockSize ?? DEFAULT_OPTIONS.password.blockSize;
@@ -1147,17 +1457,6 @@ function validatePasswordMemoryParameters(password) {
1147
1457
  }
1148
1458
  }
1149
1459
  __name(validatePasswordMemoryParameters, "validatePasswordMemoryParameters");
1150
- function validateMfaVerificationParameters(mfa) {
1151
- const totpWindow = mfa?.totpWindow;
1152
- if (totpWindow !== void 0 && (totpWindow < 0 || totpWindow > MAX_VERIFY_WINDOW)) {
1153
- throw new Error(`[BymaxAuthModule] mfa.totpWindow must be between 0 and ${MAX_VERIFY_WINDOW} inclusive (current: ${totpWindow}). The window is counted in 30-second steps on either side of now, so ${2 * totpWindow + 1} codes would be valid at once. RFC 6238 \xA75.2 recommends at most one step of tolerance; the default of 1 accepts three codes. The bound matches the drift window the verifier actually applies, so a configured value always means what it says instead of being silently clamped.`);
1154
- }
1155
- const recoveryCodeCount = mfa?.recoveryCodeCount;
1156
- if (recoveryCodeCount !== void 0 && (recoveryCodeCount < 1 || recoveryCodeCount > 50)) {
1157
- throw new Error(`[BymaxAuthModule] mfa.recoveryCodeCount must be between 1 and 50 inclusive (current: ${recoveryCodeCount}). Zero enrols an account with no way back if the authenticator is lost.`);
1158
- }
1159
- }
1160
- __name(validateMfaVerificationParameters, "validateMfaVerificationParameters");
1161
1460
  var REQUIRED_OAUTH_FIELDS = [
1162
1461
  "clientId",
1163
1462
  "clientSecret",
@@ -1168,6 +1467,7 @@ function validateOAuthProviders(oauth, isProduction) {
1168
1467
  for (const [providerOrField, rawConfig] of Object.entries(oauth)) {
1169
1468
  if (providerOrField === "successRedirectUrl" || providerOrField === "mfaRedirectUrl" || providerOrField === "errorRedirectUrl") continue;
1170
1469
  const provider = providerOrField;
1470
+ assertObject(`oauth.${provider}`, rawConfig);
1171
1471
  const config = rawConfig;
1172
1472
  for (const field of REQUIRED_OAUTH_FIELDS) {
1173
1473
  if (!config[field]) {
@@ -1176,7 +1476,7 @@ function validateOAuthProviders(oauth, isProduction) {
1176
1476
  }
1177
1477
  const callbackUrl = config["callbackUrl"];
1178
1478
  if (typeof callbackUrl === "string" && !callbackUrl.startsWith("https://") && isProduction) {
1179
- throw new Error(`[BymaxAuthModule] oauth.${provider}.callbackUrl must use HTTPS in production (got: '${callbackUrl}'). Use an HTTPS URL to prevent authorization code interception.`);
1479
+ throw new Error(`[BymaxAuthModule] oauth.${provider}.callbackUrl must use HTTPS in production (received a string). Use an HTTPS URL to prevent authorization code interception.`);
1180
1480
  }
1181
1481
  }
1182
1482
  }
@@ -1190,7 +1490,7 @@ function validateOAuthSuccessRedirectUrl(userOptions) {
1190
1490
  const isProduction = isProductionDeployment(userOptions);
1191
1491
  const isSafe = url.startsWith("/") || url.startsWith("https://");
1192
1492
  if (isProduction && !isSafe) {
1193
- throw new Error(`[BymaxAuthModule] oauth.successRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (got: '${url}').`);
1493
+ throw new Error(`[BymaxAuthModule] oauth.successRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (received a string).`);
1194
1494
  }
1195
1495
  if (userOptions.tokenDelivery === "bearer") {
1196
1496
  throw new Error(`[BymaxAuthModule] oauth.successRedirectUrl is set but tokenDelivery is 'bearer'. A redirect discards the JSON response body, so the access token would never reach the client. Use tokenDelivery: 'cookie' or 'both' when configuring a successRedirectUrl.`);
@@ -1206,7 +1506,7 @@ function validateOAuthMfaRedirectUrl(userOptions) {
1206
1506
  const isProduction = isProductionDeployment(userOptions);
1207
1507
  const isSafe = url.startsWith("/") || url.startsWith("https://");
1208
1508
  if (isProduction && !isSafe) {
1209
- throw new Error(`[BymaxAuthModule] oauth.mfaRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (got: '${url}').`);
1509
+ throw new Error(`[BymaxAuthModule] oauth.mfaRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (received a string).`);
1210
1510
  }
1211
1511
  }
1212
1512
  __name(validateOAuthMfaRedirectUrl, "validateOAuthMfaRedirectUrl");
@@ -1219,7 +1519,7 @@ function validateOAuthErrorRedirectUrl(userOptions) {
1219
1519
  const isProduction = isProductionDeployment(userOptions);
1220
1520
  const isSafe = url.startsWith("/") || url.startsWith("https://");
1221
1521
  if (isProduction && !isSafe) {
1222
- throw new Error(`[BymaxAuthModule] oauth.errorRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (got: '${url}').`);
1522
+ throw new Error(`[BymaxAuthModule] oauth.errorRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (received a string).`);
1223
1523
  }
1224
1524
  }
1225
1525
  __name(validateOAuthErrorRedirectUrl, "validateOAuthErrorRedirectUrl");
@@ -1301,22 +1601,6 @@ function isAbsoluteOrigin(value) {
1301
1601
  }
1302
1602
  }
1303
1603
  __name(isAbsoluteOrigin, "isAbsoluteOrigin");
1304
- var MAX_REFRESH_GRACE_WINDOW_SECONDS = 300;
1305
- function validateRefreshGraceWindow(jwt) {
1306
- const graceSeconds = jwt.refreshGraceWindowSeconds ?? DEFAULT_OPTIONS.jwt.refreshGraceWindowSeconds;
1307
- const refreshExpiresInDays = jwt.refreshExpiresInDays ?? DEFAULT_OPTIONS.jwt.refreshExpiresInDays;
1308
- const refreshLifetimeSeconds = refreshExpiresInDays * 86400;
1309
- if (!Number.isFinite(refreshExpiresInDays) || refreshExpiresInDays <= 0) {
1310
- throw new Error(`[BymaxAuthModule] jwt.refreshExpiresInDays must be a positive finite number. Got: ${refreshExpiresInDays}. Zero, negative, NaN, and Infinity are all rejected \u2014 any of these would produce an invalid Redis TTL and cause all token rotations to fail at runtime.`);
1311
- }
1312
- if (graceSeconds >= refreshLifetimeSeconds) {
1313
- throw new Error(`[BymaxAuthModule] jwt.refreshGraceWindowSeconds (${graceSeconds} s) must be less than the refresh token lifetime jwt.refreshExpiresInDays * 86400 (${refreshLifetimeSeconds} s). A grace window equal to or longer than the token lifetime would allow grace pointers to outlive the refresh session they protect.`);
1314
- }
1315
- if (graceSeconds < 0 || graceSeconds > MAX_REFRESH_GRACE_WINDOW_SECONDS) {
1316
- throw new Error(`[BymaxAuthModule] jwt.refreshGraceWindowSeconds must be between 0 and ${MAX_REFRESH_GRACE_WINDOW_SECONDS} inclusive (current: ${graceSeconds}). The window is how long an already-consumed refresh token still recovers a session, so it is exactly the replay window for a stolen one. It covers a client that rotated but never received the response \u2014 a retry, not a policy. 0 disables grace recovery entirely.`);
1317
- }
1318
- }
1319
- __name(validateRefreshGraceWindow, "validateRefreshGraceWindow");
1320
1604
  function validateAccessLifetimeAgainstEpochRetention(jwt) {
1321
1605
  const configured = jwt.accessExpiresIn ?? DEFAULT_OPTIONS.jwt.accessExpiresIn;
1322
1606
  const seconds = durationToSeconds(configured);
@@ -24882,7 +25166,7 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
24882
25166
  this.sink = sink;
24883
25167
  this.messages = {
24884
25168
  ...DEFAULT_MESSAGES,
24885
- ...options?.messages
25169
+ ...dropUnsetKeys(options?.messages ?? {})
24886
25170
  };
24887
25171
  const configured = options?.onDeliveryError;
24888
25172
  this.deliveryErrorPolicy = new Map(typeof configured === "string" ? AUTH_EMAIL_KINDS.map((kind) => [