@bymax-one/nest-auth 1.5.8 → 1.5.10

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.
@@ -27,6 +27,193 @@ var BYMAX_AUTH_API_KEY_CLOCK = /* @__PURE__ */ Symbol("BYMAX_AUTH_API_KEY_CLOCK"
27
27
  var BYMAX_AUTH_WORKSPACE_REPOSITORY = /* @__PURE__ */ Symbol("BYMAX_AUTH_WORKSPACE_REPOSITORY");
28
28
  var BYMAX_AUTH_MEMBERSHIP_REPOSITORY = /* @__PURE__ */ Symbol("BYMAX_AUTH_MEMBERSHIP_REPOSITORY");
29
29
 
30
+ // src/server/config/describe-received.ts
31
+ function describeReceived(value) {
32
+ if (typeof value === "number") return String(value);
33
+ if (value === null || value === void 0) return String(value);
34
+ if (Array.isArray(value)) return "an array";
35
+ const kind = typeof value;
36
+ return `${kind === "object" ? "an" : "a"} ${kind}`;
37
+ }
38
+ __name(describeReceived, "describeReceived");
39
+
40
+ // src/server/config/enum-boolean-options.ts
41
+ var BOOLEAN_OPTIONS = [
42
+ "secureCookies",
43
+ "enforceTenantBinding",
44
+ "sessions.enabled",
45
+ "emailVerification.required",
46
+ "platform.enabled",
47
+ "invitations.enabled",
48
+ "rateLimit.enabled",
49
+ "workspaces.enabled",
50
+ "apiKeys.enabled"
51
+ ];
52
+ var BOOLEAN_OR_FUNCTION_OPTIONS = [
53
+ "workspaces.allowCreate"
54
+ ];
55
+ var CONTROLLER_FLAGS = [
56
+ "auth",
57
+ "mfa",
58
+ "passwordReset",
59
+ "sessions",
60
+ "platform",
61
+ "oauth",
62
+ "invitations",
63
+ "emailChange",
64
+ "workspaces",
65
+ "workspaceInvitations"
66
+ ];
67
+ var ENUM_OPTIONS = {
68
+ tokenDelivery: [
69
+ "cookie",
70
+ "bearer",
71
+ "both"
72
+ ],
73
+ environment: [
74
+ "production",
75
+ "development",
76
+ "test"
77
+ ],
78
+ "cookies.sameSite": [
79
+ "lax",
80
+ "strict",
81
+ "none"
82
+ ],
83
+ "passwordReset.method": [
84
+ "token",
85
+ "otp"
86
+ ]
87
+ };
88
+ function readPath(root, path) {
89
+ let node = root;
90
+ for (const step of path.split(".")) {
91
+ if (typeof node !== "object" || node === null) return void 0;
92
+ node = Reflect.get(node, step);
93
+ }
94
+ return node;
95
+ }
96
+ __name(readPath, "readPath");
97
+ function assertBoolean(path, value) {
98
+ if (value === void 0 || typeof value === "boolean") return;
99
+ throw new Error(`[BymaxAuthModule] ${path} must be true or false (received ${describeReceived(value)}).`);
100
+ }
101
+ __name(assertBoolean, "assertBoolean");
102
+ function assertOneOf(path, value, allowed) {
103
+ if (value === void 0 || typeof value === "string" && allowed.includes(value)) return;
104
+ throw new Error(`[BymaxAuthModule] ${path} must be one of ${allowed.map((entry) => `'${entry}'`).join(", ")} (received ${describeReceived(value)}).`);
105
+ }
106
+ __name(assertOneOf, "assertOneOf");
107
+ function validateControllerFlags(flags) {
108
+ for (const name of CONTROLLER_FLAGS) {
109
+ const flag = readPath(flags, name);
110
+ if (flag !== null) assertBoolean(`controllers.${name}`, flag);
111
+ }
112
+ }
113
+ __name(validateControllerFlags, "validateControllerFlags");
114
+ function validateEnumAndBooleanOptions(userOptions) {
115
+ for (const path of BOOLEAN_OPTIONS) assertBoolean(path, readPath(userOptions, path));
116
+ for (const path of BOOLEAN_OR_FUNCTION_OPTIONS) {
117
+ const value = readPath(userOptions, path);
118
+ if (typeof value !== "function") assertBoolean(path, value);
119
+ }
120
+ for (const [path, allowed] of Object.entries(ENUM_OPTIONS)) {
121
+ assertOneOf(path, readPath(userOptions, path), allowed);
122
+ }
123
+ validateControllerFlags(userOptions.controllers);
124
+ }
125
+ __name(validateEnumAndBooleanOptions, "validateEnumAndBooleanOptions");
126
+
127
+ // src/server/config/provider-shape.ts
128
+ var REQUIRED_EMAIL_METHODS = [
129
+ "sendPasswordResetToken",
130
+ "sendPasswordResetOtp",
131
+ "sendEmailVerificationOtp",
132
+ "sendMfaEnabledNotification",
133
+ "sendMfaDisabledNotification",
134
+ "sendInvitation"
135
+ ];
136
+ function readyMadeValue(providers, token) {
137
+ const entry = providers.find((p) => typeof p !== "function" && "provide" in p && p.provide === token);
138
+ if (entry === void 0 || !("useValue" in entry)) return {
139
+ found: false,
140
+ value: void 0
141
+ };
142
+ return {
143
+ found: true,
144
+ value: entry.useValue
145
+ };
146
+ }
147
+ __name(readyMadeValue, "readyMadeValue");
148
+ var HOOK_NAMES = Object.keys({
149
+ beforeRegister: true,
150
+ afterRegister: true,
151
+ beforeLogin: true,
152
+ afterLogin: true,
153
+ afterLogout: true,
154
+ afterPlatformLogout: true,
155
+ onLoginFailed: true,
156
+ onLockout: true,
157
+ onRefreshTokenReuseDetected: true,
158
+ afterMfaEnabled: true,
159
+ afterMfaDisabled: true,
160
+ afterMfaRecoveryCodesRegenerated: true,
161
+ onNewSession: true,
162
+ afterEmailVerified: true,
163
+ afterPasswordReset: true,
164
+ onOAuthLogin: true,
165
+ afterInvitationAccepted: true,
166
+ onSessionEvicted: true,
167
+ onApiKeyRequest: true,
168
+ beforeWorkspaceCreate: true,
169
+ onWorkspaceEvent: true
170
+ });
171
+ var EMAIL_METHOD_NAMES = Object.keys({
172
+ sendPasswordResetToken: true,
173
+ sendPasswordResetOtp: true,
174
+ sendEmailVerificationOtp: true,
175
+ sendPasswordChangedNotification: true,
176
+ sendEmailChangeVerification: true,
177
+ sendEmailChangedNotification: true,
178
+ sendMfaEnabledNotification: true,
179
+ sendMfaDisabledNotification: true,
180
+ sendNewSessionAlert: true,
181
+ sendInvitation: true,
182
+ sendWorkspaceInvitation: true
183
+ });
184
+ function assertNamedFunctions(label, value, names) {
185
+ if (typeof value !== "object" || value === null) {
186
+ throw new Error(`[BymaxAuthModule] ${label} must be an object (received ${describeReceived(value)}).`);
187
+ }
188
+ for (const name of names) {
189
+ const member = Reflect.get(value, name);
190
+ if (member !== void 0 && member !== null && typeof member !== "function") {
191
+ throw new Error(`[BymaxAuthModule] ${label}.${name} must be a function (received ${describeReceived(member)}).`);
192
+ }
193
+ }
194
+ }
195
+ __name(assertNamedFunctions, "assertNamedFunctions");
196
+ function assertProviderShapes(providers) {
197
+ const hooks = readyMadeValue(providers, BYMAX_AUTH_HOOKS);
198
+ if (hooks.found && hooks.value !== null && hooks.value !== void 0) {
199
+ assertNamedFunctions("BYMAX_AUTH_HOOKS", hooks.value, HOOK_NAMES);
200
+ }
201
+ const email = readyMadeValue(providers, BYMAX_AUTH_EMAIL_PROVIDER);
202
+ if (!email.found) return;
203
+ assertNamedFunctions("BYMAX_AUTH_EMAIL_PROVIDER", email.value, EMAIL_METHOD_NAMES);
204
+ for (const name of REQUIRED_EMAIL_METHODS) {
205
+ if (typeof Reflect.get(email.value, name) !== "function") {
206
+ throw new Error(`[BymaxAuthModule] BYMAX_AUTH_EMAIL_PROVIDER.${name} is required and must be a function.`);
207
+ }
208
+ }
209
+ }
210
+ __name(assertProviderShapes, "assertProviderShapes");
211
+ function validateRegistrationShapes(controllers, providers) {
212
+ validateControllerFlags(controllers);
213
+ assertProviderShapes(providers);
214
+ }
215
+ __name(validateRegistrationShapes, "validateRegistrationShapes");
216
+
30
217
  // src/server/config/default-options.ts
31
218
  var DEFAULT_OPTIONS = {
32
219
  jwt: {
@@ -364,6 +551,461 @@ function durationToSeconds(value) {
364
551
  return amount * seconds;
365
552
  }
366
553
  __name(durationToSeconds, "durationToSeconds");
554
+ var TOTP_STEP_SECONDS = 30;
555
+ var TOTP_DIGITS = 6;
556
+ var BASE32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
557
+ var MIN_SECRET_BYTES = 20;
558
+ function toBase32(input) {
559
+ let bits = 0;
560
+ let value = 0;
561
+ let output = "";
562
+ for (let i = 0; i < input.length; i++) {
563
+ value = value << 8 | input.readUInt8(i);
564
+ bits += 8;
565
+ while (bits >= 5) {
566
+ bits -= 5;
567
+ output += BASE32_ALPHABET[value >>> bits & 31];
568
+ }
569
+ }
570
+ if (bits > 0) {
571
+ output += BASE32_ALPHABET[value << 5 - bits & 31];
572
+ }
573
+ return output;
574
+ }
575
+ __name(toBase32, "toBase32");
576
+ function fromBase32(input) {
577
+ const normalized = input.toUpperCase().replace(/[\s=-]/g, "");
578
+ let bits = 0;
579
+ let value = 0;
580
+ const output = [];
581
+ for (const char of normalized) {
582
+ const idx = BASE32_ALPHABET.indexOf(char);
583
+ if (idx === -1) {
584
+ throw new Error(`[totp] Invalid Base32 character: ${JSON.stringify(char)}`);
585
+ }
586
+ value = value << 5 | idx;
587
+ bits += 5;
588
+ if (bits >= 8) {
589
+ bits -= 8;
590
+ output.push(value >>> bits & 255);
591
+ }
592
+ }
593
+ return Buffer.from(output);
594
+ }
595
+ __name(fromBase32, "fromBase32");
596
+ function generateTotpSecret() {
597
+ const raw = crypto.randomBytes(MIN_SECRET_BYTES);
598
+ return {
599
+ raw,
600
+ base32: toBase32(raw)
601
+ };
602
+ }
603
+ __name(generateTotpSecret, "generateTotpSecret");
604
+ function buildTotpUri(secretBase32, accountEmail, issuer) {
605
+ if (!secretBase32 || secretBase32.length < 32) {
606
+ throw new Error("[totp] secretBase32 must encode at least 20 bytes (minimum 32 base32 characters)");
607
+ }
608
+ if (!issuer) {
609
+ throw new Error("[totp] issuer must not be empty");
610
+ }
611
+ if (!accountEmail) {
612
+ throw new Error("[totp] accountEmail must not be empty");
613
+ }
614
+ const label = `${encodeURIComponent(issuer)}:${encodeURIComponent(accountEmail)}`;
615
+ const qs = [
616
+ `secret=${encodeURIComponent(secretBase32)}`,
617
+ `issuer=${encodeURIComponent(issuer)}`,
618
+ `algorithm=SHA1`,
619
+ `digits=${String(TOTP_DIGITS)}`,
620
+ `period=${String(TOTP_STEP_SECONDS)}`
621
+ ].join("&");
622
+ return `otpauth://totp/${label}?${qs}`;
623
+ }
624
+ __name(buildTotpUri, "buildTotpUri");
625
+ function generateHotp(secretBase32, counter) {
626
+ const key = fromBase32(secretBase32);
627
+ if (key.length < MIN_SECRET_BYTES) {
628
+ throw new Error(`[totp] Secret too short: ${key.length} bytes (minimum ${MIN_SECRET_BYTES}). Generate secrets with generateTotpSecret().`);
629
+ }
630
+ if (!Number.isInteger(counter) || counter < 0 || counter > Number.MAX_SAFE_INTEGER) {
631
+ throw new Error(`[totp] Counter must be a non-negative safe integer (got ${counter}).`);
632
+ }
633
+ const counterBuffer = Buffer.allocUnsafe(8);
634
+ const hi = Math.floor(counter / 4294967296);
635
+ const lo = counter >>> 0;
636
+ counterBuffer.writeUInt32BE(hi, 0);
637
+ counterBuffer.writeUInt32BE(lo, 4);
638
+ const hmac = crypto.createHmac("sha1", key).update(counterBuffer).digest();
639
+ const offset = hmac.readUInt8(hmac.length - 1) & 15;
640
+ const truncated = (hmac.readUInt8(offset) & 127) << 24 | (hmac.readUInt8(offset + 1) & 255) << 16 | (hmac.readUInt8(offset + 2) & 255) << 8 | hmac.readUInt8(offset + 3);
641
+ const mod = 10 ** TOTP_DIGITS;
642
+ return String(truncated % mod).padStart(TOTP_DIGITS, "0");
643
+ }
644
+ __name(generateHotp, "generateHotp");
645
+ var MAX_VERIFY_WINDOW = 2;
646
+ function verifyTotp(secretBase32, code, window = 1) {
647
+ if (!/^\d{6}$/.test(code)) return false;
648
+ const currentStep = Math.floor(Date.now() / 1e3 / TOTP_STEP_SECONDS);
649
+ const effective = Math.min(Math.max(window, 0), MAX_VERIFY_WINDOW);
650
+ for (let delta = -effective; delta <= effective; delta++) {
651
+ const expected = generateHotp(secretBase32, currentStep + delta);
652
+ const expectedBuf = Buffer.from(expected, "utf8");
653
+ const codeBuf = Buffer.from(code, "utf8");
654
+ if (expectedBuf.length === codeBuf.length && crypto.timingSafeEqual(expectedBuf, codeBuf)) {
655
+ return true;
656
+ }
657
+ }
658
+ return false;
659
+ }
660
+ __name(verifyTotp, "verifyTotp");
661
+
662
+ // src/server/config/numeric-options.ts
663
+ var MAX_USER_STATUS_CACHE_TTL_SECONDS = 3600;
664
+ var MAX_REDIS_TTL_SECONDS = 31536e4;
665
+ var MAX_COOKIE_MAX_AGE_MS = MAX_REDIS_TTL_SECONDS * 1e3;
666
+ var MAX_SESSIONS_PER_USER = 1e3;
667
+ var MAX_LIFETIME_DAYS = 3650;
668
+ var MIN_ABSOLUTE_LIFETIME_DAYS = 1 / 24;
669
+ var MAX_SCRYPT_PARALLELIZATION = 16;
670
+ var MAX_BRUTE_FORCE_WINDOW_SECONDS = 604800;
671
+ function assertWholeNumber(path, value, min, max, why) {
672
+ if (value === void 0) return;
673
+ if (Number.isSafeInteger(value) && value >= min && value <= max) return;
674
+ throw new Error(`[BymaxAuthModule] ${path} must be a whole number between ${min} and ${max} inclusive (received ${describeReceived(value)}). ${why}`);
675
+ }
676
+ __name(assertWholeNumber, "assertWholeNumber");
677
+ function validateWholeNumberOptions(userOptions) {
678
+ 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.");
679
+ 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.");
680
+ 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.");
681
+ 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.");
682
+ }
683
+ __name(validateWholeNumberOptions, "validateWholeNumberOptions");
684
+ function validateRedisTtls(userOptions) {
685
+ const ttls = [
686
+ [
687
+ "passwordReset.tokenTtlSeconds",
688
+ userOptions.passwordReset?.tokenTtlSeconds
689
+ ],
690
+ [
691
+ "passwordReset.otpTtlSeconds",
692
+ userOptions.passwordReset?.otpTtlSeconds
693
+ ],
694
+ [
695
+ "emailVerification.otpTtlSeconds",
696
+ userOptions.emailVerification?.otpTtlSeconds
697
+ ],
698
+ [
699
+ "emailChange.tokenTtlSeconds",
700
+ userOptions.emailChange?.tokenTtlSeconds
701
+ ],
702
+ [
703
+ "invitations.tokenTtlSeconds",
704
+ userOptions.invitations?.tokenTtlSeconds
705
+ ]
706
+ ];
707
+ for (const [path, value] of ttls) {
708
+ 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.");
709
+ }
710
+ }
711
+ __name(validateRedisTtls, "validateRedisTtls");
712
+ function validateAbsoluteSessionLifetime(jwt) {
713
+ const days = jwt.absoluteSessionLifetimeDays;
714
+ if (days === void 0 || days === 0 || Number.isFinite(days) && days >= MIN_ABSOLUTE_LIFETIME_DAYS && days <= MAX_LIFETIME_DAYS) {
715
+ return;
716
+ }
717
+ 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.`);
718
+ }
719
+ __name(validateAbsoluteSessionLifetime, "validateAbsoluteSessionLifetime");
720
+ function validatePasswordResetOtpLength(passwordReset) {
721
+ const otpLength = passwordReset?.otpLength;
722
+ if (otpLength === void 0) return;
723
+ if (!Number.isInteger(otpLength) || otpLength < 4 || otpLength > 8) {
724
+ 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.`);
725
+ }
726
+ }
727
+ __name(validatePasswordResetOtpLength, "validatePasswordResetOtpLength");
728
+ function validateMfaVerificationParameters(mfa) {
729
+ const totpWindow = mfa?.totpWindow;
730
+ if (totpWindow !== void 0 && (!Number.isInteger(totpWindow) || totpWindow < 0 || totpWindow > MAX_VERIFY_WINDOW)) {
731
+ 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.`);
732
+ }
733
+ const recoveryCodeCount = mfa?.recoveryCodeCount;
734
+ if (recoveryCodeCount !== void 0 && (!Number.isInteger(recoveryCodeCount) || recoveryCodeCount < 1 || recoveryCodeCount > 50)) {
735
+ 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.`);
736
+ }
737
+ }
738
+ __name(validateMfaVerificationParameters, "validateMfaVerificationParameters");
739
+ var MAX_REFRESH_GRACE_WINDOW_SECONDS = 300;
740
+ function validateRefreshGraceWindow(jwt) {
741
+ const graceSeconds = jwt.refreshGraceWindowSeconds ?? DEFAULT_OPTIONS.jwt.refreshGraceWindowSeconds;
742
+ const refreshExpiresInDays = jwt.refreshExpiresInDays ?? DEFAULT_OPTIONS.jwt.refreshExpiresInDays;
743
+ const refreshLifetimeSeconds = typeof refreshExpiresInDays === "number" ? refreshExpiresInDays * 86400 : Number.NaN;
744
+ const isGraceNumber = typeof graceSeconds === "number";
745
+ if (!Number.isFinite(refreshExpiresInDays) || refreshExpiresInDays <= 0 || refreshExpiresInDays > MAX_LIFETIME_DAYS || !Number.isInteger(refreshLifetimeSeconds)) {
746
+ 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.`);
747
+ }
748
+ if (isGraceNumber && graceSeconds >= refreshLifetimeSeconds) {
749
+ 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.`);
750
+ }
751
+ if (!isGraceNumber || !Number.isInteger(graceSeconds) || graceSeconds < 0 || graceSeconds > MAX_REFRESH_GRACE_WINDOW_SECONDS) {
752
+ 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.`);
753
+ }
754
+ }
755
+ __name(validateRefreshGraceWindow, "validateRefreshGraceWindow");
756
+ function validateScryptParallelizationCeiling(password) {
757
+ const parallelization = password?.parallelization;
758
+ if (parallelization === void 0 || !Number.isFinite(parallelization) || parallelization <= MAX_SCRYPT_PARALLELIZATION) {
759
+ return;
760
+ }
761
+ 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.`);
762
+ }
763
+ __name(validateScryptParallelizationCeiling, "validateScryptParallelizationCeiling");
764
+ function validateNumericOptions(userOptions) {
765
+ validatePasswordResetOtpLength(userOptions.passwordReset);
766
+ validateMfaVerificationParameters(userOptions.mfa);
767
+ validateRefreshGraceWindow(userOptions.jwt);
768
+ validateAbsoluteSessionLifetime(userOptions.jwt);
769
+ validateScryptParallelizationCeiling(userOptions.password);
770
+ validateWholeNumberOptions(userOptions);
771
+ validateRedisTtls(userOptions);
772
+ }
773
+ __name(validateNumericOptions, "validateNumericOptions");
774
+
775
+ // src/server/config/option-values.ts
776
+ function validateOptionValues(userOptions) {
777
+ validateNumericOptions(userOptions);
778
+ validateEnumAndBooleanOptions(userOptions);
779
+ }
780
+ __name(validateOptionValues, "validateOptionValues");
781
+
782
+ // src/server/config/shape-checks.ts
783
+ function assertObject(label, value) {
784
+ if (Object(value) === value) return;
785
+ throw new Error(`[BymaxAuthModule] ${label} must be an object (received ${describeReceived(value)}).`);
786
+ }
787
+ __name(assertObject, "assertObject");
788
+ function assertArray(label, value) {
789
+ if (Array.isArray(value)) return;
790
+ throw new Error(`[BymaxAuthModule] ${label} must be an array (received ${describeReceived(value)}).`);
791
+ }
792
+ __name(assertArray, "assertArray");
793
+
794
+ // src/server/config/unset-options.ts
795
+ var TOP_KEYS = {
796
+ identifierKey: true,
797
+ jwt: true,
798
+ password: true,
799
+ tokenDelivery: true,
800
+ environment: true,
801
+ secureCookies: true,
802
+ cookies: true,
803
+ rateLimit: true,
804
+ mfa: true,
805
+ sessions: true,
806
+ bruteForce: true,
807
+ passwordReset: true,
808
+ emailVerification: true,
809
+ platform: true,
810
+ emailChange: true,
811
+ invitations: true,
812
+ apiKeys: true,
813
+ roles: true,
814
+ blockedStatuses: true,
815
+ redisNamespace: true,
816
+ oauth: true,
817
+ workspaces: true,
818
+ registration: true,
819
+ routePrefix: true,
820
+ tenantIdResolver: true,
821
+ enforceTenantBinding: true,
822
+ isTrustedProxy: true,
823
+ controllers: true,
824
+ userStatusCacheTtlSeconds: true
825
+ };
826
+ var GROUP_KEYS = {
827
+ jwt: {
828
+ secret: true,
829
+ previousSecrets: true,
830
+ accessExpiresIn: true,
831
+ accessCookieMaxAgeMs: true,
832
+ refreshExpiresInDays: true,
833
+ absoluteSessionLifetimeDays: true,
834
+ algorithm: true,
835
+ issuer: true,
836
+ audience: true,
837
+ refreshGraceWindowSeconds: true
838
+ },
839
+ password: {
840
+ costFactor: true,
841
+ minLength: true,
842
+ blockSize: true,
843
+ parallelization: true,
844
+ blocklist: true
845
+ },
846
+ cookies: {
847
+ accessTokenName: true,
848
+ refreshTokenName: true,
849
+ sessionSignalName: true,
850
+ refreshCookiePath: true,
851
+ mfaTempCookiePath: true,
852
+ resolveDomains: true,
853
+ sameSite: true,
854
+ trustedOrigins: true
855
+ },
856
+ sessions: {
857
+ enabled: true,
858
+ defaultMaxSessions: true,
859
+ maxSessionsResolver: true
860
+ },
861
+ bruteForce: {
862
+ maxAttempts: true,
863
+ windowSeconds: true
864
+ },
865
+ passwordReset: {
866
+ method: true,
867
+ tokenTtlSeconds: true,
868
+ otpTtlSeconds: true,
869
+ otpLength: true
870
+ },
871
+ emailVerification: {
872
+ required: true,
873
+ otpTtlSeconds: true
874
+ },
875
+ platform: {
876
+ enabled: true
877
+ },
878
+ invitations: {
879
+ enabled: true,
880
+ tokenTtlSeconds: true
881
+ },
882
+ emailChange: {
883
+ tokenTtlSeconds: true
884
+ },
885
+ controllers: {
886
+ auth: true,
887
+ mfa: true,
888
+ passwordReset: true,
889
+ sessions: true,
890
+ platform: true,
891
+ oauth: true,
892
+ invitations: true,
893
+ emailChange: true,
894
+ workspaces: true,
895
+ workspaceInvitations: true
896
+ },
897
+ rateLimit: {
898
+ enabled: true,
899
+ clientIpSource: true
900
+ },
901
+ mfa: {
902
+ encryptionKey: true,
903
+ previousEncryptionKeys: true,
904
+ issuer: true,
905
+ recoveryCodeCount: true,
906
+ totpWindow: true
907
+ },
908
+ apiKeys: {
909
+ enabled: true,
910
+ pepper: true,
911
+ scopes: true,
912
+ header: true,
913
+ prefix: true,
914
+ lastUsedFlushSeconds: true,
915
+ auditMode: true
916
+ },
917
+ workspaces: {
918
+ enabled: true,
919
+ roles: true,
920
+ permissions: true,
921
+ allowCreate: true,
922
+ maxWorkspacesPerUser: true,
923
+ invitationTtlSeconds: true,
924
+ maxPendingInvitationsPerWorkspace: true,
925
+ membershipCacheTtlSeconds: true,
926
+ deletionGraceDays: true,
927
+ accessDeniedEvents: true,
928
+ resolveRequestWorkspace: true,
929
+ resolveWsWorkspace: true
930
+ }
931
+ };
932
+ var KEPT_GROUP_KEYS = {
933
+ oauth: {
934
+ successRedirectUrl: true,
935
+ mfaRedirectUrl: true,
936
+ errorRedirectUrl: true,
937
+ google: true
938
+ },
939
+ roles: {
940
+ hierarchy: true,
941
+ platformHierarchy: true
942
+ }
943
+ };
944
+ var WORKSPACE_SUBGROUP_KEYS = {
945
+ accessDeniedEvents: [
946
+ "max",
947
+ "windowSeconds"
948
+ ]
949
+ };
950
+ function isObjectGroup(value) {
951
+ return Object(value) === value && typeof value !== "function" && !Array.isArray(value);
952
+ }
953
+ __name(isObjectGroup, "isObjectGroup");
954
+ function readSetKeys(group, keys) {
955
+ const out = {};
956
+ for (const key of /* @__PURE__ */ new Set([
957
+ ...keys,
958
+ ...Object.keys(group)
959
+ ])) {
960
+ const entry = Reflect.get(group, key);
961
+ if (entry !== void 0 && entry !== null) out[key] = entry;
962
+ }
963
+ return out;
964
+ }
965
+ __name(readSetKeys, "readSetKeys");
966
+ function readKeptKeys(group, keys) {
967
+ const out = {};
968
+ for (const key of /* @__PURE__ */ new Set([
969
+ ...keys,
970
+ ...Object.keys(group)
971
+ ])) {
972
+ const entry = Reflect.get(group, key);
973
+ if (entry !== void 0 || Object.hasOwn(group, key)) out[key] = entry;
974
+ }
975
+ return out;
976
+ }
977
+ __name(readKeptKeys, "readKeptKeys");
978
+ function dropUnsetKeys(value) {
979
+ const copy = {
980
+ ...value
981
+ };
982
+ for (const [key, entry] of Object.entries(copy)) {
983
+ if (entry === void 0 || entry === null) Reflect.deleteProperty(copy, key);
984
+ }
985
+ return copy;
986
+ }
987
+ __name(dropUnsetKeys, "dropUnsetKeys");
988
+ function dropUnset(options) {
989
+ const copy = readSetKeys(options, Object.keys(TOP_KEYS));
990
+ for (const [name, keys] of Object.entries(GROUP_KEYS)) {
991
+ const entry = copy[name];
992
+ if (!isObjectGroup(entry)) continue;
993
+ const group = readSetKeys(entry, Object.keys(keys));
994
+ if (name === "workspaces") {
995
+ for (const [sub, subKeys] of Object.entries(WORKSPACE_SUBGROUP_KEYS)) {
996
+ const inner = group[sub];
997
+ if (isObjectGroup(inner)) group[sub] = readSetKeys(inner, subKeys);
998
+ }
999
+ }
1000
+ copy[name] = group;
1001
+ }
1002
+ for (const [name, keys] of Object.entries(KEPT_GROUP_KEYS)) {
1003
+ const entry = copy[name];
1004
+ if (isObjectGroup(entry)) copy[name] = readKeptKeys(entry, Object.keys(keys));
1005
+ }
1006
+ return Object.assign({}, copy);
1007
+ }
1008
+ __name(dropUnset, "dropUnset");
367
1009
 
368
1010
  // src/server/constants/workspace-roles.ts
369
1011
  var ANY_WORKSPACE_MEMBER = /* @__PURE__ */ Symbol("ANY_WORKSPACE_MEMBER");
@@ -518,6 +1160,7 @@ __name(validateWorkspaceRoles, "validateWorkspaceRoles");
518
1160
  function validateWorkspacePermissions(permissions, roles) {
519
1161
  for (const [action, list] of Object.entries(permissions ?? {})) {
520
1162
  if (list === void 0) continue;
1163
+ assertArray(`workspaces.permissions.${action}`, list);
521
1164
  for (const role of list) {
522
1165
  const known = roles.has(role);
523
1166
  if (!known && !(action === "viewMembers" && role === ANY_WORKSPACE_MEMBER)) {
@@ -668,113 +1311,6 @@ __name(assertWorkspaceProviders, "assertWorkspaceProviders");
668
1311
 
669
1312
  // src/server/constants/token-epoch.ts
670
1313
  var TOKEN_EPOCH_RETENTION_SECONDS = 30 * 24 * 60 * 60;
671
- var TOTP_STEP_SECONDS = 30;
672
- var TOTP_DIGITS = 6;
673
- var BASE32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
674
- var MIN_SECRET_BYTES = 20;
675
- function toBase32(input) {
676
- let bits = 0;
677
- let value = 0;
678
- let output = "";
679
- for (let i = 0; i < input.length; i++) {
680
- value = value << 8 | input.readUInt8(i);
681
- bits += 8;
682
- while (bits >= 5) {
683
- bits -= 5;
684
- output += BASE32_ALPHABET[value >>> bits & 31];
685
- }
686
- }
687
- if (bits > 0) {
688
- output += BASE32_ALPHABET[value << 5 - bits & 31];
689
- }
690
- return output;
691
- }
692
- __name(toBase32, "toBase32");
693
- function fromBase32(input) {
694
- const normalized = input.toUpperCase().replace(/[\s=-]/g, "");
695
- let bits = 0;
696
- let value = 0;
697
- const output = [];
698
- for (const char of normalized) {
699
- const idx = BASE32_ALPHABET.indexOf(char);
700
- if (idx === -1) {
701
- throw new Error(`[totp] Invalid Base32 character: ${JSON.stringify(char)}`);
702
- }
703
- value = value << 5 | idx;
704
- bits += 5;
705
- if (bits >= 8) {
706
- bits -= 8;
707
- output.push(value >>> bits & 255);
708
- }
709
- }
710
- return Buffer.from(output);
711
- }
712
- __name(fromBase32, "fromBase32");
713
- function generateTotpSecret() {
714
- const raw = crypto.randomBytes(MIN_SECRET_BYTES);
715
- return {
716
- raw,
717
- base32: toBase32(raw)
718
- };
719
- }
720
- __name(generateTotpSecret, "generateTotpSecret");
721
- function buildTotpUri(secretBase32, accountEmail, issuer) {
722
- if (!secretBase32 || secretBase32.length < 32) {
723
- throw new Error("[totp] secretBase32 must encode at least 20 bytes (minimum 32 base32 characters)");
724
- }
725
- if (!issuer) {
726
- throw new Error("[totp] issuer must not be empty");
727
- }
728
- if (!accountEmail) {
729
- throw new Error("[totp] accountEmail must not be empty");
730
- }
731
- const label = `${encodeURIComponent(issuer)}:${encodeURIComponent(accountEmail)}`;
732
- const qs = [
733
- `secret=${encodeURIComponent(secretBase32)}`,
734
- `issuer=${encodeURIComponent(issuer)}`,
735
- `algorithm=SHA1`,
736
- `digits=${String(TOTP_DIGITS)}`,
737
- `period=${String(TOTP_STEP_SECONDS)}`
738
- ].join("&");
739
- return `otpauth://totp/${label}?${qs}`;
740
- }
741
- __name(buildTotpUri, "buildTotpUri");
742
- function generateHotp(secretBase32, counter) {
743
- const key = fromBase32(secretBase32);
744
- if (key.length < MIN_SECRET_BYTES) {
745
- throw new Error(`[totp] Secret too short: ${key.length} bytes (minimum ${MIN_SECRET_BYTES}). Generate secrets with generateTotpSecret().`);
746
- }
747
- if (!Number.isInteger(counter) || counter < 0 || counter > Number.MAX_SAFE_INTEGER) {
748
- throw new Error(`[totp] Counter must be a non-negative safe integer (got ${counter}).`);
749
- }
750
- const counterBuffer = Buffer.allocUnsafe(8);
751
- const hi = Math.floor(counter / 4294967296);
752
- const lo = counter >>> 0;
753
- counterBuffer.writeUInt32BE(hi, 0);
754
- counterBuffer.writeUInt32BE(lo, 4);
755
- const hmac = crypto.createHmac("sha1", key).update(counterBuffer).digest();
756
- const offset = hmac.readUInt8(hmac.length - 1) & 15;
757
- const truncated = (hmac.readUInt8(offset) & 127) << 24 | (hmac.readUInt8(offset + 1) & 255) << 16 | (hmac.readUInt8(offset + 2) & 255) << 8 | hmac.readUInt8(offset + 3);
758
- const mod = 10 ** TOTP_DIGITS;
759
- return String(truncated % mod).padStart(TOTP_DIGITS, "0");
760
- }
761
- __name(generateHotp, "generateHotp");
762
- var MAX_VERIFY_WINDOW = 2;
763
- function verifyTotp(secretBase32, code, window = 1) {
764
- if (!/^\d{6}$/.test(code)) return false;
765
- const currentStep = Math.floor(Date.now() / 1e3 / TOTP_STEP_SECONDS);
766
- const effective = Math.min(Math.max(window, 0), MAX_VERIFY_WINDOW);
767
- for (let delta = -effective; delta <= effective; delta++) {
768
- const expected = generateHotp(secretBase32, currentStep + delta);
769
- const expectedBuf = Buffer.from(expected, "utf8");
770
- const codeBuf = Buffer.from(code, "utf8");
771
- if (expectedBuf.length === codeBuf.length && crypto.timingSafeEqual(expectedBuf, codeBuf)) {
772
- return true;
773
- }
774
- }
775
- return false;
776
- }
777
- __name(verifyTotp, "verifyTotp");
778
1314
 
779
1315
  // src/server/config/resolved-options.ts
780
1316
  var HMAC_KEY_DERIVATION_LABEL = "bymax-auth:hmac-key:v1";
@@ -786,17 +1322,17 @@ function isProductionDeployment(userOptions) {
786
1322
  return (userOptions.environment ?? "production") === "production";
787
1323
  }
788
1324
  __name(isProductionDeployment, "isProductionDeployment");
789
- function resolveOptions(userOptions) {
1325
+ function resolveOptions(given) {
1326
+ const userOptions = dropUnset(given);
790
1327
  validateJwt(userOptions.jwt);
791
1328
  validateIdentifierKey(userOptions.identifierKey);
792
1329
  validateMfaEncryptionKey(userOptions.mfa);
793
1330
  validateRolesHierarchy(userOptions.roles);
794
1331
  validatePlatformAdmin(userOptions.platform, userOptions.roles);
795
- validatePasswordResetOtpLength(userOptions.passwordReset);
1332
+ validateOptionValues(userOptions);
796
1333
  validatePasswordMinLength(userOptions.password);
797
1334
  validatePasswordCostFactor(userOptions.password);
798
1335
  validatePasswordMemoryParameters(userOptions.password);
799
- validateMfaVerificationParameters(userOptions.mfa);
800
1336
  validateBruteForce(userOptions.bruteForce);
801
1337
  validateOAuthProviders(userOptions.oauth, isProductionDeployment(userOptions));
802
1338
  validateClientIpSource(userOptions.rateLimit);
@@ -812,7 +1348,6 @@ function resolveOptions(userOptions) {
812
1348
  validateProductionCookiesAreSecure(userOptions);
813
1349
  validateCookiePrefixes(userOptions);
814
1350
  validateTrustedOrigins(userOptions);
815
- validateRefreshGraceWindow(userOptions.jwt);
816
1351
  validateAccessLifetimeAgainstEpochRetention(userOptions.jwt);
817
1352
  const { mfa: _mfa, identifierKey: _identifierKey, workspaces: _workspaces, ...userOptionsWithoutMfa } = userOptions;
818
1353
  const resolved = {
@@ -886,16 +1421,14 @@ function resolveOptions(userOptions) {
886
1421
  userStatusCacheTtlSeconds: userOptions.userStatusCacheTtlSeconds ?? DEFAULT_OPTIONS.userStatusCacheTtlSeconds,
887
1422
  // Evaluated once at startup — not re-evaluated per request.
888
1423
  //
889
- // `clientIpSource` has no default and `validateClientIpSource` has already refused a
890
- // deployment that left it unset with limiting on. The fallback here is reached only when
891
- // limiting is OFF, where the value is never read; `'peer'` is the inert choice because it
892
- // consults no request header at all.
1424
+ // `clientIpSource` has no default and `validateClientIpSource` refused a deployment that left it
1425
+ // unset with limiting on. The fallback is reached only when limiting is OFF, where the value is
1426
+ // never read; `'peer'` is the inert choice because it consults no request header at all.
893
1427
  rateLimit: {
894
1428
  ...DEFAULT_OPTIONS.rateLimit,
895
1429
  ...userOptions.rateLimit,
896
- // Stryker disable next-line OptionalChaining: unreachable — `validateClientIpSource` has
897
- // already run, and it only returns without throwing when `rateLimit` is an object (either
898
- // naming a source or disabling limiting), so `rateLimit` is never undefined here
1430
+ // Stryker disable next-line OptionalChaining: unreachable — `validateClientIpSource` has run, and
1431
+ // it returns only when `rateLimit` is an object (naming a source or disabling limiting)
899
1432
  clientIpSource: userOptions.rateLimit?.clientIpSource ?? "peer"
900
1433
  },
901
1434
  environment: userOptions.environment ?? "production",
@@ -960,7 +1493,7 @@ function validateClientIpSource(rateLimit) {
960
1493
  if (rateLimit?.clientIpSource === "peer" || rateLimit?.clientIpSource === "trusted-proxy") {
961
1494
  return;
962
1495
  }
963
- 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.`);
1496
+ 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.`);
964
1497
  }
965
1498
  __name(validateClientIpSource, "validateClientIpSource");
966
1499
  function validateTenantBinding(userOptions) {
@@ -1067,6 +1600,7 @@ function validateRolesHierarchy(roles) {
1067
1600
  }
1068
1601
  const allRoles = new Set(Object.keys(roles.hierarchy));
1069
1602
  for (const [role, children] of Object.entries(roles.hierarchy)) {
1603
+ assertArray(`roles.hierarchy['${role}']`, children);
1070
1604
  for (const child of children) {
1071
1605
  if (!allRoles.has(child)) {
1072
1606
  throw new Error(`[BymaxAuthModule] roles.hierarchy['${role}'] references unknown role '${child}'. All roles referenced as children must be declared as keys in the hierarchy.`);
@@ -1081,24 +1615,16 @@ function validatePlatformAdmin(platform, roles) {
1081
1615
  }
1082
1616
  }
1083
1617
  __name(validatePlatformAdmin, "validatePlatformAdmin");
1084
- function validatePasswordResetOtpLength(passwordReset) {
1085
- const otpLength = passwordReset?.otpLength;
1086
- if (otpLength === void 0) return;
1087
- if (otpLength < 4 || otpLength > 8) {
1088
- 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.`);
1089
- }
1090
- }
1091
- __name(validatePasswordResetOtpLength, "validatePasswordResetOtpLength");
1092
1618
  function assertIntegralScryptParameter(name, value) {
1093
1619
  if (value === void 0 || Number.isInteger(value)) return;
1094
- 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.`);
1620
+ 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.`);
1095
1621
  }
1096
1622
  __name(assertIntegralScryptParameter, "assertIntegralScryptParameter");
1097
1623
  function validatePasswordMinLength(password) {
1098
1624
  const minLength = password?.minLength;
1099
1625
  if (minLength === void 0) return;
1100
1626
  if (!Number.isInteger(minLength) || minLength < 8 || minLength > 128) {
1101
- 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.`);
1627
+ 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.`);
1102
1628
  }
1103
1629
  }
1104
1630
  __name(validatePasswordMinLength, "validatePasswordMinLength");
@@ -1107,24 +1633,20 @@ function validatePasswordCostFactor(password) {
1107
1633
  if (costFactor === void 0) return;
1108
1634
  assertIntegralScryptParameter("costFactor", costFactor);
1109
1635
  if (costFactor < 16384) {
1110
- 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).`);
1636
+ 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).`);
1111
1637
  }
1112
1638
  if ((costFactor & costFactor - 1) !== 0) {
1113
- throw new Error(`[BymaxAuthModule] password.costFactor must be a power of 2 (current: ${costFactor}).`);
1639
+ throw new Error(`[BymaxAuthModule] password.costFactor must be a power of 2 (received ${describeReceived(costFactor)}).`);
1114
1640
  }
1115
1641
  }
1116
1642
  __name(validatePasswordCostFactor, "validatePasswordCostFactor");
1117
1643
  function validateBruteForce(bruteForce) {
1118
- const windowSeconds = bruteForce?.windowSeconds;
1119
- if (windowSeconds !== void 0 && (!Number.isInteger(windowSeconds) || windowSeconds < 1)) {
1120
- 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.`);
1121
- }
1122
1644
  const maxAttempts = bruteForce?.maxAttempts;
1123
1645
  if (maxAttempts !== void 0 && (!Number.isInteger(maxAttempts) || maxAttempts < 1)) {
1124
- 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".`);
1646
+ 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".`);
1125
1647
  }
1126
1648
  if (maxAttempts !== void 0 && maxAttempts > MAX_BRUTE_FORCE_ATTEMPTS) {
1127
- 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.`);
1649
+ 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.`);
1128
1650
  }
1129
1651
  }
1130
1652
  __name(validateBruteForce, "validateBruteForce");
@@ -1134,12 +1656,12 @@ function validatePasswordMemoryParameters(password) {
1134
1656
  const blockSize = password?.blockSize;
1135
1657
  assertIntegralScryptParameter("blockSize", blockSize);
1136
1658
  if (blockSize !== void 0 && blockSize < 8) {
1137
- 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.`);
1659
+ 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.`);
1138
1660
  }
1139
1661
  const parallelization = password?.parallelization;
1140
1662
  assertIntegralScryptParameter("parallelization", parallelization);
1141
1663
  if (parallelization !== void 0 && parallelization < 1) {
1142
- throw new Error(`[BymaxAuthModule] password.parallelization must be at least 1 (current: ${parallelization}).`);
1664
+ throw new Error(`[BymaxAuthModule] password.parallelization must be at least 1 (received ${describeReceived(parallelization)}).`);
1143
1665
  }
1144
1666
  const effectiveN = password?.costFactor ?? DEFAULT_OPTIONS.password.costFactor;
1145
1667
  const effectiveR = password?.blockSize ?? DEFAULT_OPTIONS.password.blockSize;
@@ -1149,17 +1671,6 @@ function validatePasswordMemoryParameters(password) {
1149
1671
  }
1150
1672
  }
1151
1673
  __name(validatePasswordMemoryParameters, "validatePasswordMemoryParameters");
1152
- function validateMfaVerificationParameters(mfa) {
1153
- const totpWindow = mfa?.totpWindow;
1154
- if (totpWindow !== void 0 && (totpWindow < 0 || totpWindow > MAX_VERIFY_WINDOW)) {
1155
- 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.`);
1156
- }
1157
- const recoveryCodeCount = mfa?.recoveryCodeCount;
1158
- if (recoveryCodeCount !== void 0 && (recoveryCodeCount < 1 || recoveryCodeCount > 50)) {
1159
- 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.`);
1160
- }
1161
- }
1162
- __name(validateMfaVerificationParameters, "validateMfaVerificationParameters");
1163
1674
  var REQUIRED_OAUTH_FIELDS = [
1164
1675
  "clientId",
1165
1676
  "clientSecret",
@@ -1170,6 +1681,7 @@ function validateOAuthProviders(oauth, isProduction) {
1170
1681
  for (const [providerOrField, rawConfig] of Object.entries(oauth)) {
1171
1682
  if (providerOrField === "successRedirectUrl" || providerOrField === "mfaRedirectUrl" || providerOrField === "errorRedirectUrl") continue;
1172
1683
  const provider = providerOrField;
1684
+ assertObject(`oauth.${provider}`, rawConfig);
1173
1685
  const config = rawConfig;
1174
1686
  for (const field of REQUIRED_OAUTH_FIELDS) {
1175
1687
  if (!config[field]) {
@@ -1178,7 +1690,7 @@ function validateOAuthProviders(oauth, isProduction) {
1178
1690
  }
1179
1691
  const callbackUrl = config["callbackUrl"];
1180
1692
  if (typeof callbackUrl === "string" && !callbackUrl.startsWith("https://") && isProduction) {
1181
- throw new Error(`[BymaxAuthModule] oauth.${provider}.callbackUrl must use HTTPS in production (got: '${callbackUrl}'). Use an HTTPS URL to prevent authorization code interception.`);
1693
+ throw new Error(`[BymaxAuthModule] oauth.${provider}.callbackUrl must use HTTPS in production (received a string). Use an HTTPS URL to prevent authorization code interception.`);
1182
1694
  }
1183
1695
  }
1184
1696
  }
@@ -1192,7 +1704,7 @@ function validateOAuthSuccessRedirectUrl(userOptions) {
1192
1704
  const isProduction = isProductionDeployment(userOptions);
1193
1705
  const isSafe = url.startsWith("/") || url.startsWith("https://");
1194
1706
  if (isProduction && !isSafe) {
1195
- throw new Error(`[BymaxAuthModule] oauth.successRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (got: '${url}').`);
1707
+ throw new Error(`[BymaxAuthModule] oauth.successRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (received a string).`);
1196
1708
  }
1197
1709
  if (userOptions.tokenDelivery === "bearer") {
1198
1710
  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.`);
@@ -1208,7 +1720,7 @@ function validateOAuthMfaRedirectUrl(userOptions) {
1208
1720
  const isProduction = isProductionDeployment(userOptions);
1209
1721
  const isSafe = url.startsWith("/") || url.startsWith("https://");
1210
1722
  if (isProduction && !isSafe) {
1211
- throw new Error(`[BymaxAuthModule] oauth.mfaRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (got: '${url}').`);
1723
+ throw new Error(`[BymaxAuthModule] oauth.mfaRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (received a string).`);
1212
1724
  }
1213
1725
  }
1214
1726
  __name(validateOAuthMfaRedirectUrl, "validateOAuthMfaRedirectUrl");
@@ -1221,7 +1733,7 @@ function validateOAuthErrorRedirectUrl(userOptions) {
1221
1733
  const isProduction = isProductionDeployment(userOptions);
1222
1734
  const isSafe = url.startsWith("/") || url.startsWith("https://");
1223
1735
  if (isProduction && !isSafe) {
1224
- throw new Error(`[BymaxAuthModule] oauth.errorRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (got: '${url}').`);
1736
+ throw new Error(`[BymaxAuthModule] oauth.errorRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (received a string).`);
1225
1737
  }
1226
1738
  }
1227
1739
  __name(validateOAuthErrorRedirectUrl, "validateOAuthErrorRedirectUrl");
@@ -1303,30 +1815,14 @@ function isAbsoluteOrigin(value) {
1303
1815
  }
1304
1816
  }
1305
1817
  __name(isAbsoluteOrigin, "isAbsoluteOrigin");
1306
- var MAX_REFRESH_GRACE_WINDOW_SECONDS = 300;
1307
- function validateRefreshGraceWindow(jwt) {
1308
- const graceSeconds = jwt.refreshGraceWindowSeconds ?? DEFAULT_OPTIONS.jwt.refreshGraceWindowSeconds;
1309
- const refreshExpiresInDays = jwt.refreshExpiresInDays ?? DEFAULT_OPTIONS.jwt.refreshExpiresInDays;
1310
- const refreshLifetimeSeconds = refreshExpiresInDays * 86400;
1311
- if (!Number.isFinite(refreshExpiresInDays) || refreshExpiresInDays <= 0) {
1312
- 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.`);
1313
- }
1314
- if (graceSeconds >= refreshLifetimeSeconds) {
1315
- 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.`);
1316
- }
1317
- if (graceSeconds < 0 || graceSeconds > MAX_REFRESH_GRACE_WINDOW_SECONDS) {
1318
- 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.`);
1319
- }
1320
- }
1321
- __name(validateRefreshGraceWindow, "validateRefreshGraceWindow");
1322
1818
  function validateAccessLifetimeAgainstEpochRetention(jwt) {
1323
1819
  const configured = jwt.accessExpiresIn ?? DEFAULT_OPTIONS.jwt.accessExpiresIn;
1324
1820
  const seconds = durationToSeconds(configured);
1325
1821
  if (seconds === void 0) {
1326
- throw new Error(`[BymaxAuthModule] jwt.accessExpiresIn must be a time span such as '15m', '1h' or '900s'. Got: '${configured}'. A value the signer cannot read would fail at the first token issued, and leaves the token-epoch retention bound unverifiable at startup.`);
1822
+ throw new Error(`[BymaxAuthModule] jwt.accessExpiresIn must be a time span such as '15m', '1h' or '900s'. Received ${describeReceived(configured)}. A value the signer cannot read would fail at the first token issued, and leaves the token-epoch retention bound unverifiable at startup.`);
1327
1823
  }
1328
1824
  if (seconds > TOKEN_EPOCH_RETENTION_SECONDS) {
1329
- throw new Error(`[BymaxAuthModule] jwt.accessExpiresIn ('${configured}' = ${seconds} s) must not exceed the token-epoch retention window (${TOKEN_EPOCH_RETENTION_SECONDS} s). An access token that outlives the stored epoch would survive the password reset that revoked it: the epoch lookup falls back to 0 once the record expires, and the staleness check stops firing.`);
1825
+ throw new Error(`[BymaxAuthModule] jwt.accessExpiresIn (${seconds} s) must not exceed the token-epoch retention window (${TOKEN_EPOCH_RETENTION_SECONDS} s). An access token that outlives the stored epoch would survive the password reset that revoked it: the epoch lookup falls back to 0 once the record expires, and the staleness check stops firing.`);
1330
1826
  }
1331
1827
  }
1332
1828
  __name(validateAccessLifetimeAgainstEpochRetention, "validateAccessLifetimeAgainstEpochRetention");
@@ -24272,6 +24768,7 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
24272
24768
  */
24273
24769
  static registerAsync(options) {
24274
24770
  const extraProviders = options.extraProviders ?? [];
24771
+ validateRegistrationShapes(options.controllers, extraProviders);
24275
24772
  if (!hasProviderToken(extraProviders, BYMAX_AUTH_USER_REPOSITORY)) {
24276
24773
  throw new Error("[BymaxAuthModule] BYMAX_AUTH_USER_REPOSITORY is required in extraProviders. Provide your IUserRepository implementation: { provide: BYMAX_AUTH_USER_REPOSITORY, useClass: YourUserRepository }.");
24277
24774
  }
@@ -24884,7 +25381,7 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
24884
25381
  this.sink = sink;
24885
25382
  this.messages = {
24886
25383
  ...DEFAULT_MESSAGES,
24887
- ...options?.messages
25384
+ ...dropUnsetKeys(options?.messages ?? {})
24888
25385
  };
24889
25386
  const configured = options?.onDeliveryError;
24890
25387
  this.deliveryErrorPolicy = new Map(typeof configured === "string" ? AUTH_EMAIL_KINDS.map((kind) => [