@bymax-one/nest-auth 1.5.12 → 1.5.14

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.
package/CHANGELOG.md CHANGED
@@ -18,6 +18,89 @@ what moves, and that note is the compatibility contract until strict SemVer begi
18
18
 
19
19
  ## [Unreleased]
20
20
 
21
+ ## [1.5.14] - 2026-11-22
22
+
23
+ A patch release.
24
+
25
+ ### Fixed
26
+
27
+ - **The lists a host keeps in its options are read once and what is checked is what is kept.** The permissions of the
28
+ workspaces (`manageWorkspace`, `deleteWorkspace`, `manageMembers`, `viewMembers`) were validated through their own
29
+ entries and then read again by property and kept as the host's arrays: a typed configuration class that served them on
30
+ its prototype was never validated, and a change by the host after start reached the authorization table. They are read
31
+ by property like the other groups and kept as copies, and so are `jwt.previousSecrets`,
32
+ `mfa.previousEncryptionKeys` and `apiKeys.scopes`, whose strength and format checks ran once at start.
33
+ `jwt`, `mfa`, `apiKeys` and `workspaces.permissions` must be objects: a function, an array or a primitive given for
34
+ one is refused with `[BymaxAuthModule] <option> must be an object (received …)`.
35
+ - **The id of a row is required.** The ids of a user, a platform user, an API key, a workspace and of a membership (its
36
+ workspace and its user) were accepted when absent or `null`, so a row without an id logged in with a token whose
37
+ subject was nothing. Each is refused as `auth.internal` when it is absent, `undefined` or `null`; an id that
38
+ is optional by design, such as the user that invited a member, is still accepted when absent.
39
+ - **A resend of the verification code gives the cooldown back when the code cannot be stored.** The write of the code
40
+ to the store was the one failure on the path that the response had not left yet and that kept the cooldown. A request
41
+ that finds no account, or an account that is already verified, still keeps it, so the throttle never tells the two
42
+ apart. A mail provider that fails after the response left does not release it: a delete by key from there could remove
43
+ the cooldown of a later request, so the user retries after the minute.
44
+ - **The hierarchy of the platform is judged as the others are.** When the platform is enabled, `roles.platformHierarchy`
45
+ must be an object that names at least one role, whose children are lists of roles it declares (a string, a number, a
46
+ child that is no list or a child nobody declares ends the boot with the option and the role named).
47
+ - **An id is never blank, the text of a missing value, an error or a buffer.** A string or a printed text that is empty
48
+ or only whitespace, `undefined` or `null`, and an `Error`, a `Buffer` or any other view of bytes, are refused as an id
49
+ with `auth.internal`.
50
+ - **The ids of the rows the workspace access reads are compared with the ones asked about.** The id of the workspace, the
51
+ workspace of the membership and the user of the membership are compared exactly, as the tenant already was; a
52
+ repository that answers another row is denied access and nothing is cached. **Apply to a derived backend:** the ids
53
+ are compared as the exact strings the library keeps, so a store that normalises an id when it reads it (a column that
54
+ lowercases a uuid) has to be asked for the id in the form it returns, or it answers a row that is denied.
55
+
56
+ ## [1.5.13] - 2026-11-21
57
+
58
+ A patch release.
59
+
60
+ ### Fixed
61
+
62
+ - **A tenant is read as a string and as nothing else.** The `tenantId` of a user, a workspace and a membership was
63
+ accepted as a string or as any instance of a class of the host: a `Date`, a `Map`, an object that inherits from a
64
+ plain object, a class that only has `toString`. Comparisons with the tenant of a request already failed closed, but
65
+ the value is written into the claims of a token, where two tenants whose ids are objects both serialize to `{}`. Any
66
+ value that is not a string now ends as `auth.internal`. **Apply to a derived backend:** a repository that serves the
67
+ tenant as an object (an id type of a driver) has to serve it as a string.
68
+ - **The time of a real date is the time it holds.** A subclass of `Date` that overrides `getTime` was asked for its
69
+ time, so a host could name a deadline other than the one the date carries. A real date is read through
70
+ `Date.prototype.getTime`; a Proxy of a date, which has no slot, is still read through its own `getTime`.
71
+ - **A read follows a bounded number of nodes in all.** The cap of 100 000 elements or keys applied to each array and
72
+ each object, so a list of records that each stayed under it could still make a copy walk as many nodes as the host
73
+ served. A read now follows at most 1 000 000 nodes (the elements of lists, the own keys of records and the strings of
74
+ lists of strings); an answer that holds more ends as `auth.internal`.
75
+ - **Access to a workspace is refused when the repository answers with a row of another tenant.** The workspace and the
76
+ membership read for a tenant, a workspace and a user are now checked to carry the tenant that was asked about; the
77
+ key given to a repository is not a proof of the row it returned.
78
+ - **An id names one row, and the library keeps it as a string.** The ids of users, workspaces and memberships were
79
+ accepted as a string, a finite number or any instance of a class of the host, so a `Map` or a `Date` was an id, and
80
+ two of them printed the same in a claim, a key or the scope of a query. An id is now a non-empty string, a safe
81
+ integer, or an object of the host that prints as a non-empty text of its own, and what the library keeps is the text
82
+ it prints as, read once. A `Date`, a `RegExp`, a `Map`, a `Set`, a `Promise`, an array, a plain object, a function, a
83
+ boolean, a fraction, an integer past the safe range and an object that prints as nothing or as `[object ...]` end as
84
+ `auth.internal`. An account whose id is a number now works after the login: the token's subject was the number, which
85
+ the verifier refuses, so `/me`, a refresh and a password change answered 401 for an account that had just logged in.
86
+ **Apply to a derived backend:** the library hands the repository the id as a string (it always did, from the token),
87
+ so a repository keyed by a number has to accept the string; a repository that serves a numeric id as a fraction or
88
+ past 2^53 has to serve it as a string. A hook that receives a user now sees the id as its string form (a host
89
+ callback that receives the host's own entity, such as `maxSessionsResolver`, still gets the object as it was).
90
+ - **The secret that signs is the secret that was checked, and the role hierarchies are read once.** The signer is
91
+ configured by a second call of the host's options factory, and what that call answered was the secret that signed
92
+ and verified: a factory that answered a weak secret the second time passed the strength check on the first answer and
93
+ signed with the weak one. Every sign and every verify now names the secret the options resolved to. The role
94
+ hierarchies (`roles.hierarchy`, `roles.platformHierarchy` and `workspaces.roles.hierarchy`) were kept as the host's
95
+ own objects and read through its getters at every check; each is read once, as plain data, so a getter that answers
96
+ differently later cannot grant a role that was never validated. `roles`, `workspaces` and `workspaces.roles` must be objects: a
97
+ function, an array or a primitive given for one is refused with `[BymaxAuthModule] <option> must be an object
98
+ (received …)`, as the other option groups already were.
99
+ - **A resend of the verification code that fails gives the cooldown back.** The request took the one-minute cooldown
100
+ before it looked the account up, so a request that failed there (a repository that throws, or answers with a record the
101
+ copy refuses) left the retry it invites refused for the rest of the minute. A request that took the cooldown and failed
102
+ releases it, as the password reset request already did; a request that sent, or found the cooldown taken, keeps it.
103
+
21
104
  ## [1.5.12] - 2026-11-21
22
105
 
23
106
  A patch release.
@@ -5512,7 +5595,9 @@ ever installable.
5512
5595
  - Phase 4 password-reset tests cover: both `token` and `otp` flows, mutual exclusivity validation, `verifiedToken` exchange, resend cooldown, anti-enumeration (no error on unknown email), and session invalidation on reset
5513
5596
  - Phase 5 tests cover: platform login with MFA path and brute-force lockout, `JwtPlatformGuard` cross-context rejection, `PlatformRolesGuard` hierarchy enforcement, OAuth CSRF state lifecycle, `onOAuthLogin` hook resolution strategies, and invitation role-authorization + acceptance single-use enforcement
5514
5597
 
5515
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.5.12...HEAD
5598
+ [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.5.14...HEAD
5599
+ [1.5.14]: https://github.com/bymaxone/nest-auth/compare/v1.5.13...v1.5.14
5600
+ [1.5.13]: https://github.com/bymaxone/nest-auth/compare/v1.5.12...v1.5.13
5516
5601
  [1.5.12]: https://github.com/bymaxone/nest-auth/compare/v1.5.11...v1.5.12
5517
5602
  [1.5.11]: https://github.com/bymaxone/nest-auth/compare/v1.5.10...v1.5.11
5518
5603
  [1.5.10]: https://github.com/bymaxone/nest-auth/compare/v1.5.9...v1.5.10
package/README.md CHANGED
@@ -1408,9 +1408,9 @@ With `@opentelemetry/api` installed and an SDK registered, each of these routes
1408
1408
 
1409
1409
  | Span | Routes |
1410
1410
  | --------------------- | ----------------------------------------------------------------- |
1411
- | `auth.login` | `POST /login`, `POST /platform/auth/login` |
1412
- | `auth.refresh` | `POST /refresh`, `POST /platform/auth/refresh` |
1413
- | `auth.mfa.verify` | `POST /mfa/challenge`, `POST /platform/auth/mfa/challenge` |
1411
+ | `auth.login` | `POST /login`, `POST /platform/login` |
1412
+ | `auth.refresh` | `POST /refresh`, `POST /platform/refresh` |
1413
+ | `auth.mfa.verify` | `POST /mfa/challenge`, `POST /platform/mfa/challenge` |
1414
1414
  | `auth.password_reset` | `POST /password/forgot-password`, `POST /password/reset-password` |
1415
1415
 
1416
1416
  ### Readiness
@@ -1494,7 +1494,7 @@ A Nest `Logger` calls the host logger and discards what it returns, so a host lo
1494
1494
  The fields that name a step come from sets the library owns, typed in the code and listed here; none is ever text a host or a store wrote.
1495
1495
 
1496
1496
  - **`hook`** of `AUTH_HOOK_FAILED`: `beforeRegister`, `afterRegister`, `beforeLogin`, `afterLogin`, `afterLogout`, `afterPlatformLogout`, `onLoginFailed`, `onLockout`, `onRefreshTokenReuseDetected`, `afterMfaEnabled`, `afterMfaDisabled`, `afterMfaRecoveryCodesRegenerated`, `onNewSession`, `afterEmailVerified`, `afterPasswordReset`, `onOAuthLogin`, `afterInvitationAccepted`, `onSessionEvicted`, `onApiKeyRequest`, `beforeWorkspaceCreate`, `onWorkspaceEvent`, `updateLastLogin`, `accessDenied`, `maxSessionsResolver`.
1497
- - **`operation`** of `AUTH_STORE_FAILED` and `AUTH_STORE_DEGRADED`: `account_status_cache_write`, `api_key_last_used_flush`, `api_key_lookup`, `cache_invalidation`, `dead_member_prune`, `grace_pointer_prune`, `invitation_withdraw`, `logout_marker_clear`, `logout_owner_keep`, `mfa_lock_release`, `mfa_reencryption`, `new_session_user_lookup`, `rehash_on_verify`, `reset_account_lookup`, `reset_cooldown_release`, `reset_cooldown_store`, `reset_issue`, `session_cleanup`, `session_detail_read`, `session_detail_rotation`, `workspace_cache_read`, `workspace_cache_write`.
1497
+ - **`operation`** of `AUTH_STORE_FAILED` and `AUTH_STORE_DEGRADED`: `account_status_cache_write`, `api_key_last_used_flush`, `api_key_lookup`, `cache_invalidation`, `dead_member_prune`, `grace_pointer_prune`, `invitation_withdraw`, `logout_marker_clear`, `logout_owner_keep`, `mfa_lock_release`, `mfa_reencryption`, `new_session_user_lookup`, `rehash_on_verify`, `resend_cooldown_release`, `reset_account_lookup`, `reset_cooldown_release`, `reset_cooldown_store`, `reset_issue`, `session_cleanup`, `session_detail_read`, `session_detail_rotation`, `workspace_cache_read`, `workspace_cache_write`.
1498
1498
  - **`kind`** of `AUTH_DELIVERY_FAILED`: `passwordResetToken`, `passwordResetOtp`, `emailVerificationOtp`, `passwordChanged`, `emailChangeVerification`, `emailChanged`, `mfaEnabled`, `mfaDisabled`, `newSessionAlert`, `invitation`, `workspaceInvitation`, `email_verification_otp`, `password_changed_notice`, `password_reset_token`, `password_reset_otp`, `mfa_enabled_notice`, `mfa_disabled_notice`, `mfa_reset_notice`, `email_change_notice`.
1499
1499
 
1500
1500
  ---
@@ -830,7 +830,14 @@ var OBJECT_GROUPS = [
830
830
  "platform",
831
831
  "invitations",
832
832
  "emailChange",
833
- "oauth"
833
+ "oauth",
834
+ "roles",
835
+ "workspaces",
836
+ "workspaces.roles",
837
+ "workspaces.permissions",
838
+ "jwt",
839
+ "mfa",
840
+ "apiKeys"
834
841
  ];
835
842
  function readPath2(root, path) {
836
843
  let node = root;
@@ -1027,6 +1034,16 @@ var WORKSPACE_SUBGROUP_KEYS = {
1027
1034
  accessDeniedEvents: [
1028
1035
  "max",
1029
1036
  "windowSeconds"
1037
+ ],
1038
+ roles: [
1039
+ "hierarchy",
1040
+ "ownerRole"
1041
+ ],
1042
+ permissions: [
1043
+ "manageWorkspace",
1044
+ "deleteWorkspace",
1045
+ "manageMembers",
1046
+ "viewMembers"
1030
1047
  ]
1031
1048
  };
1032
1049
  function isObjectGroup(value) {
@@ -1076,7 +1093,7 @@ function dropUnset(options) {
1076
1093
  if (name === "workspaces") {
1077
1094
  for (const [sub, subKeys] of Object.entries(WORKSPACE_SUBGROUP_KEYS)) {
1078
1095
  const inner = group[sub];
1079
- if (isObjectGroup(inner)) group[sub] = readSetKeys(inner, subKeys);
1096
+ if (isObjectGroup(inner)) group[sub] = (sub === "accessDeniedEvents" ? readSetKeys : readKeptKeys)(inner, subKeys);
1080
1097
  }
1081
1098
  }
1082
1099
  copy[name] = group;
@@ -1100,15 +1117,127 @@ __name(dropUnset, "dropUnset");
1100
1117
  function readOptions(given) {
1101
1118
  const options = dropUnset(given);
1102
1119
  validateTextOptions(options);
1103
- return options;
1120
+ return pinCopied(options);
1104
1121
  }
1105
1122
  __name(readOptions, "readOptions");
1123
+ function copyHierarchy(held) {
1124
+ if (Object(held) !== held) return held;
1125
+ return Object.fromEntries(Object.entries(held).map(([role, children]) => [
1126
+ role,
1127
+ Array.isArray(children) ? [
1128
+ ...children
1129
+ ] : children
1130
+ ]));
1131
+ }
1132
+ __name(copyHierarchy, "copyHierarchy");
1133
+ function copyList(held) {
1134
+ return Array.isArray(held) ? [
1135
+ ...held
1136
+ ] : held;
1137
+ }
1138
+ __name(copyList, "copyList");
1139
+ var COPIED = [
1140
+ {
1141
+ path: [
1142
+ "roles"
1143
+ ],
1144
+ keys: [
1145
+ "hierarchy",
1146
+ "platformHierarchy"
1147
+ ],
1148
+ copy: copyHierarchy
1149
+ },
1150
+ {
1151
+ path: [
1152
+ "workspaces",
1153
+ "roles"
1154
+ ],
1155
+ keys: [
1156
+ "hierarchy"
1157
+ ],
1158
+ copy: copyHierarchy
1159
+ },
1160
+ {
1161
+ path: [
1162
+ "workspaces",
1163
+ "permissions"
1164
+ ],
1165
+ keys: [
1166
+ "manageWorkspace",
1167
+ "deleteWorkspace",
1168
+ "manageMembers",
1169
+ "viewMembers"
1170
+ ],
1171
+ copy: copyList
1172
+ },
1173
+ {
1174
+ path: [
1175
+ "jwt"
1176
+ ],
1177
+ keys: [
1178
+ "previousSecrets"
1179
+ ],
1180
+ copy: copyList
1181
+ },
1182
+ {
1183
+ path: [
1184
+ "mfa"
1185
+ ],
1186
+ keys: [
1187
+ "previousEncryptionKeys"
1188
+ ],
1189
+ copy: copyList
1190
+ },
1191
+ {
1192
+ path: [
1193
+ "apiKeys"
1194
+ ],
1195
+ keys: [
1196
+ "scopes"
1197
+ ],
1198
+ copy: copyList
1199
+ }
1200
+ ];
1201
+ function pinCopied(options) {
1202
+ for (const { path, keys, copy } of COPIED) {
1203
+ let group = options;
1204
+ for (const step of path) group = Object(group) === group ? group[step] : void 0;
1205
+ if (Object(group) !== group) continue;
1206
+ const plain = group;
1207
+ for (const key of keys) if (plain[key] !== void 0) plain[key] = copy(plain[key]);
1208
+ }
1209
+ return options;
1210
+ }
1211
+ __name(pinCopied, "pinCopied");
1106
1212
  function validateOptionValues(userOptions) {
1107
1213
  validateNumericOptions(userOptions);
1108
1214
  validateEnumAndBooleanOptions(userOptions);
1109
1215
  }
1110
1216
  __name(validateOptionValues, "validateOptionValues");
1111
1217
 
1218
+ // src/server/config/platform-options.ts
1219
+ function validatePlatformAdmin(platform, roles) {
1220
+ if (!platform?.enabled) return;
1221
+ const hierarchy = roles.platformHierarchy;
1222
+ if (!hierarchy) {
1223
+ throw new Error(`[BymaxAuthModule] roles.platformHierarchy is required when platform.enabled is true. Define the platform role hierarchy (e.g. { SUPER_ADMIN: ['SUPPORT'], SUPPORT: [] }).`);
1224
+ }
1225
+ assertObject("roles.platformHierarchy", hierarchy);
1226
+ const names = new Set(Object.keys(hierarchy));
1227
+ if (names.size === 0) {
1228
+ throw new Error(`[BymaxAuthModule] roles.platformHierarchy must not be an empty object. Define at least one role (e.g. { SUPER_ADMIN: [] }).`);
1229
+ }
1230
+ for (const [role, children] of Object.entries(hierarchy)) {
1231
+ assertArray(`roles.platformHierarchy['${role}']`, children);
1232
+ for (const child of children) {
1233
+ if (!names.has(child)) {
1234
+ throw new Error(`[BymaxAuthModule] roles.platformHierarchy['${role}'] references unknown role '${child}'. All roles referenced as children must be declared as keys in the hierarchy.`);
1235
+ }
1236
+ }
1237
+ }
1238
+ }
1239
+ __name(validatePlatformAdmin, "validatePlatformAdmin");
1240
+
1112
1241
  // src/server/constants/workspace-roles.ts
1113
1242
  var ANY_WORKSPACE_MEMBER = /* @__PURE__ */ Symbol("ANY_WORKSPACE_MEMBER");
1114
1243
 
@@ -1711,12 +1840,6 @@ function validateRolesHierarchy(roles) {
1711
1840
  }
1712
1841
  }
1713
1842
  __name(validateRolesHierarchy, "validateRolesHierarchy");
1714
- function validatePlatformAdmin(platform, roles) {
1715
- if (platform?.enabled && !roles.platformHierarchy) {
1716
- throw new Error(`[BymaxAuthModule] roles.platformHierarchy is required when platform.enabled is true. Define the platform role hierarchy (e.g. { SUPER_ADMIN: ['SUPPORT'], SUPPORT: [] }).`);
1717
- }
1718
- }
1719
- __name(validatePlatformAdmin, "validatePlatformAdmin");
1720
1843
  function assertIntegralScryptParameter(name, value) {
1721
1844
  if (value === void 0 || Number.isInteger(value)) return;
1722
1845
  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.`);
@@ -5435,26 +5558,34 @@ function malformedRefreshToken() {
5435
5558
  __name(malformedRefreshToken, "malformedRefreshToken");
5436
5559
 
5437
5560
  // src/server/utils/verify-with-rotation.ts
5561
+ function signerOf(options) {
5562
+ return {
5563
+ secret: options.jwt.secret,
5564
+ algorithm: options.jwt.algorithm
5565
+ };
5566
+ }
5567
+ __name(signerOf, "signerOf");
5438
5568
  function verifyWithRotation(jwtService, options, token, { ignoreExpiration = false } = {}) {
5439
5569
  const algorithms = [
5440
5570
  options.jwt.algorithm
5441
5571
  ];
5442
- const { issuer, audience } = options.jwt;
5572
+ const { issuer, audience, secret } = options.jwt;
5443
5573
  const base = {
5444
5574
  algorithms,
5445
5575
  ignoreExpiration,
5446
5576
  issuer,
5447
- audience
5577
+ audience,
5578
+ secret
5448
5579
  };
5449
5580
  try {
5450
5581
  return jwtService.verify(token, base);
5451
5582
  } catch (currentFailure) {
5452
5583
  const previous = options.jwt.previousSecrets ?? [];
5453
- for (const secret of previous) {
5584
+ for (const secret2 of previous) {
5454
5585
  try {
5455
5586
  return jwtService.verify(token, {
5456
5587
  ...base,
5457
- secret
5588
+ secret: secret2
5458
5589
  });
5459
5590
  } catch {
5460
5591
  }
@@ -6649,6 +6780,18 @@ function _ts_param11(paramIndex, decorator) {
6649
6780
  };
6650
6781
  }
6651
6782
  __name(_ts_param11, "_ts_param");
6783
+ async function releasingCooldownOnFailure(redis, logger, cooldownKey, work) {
6784
+ const release = /* @__PURE__ */ __name(() => redis.del(cooldownKey).then(() => void 0, (err) => {
6785
+ logStore(logger, "AUTH_STORE_FAILED", "resend_cooldown_release", err);
6786
+ }), "release");
6787
+ try {
6788
+ if (await work() === false) await release();
6789
+ } catch (error) {
6790
+ await release();
6791
+ throw error;
6792
+ }
6793
+ }
6794
+ __name(releasingCooldownOnFailure, "releasingCooldownOnFailure");
6652
6795
  var MAX_ATTEMPTS = 5;
6653
6796
  var MIN_VERIFY_MS = 100;
6654
6797
  var OTP_STORE_LUA = `
@@ -7159,8 +7302,8 @@ PasswordService = _ts_decorate20([
7159
7302
  var RECORD_CONTRACTS = {
7160
7303
  workspace: {
7161
7304
  fields: {
7162
- id: "~id",
7163
- tenantId: "id",
7305
+ id: "id",
7306
+ tenantId: "string",
7164
7307
  name: "~string",
7165
7308
  status: "string",
7166
7309
  createdAt: "~date",
@@ -7170,9 +7313,9 @@ var RECORD_CONTRACTS = {
7170
7313
  },
7171
7314
  membership: {
7172
7315
  fields: {
7173
- tenantId: "id",
7174
- workspaceId: "~id",
7175
- userId: "~id",
7316
+ tenantId: "string",
7317
+ workspaceId: "id",
7318
+ userId: "id",
7176
7319
  role: "string",
7177
7320
  status: "string",
7178
7321
  invitedByUserId: "~id",
@@ -7183,13 +7326,13 @@ var RECORD_CONTRACTS = {
7183
7326
  },
7184
7327
  user: {
7185
7328
  fields: {
7186
- id: "~id",
7329
+ id: "id",
7187
7330
  email: "~string",
7188
7331
  name: "~string",
7189
7332
  passwordHash: "string|null",
7190
7333
  role: "string",
7191
7334
  status: "string",
7192
- tenantId: "id",
7335
+ tenantId: "string",
7193
7336
  emailVerified: "boolean",
7194
7337
  mfaEnabled: "boolean",
7195
7338
  mfaSecret: "string?",
@@ -7203,7 +7346,7 @@ var RECORD_CONTRACTS = {
7203
7346
  },
7204
7347
  platformUser: {
7205
7348
  fields: {
7206
- id: "~id",
7349
+ id: "id",
7207
7350
  email: "~string",
7208
7351
  name: "~string",
7209
7352
  passwordHash: "string",
@@ -7221,7 +7364,7 @@ var RECORD_CONTRACTS = {
7221
7364
  },
7222
7365
  apiKey: {
7223
7366
  fields: {
7224
- id: "~id",
7367
+ id: "id",
7225
7368
  label: "~string",
7226
7369
  digest: "string",
7227
7370
  scopes: "strings",
@@ -7234,7 +7377,7 @@ var RECORD_CONTRACTS = {
7234
7377
  },
7235
7378
  removedMembership: {
7236
7379
  fields: {
7237
- workspaceId: "~id",
7380
+ workspaceId: "id",
7238
7381
  role: "string"
7239
7382
  },
7240
7383
  nested: {}
@@ -7373,14 +7516,15 @@ var CREDENTIAL_FIELDS = /* @__PURE__ */ new Set([
7373
7516
 
7374
7517
  // src/server/utils/host-read.ts
7375
7518
  var MAX_BREADTH = 1e5;
7376
- function copiedUnder(seen, value, contract) {
7377
- return seen.get(value)?.get(contract);
7519
+ var MAX_NODES = 1e6;
7520
+ function copiedUnder(read, value, contract) {
7521
+ return read.copies.get(value)?.get(contract);
7378
7522
  }
7379
7523
  __name(copiedUnder, "copiedUnder");
7380
- function rememberUnder(seen, value, contract, copy) {
7381
- const copies = seen.get(value) ?? /* @__PURE__ */ new Map();
7524
+ function rememberUnder(read, value, contract, copy) {
7525
+ const copies = read.copies.get(value) ?? /* @__PURE__ */ new Map();
7382
7526
  copies.set(contract, copy);
7383
- seen.set(value, copies);
7527
+ read.copies.set(value, copies);
7384
7528
  }
7385
7529
  __name(rememberUnder, "rememberUnder");
7386
7530
  function readHostOptions(read) {
@@ -7426,10 +7570,11 @@ function define(copy, key, value, enumerable) {
7426
7570
  }
7427
7571
  __name(define, "define");
7428
7572
  var ENTITIES = /* @__PURE__ */ new WeakMap();
7429
- function refuseBreadth(size) {
7430
- if (size > MAX_BREADTH) throw new Error("the answer holds more than the library follows");
7573
+ function follow(read, size) {
7574
+ read.nodes -= size;
7575
+ if (size > MAX_BREADTH || read.nodes < 0) throw new Error("the answer holds more than the library follows");
7431
7576
  }
7432
- __name(refuseBreadth, "refuseBreadth");
7577
+ __name(follow, "follow");
7433
7578
  function isDateLike(value) {
7434
7579
  return util.types.isDate(value) || util.types.isProxy(value) && value instanceof Date;
7435
7580
  }
@@ -7451,17 +7596,22 @@ function isHostInstance(value) {
7451
7596
  return typeof value === "object" && value !== null && !Array.isArray(value) && !util.types.isBoxedPrimitive(value) && !isPlainObject(value);
7452
7597
  }
7453
7598
  __name(isHostInstance, "isHostInstance");
7599
+ function timeOf(date) {
7600
+ const real = util.types.isDate(date);
7601
+ return real ? Date.prototype.getTime.call(date) : date.getTime();
7602
+ }
7603
+ __name(timeOf, "timeOf");
7454
7604
  function copyDate(value) {
7455
7605
  if (typeof value !== "object" || value === null || !isDateLike(value)) throw new Error(WRONG_KIND);
7456
- const time = value.getTime();
7606
+ const time = timeOf(value);
7457
7607
  const copy = new Date(typeof time === "number" ? time : Number.NaN);
7458
7608
  if (Number.isNaN(copy.getTime())) throw new Error(NOT_A_TIME);
7459
7609
  return copy;
7460
7610
  }
7461
7611
  __name(copyDate, "copyDate");
7462
- function copyStrings(value) {
7612
+ function copyStrings(value, read) {
7463
7613
  if (!Array.isArray(value)) throw new Error(WRONG_KIND);
7464
- refuseBreadth(value.length);
7614
+ follow(read, value.length);
7465
7615
  const copy = [];
7466
7616
  for (let index = 0; index < value.length; index += 1) {
7467
7617
  const element = value[index];
@@ -7470,6 +7620,18 @@ function copyStrings(value) {
7470
7620
  return copy;
7471
7621
  }
7472
7622
  __name(copyStrings, "copyStrings");
7623
+ var NOT_AN_ID_TEXT = /* @__PURE__ */ new Set([
7624
+ "undefined",
7625
+ "null"
7626
+ ]);
7627
+ function readId(value) {
7628
+ if (typeof value === "number") return accept(Number.isSafeInteger(value), String(value));
7629
+ if (typeof value !== "string" && (!isHostInstance(value) || util.types.isDate(value) || util.types.isRegExp(value) || util.types.isNativeError(value) || util.types.isArrayBufferView(value))) throw new Error(WRONG_KIND);
7630
+ const text = String(value);
7631
+ const printed = typeof value !== "string";
7632
+ return accept(text.trim() !== "" && !NOT_AN_ID_TEXT.has(text) && !(printed && text.startsWith("[object ")), text);
7633
+ }
7634
+ __name(readId, "readId");
7473
7635
  function readInforming(value) {
7474
7636
  return accept(typeof value === "string" || Number.isFinite(value) || isHostInstance(value), value);
7475
7637
  }
@@ -7478,7 +7640,7 @@ function readInformingDate(value) {
7478
7640
  if (typeof value === "string" || Number.isFinite(value)) return value;
7479
7641
  if (!isHostInstance(value)) throw new Error(WRONG_KIND);
7480
7642
  if (!isDateLike(value)) return value;
7481
- const time = value.getTime();
7643
+ const time = timeOf(value);
7482
7644
  const copy = new Date(typeof time === "number" ? time : Number.NaN);
7483
7645
  return Number.isNaN(copy.getTime()) ? value : copy;
7484
7646
  }
@@ -7486,11 +7648,11 @@ __name(readInformingDate, "readInformingDate");
7486
7648
  var READERS = {
7487
7649
  boolean: /* @__PURE__ */ __name((value) => accept(typeof value === "boolean", value), "boolean"),
7488
7650
  string: /* @__PURE__ */ __name((value) => accept(typeof value === "string", value), "string"),
7651
+ id: readId,
7489
7652
  number: /* @__PURE__ */ __name((value) => accept(Number.isFinite(value), value), "number"),
7490
- id: /* @__PURE__ */ __name((value) => accept(typeof value === "string" || isHostInstance(value), value), "id"),
7491
7653
  date: copyDate,
7492
7654
  strings: copyStrings,
7493
- "~id": readInforming,
7655
+ "~id": readId,
7494
7656
  "~string": readInforming,
7495
7657
  "~date": readInformingDate
7496
7658
  };
@@ -7511,19 +7673,19 @@ function readNull(nullable) {
7511
7673
  return null;
7512
7674
  }
7513
7675
  __name(readNull, "readNull");
7514
- function readScalar(value, spec) {
7676
+ function readScalar(value, spec, run) {
7515
7677
  const { base, nullable } = parseSpec(spec);
7516
7678
  if (base === "void") return void 0;
7517
- return value === null ? readNull(nullable) : READERS[base](value);
7679
+ return value === null ? readNull(nullable) : READERS[base](value, run);
7518
7680
  }
7519
7681
  __name(readScalar, "readScalar");
7520
- function copyRecord(value, contract, seen) {
7682
+ function copyRecord(value, contract, run) {
7521
7683
  const copy = {};
7522
- rememberUnder(seen, value, contract, copy);
7684
+ rememberUnder(run, value, contract, copy);
7523
7685
  ENTITIES.set(copy, value);
7524
7686
  const source = value;
7525
7687
  const keys = Object.keys(value);
7526
- refuseBreadth(keys.length);
7688
+ follow(run, keys.length);
7527
7689
  for (const key of keys) {
7528
7690
  if (Object.hasOwn(contract.fields, key)) continue;
7529
7691
  const descriptor = Object.getOwnPropertyDescriptor(value, key);
@@ -7532,38 +7694,42 @@ function copyRecord(value, contract, seen) {
7532
7694
  const own = new Set(keys);
7533
7695
  for (const [field, spec] of Object.entries(contract.fields)) {
7534
7696
  const { base, nullable, optional } = parseSpec(spec);
7535
- const read = source[field];
7536
- if (read === void 0) {
7697
+ const held = source[field];
7698
+ if (held === void 0) {
7537
7699
  if (optional) continue;
7538
7700
  throw new Error(ABSENT);
7539
7701
  }
7540
- const copied = read === null ? readNull(nullable || optional) : base === "nested" ? applyContract(read, contract.nested[field], seen) : READERS[base](read);
7702
+ const copied = held === null ? readNull(nullable || optional) : base === "nested" ? applyContract(held, contract.nested[field], run) : READERS[base](held, run);
7541
7703
  define(copy, field, copied, own.has(field) || !CREDENTIAL_FIELDS.has(field));
7542
7704
  }
7543
7705
  return copy;
7544
7706
  }
7545
7707
  __name(copyRecord, "copyRecord");
7546
- function applyContract(value, contract, seen) {
7708
+ function applyContract(value, contract, run) {
7547
7709
  if (typeof value !== "object" || value === null) throw new Error(WRONG_KIND);
7548
- const known = copiedUnder(seen, value, contract);
7710
+ const known = copiedUnder(run, value, contract);
7549
7711
  if (known !== void 0) return known;
7550
7712
  if ("list" in contract) {
7551
7713
  if (!Array.isArray(value)) throw new Error("the answer is not the list its method promises");
7552
- refuseBreadth(value.length);
7714
+ follow(run, value.length);
7553
7715
  const copy = [];
7554
- rememberUnder(seen, value, contract, copy);
7555
- for (let index = 0; index < value.length; index += 1) copy.push(applyContract(value[index], contract.list, seen));
7716
+ rememberUnder(run, value, contract, copy);
7717
+ for (let index = 0; index < value.length; index += 1) copy.push(applyContract(value[index], contract.list, run));
7556
7718
  return copy;
7557
7719
  }
7558
7720
  if (Array.isArray(value)) throw new Error("the answer is not the record its method promises");
7559
- return copyRecord(value, contract, seen);
7721
+ return copyRecord(value, contract, run);
7560
7722
  }
7561
7723
  __name(applyContract, "applyContract");
7562
7724
  function copyHostRecord(record, contract) {
7563
7725
  try {
7564
- if (typeof contract === "string") return readScalar(record, contract);
7726
+ const run = {
7727
+ copies: /* @__PURE__ */ new WeakMap(),
7728
+ nodes: MAX_NODES
7729
+ };
7730
+ if (typeof contract === "string") return readScalar(record, contract, run);
7565
7731
  if ((record === null || record === void 0) && contract.nullable === true) return record;
7566
- return applyContract(record, contract, /* @__PURE__ */ new WeakMap());
7732
+ return applyContract(record, contract, run);
7567
7733
  } catch (error) {
7568
7734
  throw new AuthException(AUTH_ERROR_CODES.INTERNAL, void 0, {
7569
7735
  cause: error
@@ -8580,7 +8746,7 @@ var TokenManagerService = class _TokenManagerService {
8580
8746
  accessSignOptions() {
8581
8747
  return {
8582
8748
  expiresIn: this.options.jwt.accessExpiresIn,
8583
- algorithm: this.options.jwt.algorithm,
8749
+ ...signerOf(this.options),
8584
8750
  ...this.issuerAudience()
8585
8751
  };
8586
8752
  }
@@ -9366,7 +9532,7 @@ var TokenManagerService = class _TokenManagerService {
9366
9532
  };
9367
9533
  const token = this.jwtService.sign(payload, {
9368
9534
  expiresIn: `${MFA_TEMP_TOKEN_TTL_SECONDS}s`,
9369
- algorithm: this.options.jwt.algorithm,
9535
+ ...signerOf(this.options),
9370
9536
  // The challenge token is stamped and checked like every other: it grants no resource
9371
9537
  // access on its own, but it is still a token this backend minted, and a verifier that
9372
9538
  // exempted one shape would be a verifier an attacker aims at.
@@ -10391,13 +10557,13 @@ exports.AuthService = class _AuthService {
10391
10557
  await sleep(Math.max(0, ANTI_ENUM_MIN_MS - (Date.now() - start)));
10392
10558
  return;
10393
10559
  }
10394
- const user = tenantScoped(await this.userRepo.findByEmail({
10395
- email,
10396
- tenantId
10397
- }), tenantId);
10398
- if (user && !user.emailVerified) {
10399
- await this.sendVerificationOtp(tenantId, email);
10400
- }
10560
+ await releasingCooldownOnFailure(this.redis, this.logger, cooldownKey, async () => {
10561
+ const user = tenantScoped(await this.userRepo.findByEmail({
10562
+ email,
10563
+ tenantId
10564
+ }), tenantId);
10565
+ return user && !user.emailVerified ? this.sendVerificationOtp(tenantId, email) : void 0;
10566
+ });
10401
10567
  await sleep(Math.max(0, ANTI_ENUM_MIN_MS - (Date.now() - start)));
10402
10568
  }
10403
10569
  // ---------------------------------------------------------------------------
@@ -10647,12 +10813,12 @@ exports.AuthService = class _AuthService {
10647
10813
  logEvent(this.logger, "AUTH_PROVIDER_MISSING", {
10648
10814
  flow: "email_verification_otp"
10649
10815
  });
10650
- return;
10816
+ return true;
10651
10817
  }
10652
10818
  const identifier = this.otpIdentifier(tenantId, email);
10653
10819
  const otp = this.otpService.generate(6);
10654
10820
  const { otpTtlSeconds: ttl } = this.options.emailVerification;
10655
- if (!await storeVerificationCode(this.otpService, this.logger, identifier, otp, ttl)) return;
10821
+ if (!await storeVerificationCode(this.otpService, this.logger, identifier, otp, ttl)) return false;
10656
10822
  const provider = this.emailProvider;
10657
10823
  void (async () => {
10658
10824
  try {
@@ -10661,6 +10827,7 @@ exports.AuthService = class _AuthService {
10661
10827
  logDelivery(this.logger, "email_verification_otp", err);
10662
10828
  }
10663
10829
  })();
10830
+ return true;
10664
10831
  }
10665
10832
  };
10666
10833
  exports.AuthService = _ts_decorate23([
@@ -18028,6 +18195,9 @@ exports.WorkspaceAccessService = class _WorkspaceAccessService {
18028
18195
  if (membership?.status !== "active" || workspace === null) return {
18029
18196
  kind: "denied"
18030
18197
  };
18198
+ if (workspace.tenantId !== ref.tenantId || membership.tenantId !== ref.tenantId || workspace.id !== ref.workspaceId || membership.workspaceId !== ref.workspaceId || membership.userId !== ref.userId) return {
18199
+ kind: "denied"
18200
+ };
18031
18201
  const member = {
18032
18202
  ...ref,
18033
18203
  role: membership.role
@@ -26776,9 +26946,8 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
26776
26946
  ...includeApiKeys ? [
26777
26947
  core.DiscoveryModule
26778
26948
  ] : [],
26779
- // JwtModule reads the secret directly from the consumer factory (without re-running
26780
- // resolveOptions) to avoid double-validation on startup. Full validation happens once
26781
- // in the BYMAX_AUTH_OPTIONS provider above.
26949
+ // A second call of the consumer factory, not resolveOptions: what it answers is not what the
26950
+ // BYMAX_AUTH_OPTIONS provider validated, so every sign and verify names the resolved secret.
26782
26951
  // expiresIn is omitted — TokenManagerService sets it per-call via accessSignOptions().
26783
26952
  jwt.JwtModule.registerAsync({
26784
26953
  // The factory runs here too, so it needs the modules the consumer's `inject` tokens come from.
@@ -828,7 +828,14 @@ var OBJECT_GROUPS = [
828
828
  "platform",
829
829
  "invitations",
830
830
  "emailChange",
831
- "oauth"
831
+ "oauth",
832
+ "roles",
833
+ "workspaces",
834
+ "workspaces.roles",
835
+ "workspaces.permissions",
836
+ "jwt",
837
+ "mfa",
838
+ "apiKeys"
832
839
  ];
833
840
  function readPath2(root, path) {
834
841
  let node = root;
@@ -1025,6 +1032,16 @@ var WORKSPACE_SUBGROUP_KEYS = {
1025
1032
  accessDeniedEvents: [
1026
1033
  "max",
1027
1034
  "windowSeconds"
1035
+ ],
1036
+ roles: [
1037
+ "hierarchy",
1038
+ "ownerRole"
1039
+ ],
1040
+ permissions: [
1041
+ "manageWorkspace",
1042
+ "deleteWorkspace",
1043
+ "manageMembers",
1044
+ "viewMembers"
1028
1045
  ]
1029
1046
  };
1030
1047
  function isObjectGroup(value) {
@@ -1074,7 +1091,7 @@ function dropUnset(options) {
1074
1091
  if (name === "workspaces") {
1075
1092
  for (const [sub, subKeys] of Object.entries(WORKSPACE_SUBGROUP_KEYS)) {
1076
1093
  const inner = group[sub];
1077
- if (isObjectGroup(inner)) group[sub] = readSetKeys(inner, subKeys);
1094
+ if (isObjectGroup(inner)) group[sub] = (sub === "accessDeniedEvents" ? readSetKeys : readKeptKeys)(inner, subKeys);
1078
1095
  }
1079
1096
  }
1080
1097
  copy[name] = group;
@@ -1098,15 +1115,127 @@ __name(dropUnset, "dropUnset");
1098
1115
  function readOptions(given) {
1099
1116
  const options = dropUnset(given);
1100
1117
  validateTextOptions(options);
1101
- return options;
1118
+ return pinCopied(options);
1102
1119
  }
1103
1120
  __name(readOptions, "readOptions");
1121
+ function copyHierarchy(held) {
1122
+ if (Object(held) !== held) return held;
1123
+ return Object.fromEntries(Object.entries(held).map(([role, children]) => [
1124
+ role,
1125
+ Array.isArray(children) ? [
1126
+ ...children
1127
+ ] : children
1128
+ ]));
1129
+ }
1130
+ __name(copyHierarchy, "copyHierarchy");
1131
+ function copyList(held) {
1132
+ return Array.isArray(held) ? [
1133
+ ...held
1134
+ ] : held;
1135
+ }
1136
+ __name(copyList, "copyList");
1137
+ var COPIED = [
1138
+ {
1139
+ path: [
1140
+ "roles"
1141
+ ],
1142
+ keys: [
1143
+ "hierarchy",
1144
+ "platformHierarchy"
1145
+ ],
1146
+ copy: copyHierarchy
1147
+ },
1148
+ {
1149
+ path: [
1150
+ "workspaces",
1151
+ "roles"
1152
+ ],
1153
+ keys: [
1154
+ "hierarchy"
1155
+ ],
1156
+ copy: copyHierarchy
1157
+ },
1158
+ {
1159
+ path: [
1160
+ "workspaces",
1161
+ "permissions"
1162
+ ],
1163
+ keys: [
1164
+ "manageWorkspace",
1165
+ "deleteWorkspace",
1166
+ "manageMembers",
1167
+ "viewMembers"
1168
+ ],
1169
+ copy: copyList
1170
+ },
1171
+ {
1172
+ path: [
1173
+ "jwt"
1174
+ ],
1175
+ keys: [
1176
+ "previousSecrets"
1177
+ ],
1178
+ copy: copyList
1179
+ },
1180
+ {
1181
+ path: [
1182
+ "mfa"
1183
+ ],
1184
+ keys: [
1185
+ "previousEncryptionKeys"
1186
+ ],
1187
+ copy: copyList
1188
+ },
1189
+ {
1190
+ path: [
1191
+ "apiKeys"
1192
+ ],
1193
+ keys: [
1194
+ "scopes"
1195
+ ],
1196
+ copy: copyList
1197
+ }
1198
+ ];
1199
+ function pinCopied(options) {
1200
+ for (const { path, keys, copy } of COPIED) {
1201
+ let group = options;
1202
+ for (const step of path) group = Object(group) === group ? group[step] : void 0;
1203
+ if (Object(group) !== group) continue;
1204
+ const plain = group;
1205
+ for (const key of keys) if (plain[key] !== void 0) plain[key] = copy(plain[key]);
1206
+ }
1207
+ return options;
1208
+ }
1209
+ __name(pinCopied, "pinCopied");
1104
1210
  function validateOptionValues(userOptions) {
1105
1211
  validateNumericOptions(userOptions);
1106
1212
  validateEnumAndBooleanOptions(userOptions);
1107
1213
  }
1108
1214
  __name(validateOptionValues, "validateOptionValues");
1109
1215
 
1216
+ // src/server/config/platform-options.ts
1217
+ function validatePlatformAdmin(platform, roles) {
1218
+ if (!platform?.enabled) return;
1219
+ const hierarchy = roles.platformHierarchy;
1220
+ if (!hierarchy) {
1221
+ throw new Error(`[BymaxAuthModule] roles.platformHierarchy is required when platform.enabled is true. Define the platform role hierarchy (e.g. { SUPER_ADMIN: ['SUPPORT'], SUPPORT: [] }).`);
1222
+ }
1223
+ assertObject("roles.platformHierarchy", hierarchy);
1224
+ const names = new Set(Object.keys(hierarchy));
1225
+ if (names.size === 0) {
1226
+ throw new Error(`[BymaxAuthModule] roles.platformHierarchy must not be an empty object. Define at least one role (e.g. { SUPER_ADMIN: [] }).`);
1227
+ }
1228
+ for (const [role, children] of Object.entries(hierarchy)) {
1229
+ assertArray(`roles.platformHierarchy['${role}']`, children);
1230
+ for (const child of children) {
1231
+ if (!names.has(child)) {
1232
+ throw new Error(`[BymaxAuthModule] roles.platformHierarchy['${role}'] references unknown role '${child}'. All roles referenced as children must be declared as keys in the hierarchy.`);
1233
+ }
1234
+ }
1235
+ }
1236
+ }
1237
+ __name(validatePlatformAdmin, "validatePlatformAdmin");
1238
+
1110
1239
  // src/server/constants/workspace-roles.ts
1111
1240
  var ANY_WORKSPACE_MEMBER = /* @__PURE__ */ Symbol("ANY_WORKSPACE_MEMBER");
1112
1241
 
@@ -1709,12 +1838,6 @@ function validateRolesHierarchy(roles) {
1709
1838
  }
1710
1839
  }
1711
1840
  __name(validateRolesHierarchy, "validateRolesHierarchy");
1712
- function validatePlatformAdmin(platform, roles) {
1713
- if (platform?.enabled && !roles.platformHierarchy) {
1714
- throw new Error(`[BymaxAuthModule] roles.platformHierarchy is required when platform.enabled is true. Define the platform role hierarchy (e.g. { SUPER_ADMIN: ['SUPPORT'], SUPPORT: [] }).`);
1715
- }
1716
- }
1717
- __name(validatePlatformAdmin, "validatePlatformAdmin");
1718
1841
  function assertIntegralScryptParameter(name, value) {
1719
1842
  if (value === void 0 || Number.isInteger(value)) return;
1720
1843
  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.`);
@@ -5433,26 +5556,34 @@ function malformedRefreshToken() {
5433
5556
  __name(malformedRefreshToken, "malformedRefreshToken");
5434
5557
 
5435
5558
  // src/server/utils/verify-with-rotation.ts
5559
+ function signerOf(options) {
5560
+ return {
5561
+ secret: options.jwt.secret,
5562
+ algorithm: options.jwt.algorithm
5563
+ };
5564
+ }
5565
+ __name(signerOf, "signerOf");
5436
5566
  function verifyWithRotation(jwtService, options, token, { ignoreExpiration = false } = {}) {
5437
5567
  const algorithms = [
5438
5568
  options.jwt.algorithm
5439
5569
  ];
5440
- const { issuer, audience } = options.jwt;
5570
+ const { issuer, audience, secret } = options.jwt;
5441
5571
  const base = {
5442
5572
  algorithms,
5443
5573
  ignoreExpiration,
5444
5574
  issuer,
5445
- audience
5575
+ audience,
5576
+ secret
5446
5577
  };
5447
5578
  try {
5448
5579
  return jwtService.verify(token, base);
5449
5580
  } catch (currentFailure) {
5450
5581
  const previous = options.jwt.previousSecrets ?? [];
5451
- for (const secret of previous) {
5582
+ for (const secret2 of previous) {
5452
5583
  try {
5453
5584
  return jwtService.verify(token, {
5454
5585
  ...base,
5455
- secret
5586
+ secret: secret2
5456
5587
  });
5457
5588
  } catch {
5458
5589
  }
@@ -6647,6 +6778,18 @@ function _ts_param11(paramIndex, decorator) {
6647
6778
  };
6648
6779
  }
6649
6780
  __name(_ts_param11, "_ts_param");
6781
+ async function releasingCooldownOnFailure(redis, logger, cooldownKey, work) {
6782
+ const release = /* @__PURE__ */ __name(() => redis.del(cooldownKey).then(() => void 0, (err) => {
6783
+ logStore(logger, "AUTH_STORE_FAILED", "resend_cooldown_release", err);
6784
+ }), "release");
6785
+ try {
6786
+ if (await work() === false) await release();
6787
+ } catch (error) {
6788
+ await release();
6789
+ throw error;
6790
+ }
6791
+ }
6792
+ __name(releasingCooldownOnFailure, "releasingCooldownOnFailure");
6650
6793
  var MAX_ATTEMPTS = 5;
6651
6794
  var MIN_VERIFY_MS = 100;
6652
6795
  var OTP_STORE_LUA = `
@@ -7157,8 +7300,8 @@ PasswordService = _ts_decorate20([
7157
7300
  var RECORD_CONTRACTS = {
7158
7301
  workspace: {
7159
7302
  fields: {
7160
- id: "~id",
7161
- tenantId: "id",
7303
+ id: "id",
7304
+ tenantId: "string",
7162
7305
  name: "~string",
7163
7306
  status: "string",
7164
7307
  createdAt: "~date",
@@ -7168,9 +7311,9 @@ var RECORD_CONTRACTS = {
7168
7311
  },
7169
7312
  membership: {
7170
7313
  fields: {
7171
- tenantId: "id",
7172
- workspaceId: "~id",
7173
- userId: "~id",
7314
+ tenantId: "string",
7315
+ workspaceId: "id",
7316
+ userId: "id",
7174
7317
  role: "string",
7175
7318
  status: "string",
7176
7319
  invitedByUserId: "~id",
@@ -7181,13 +7324,13 @@ var RECORD_CONTRACTS = {
7181
7324
  },
7182
7325
  user: {
7183
7326
  fields: {
7184
- id: "~id",
7327
+ id: "id",
7185
7328
  email: "~string",
7186
7329
  name: "~string",
7187
7330
  passwordHash: "string|null",
7188
7331
  role: "string",
7189
7332
  status: "string",
7190
- tenantId: "id",
7333
+ tenantId: "string",
7191
7334
  emailVerified: "boolean",
7192
7335
  mfaEnabled: "boolean",
7193
7336
  mfaSecret: "string?",
@@ -7201,7 +7344,7 @@ var RECORD_CONTRACTS = {
7201
7344
  },
7202
7345
  platformUser: {
7203
7346
  fields: {
7204
- id: "~id",
7347
+ id: "id",
7205
7348
  email: "~string",
7206
7349
  name: "~string",
7207
7350
  passwordHash: "string",
@@ -7219,7 +7362,7 @@ var RECORD_CONTRACTS = {
7219
7362
  },
7220
7363
  apiKey: {
7221
7364
  fields: {
7222
- id: "~id",
7365
+ id: "id",
7223
7366
  label: "~string",
7224
7367
  digest: "string",
7225
7368
  scopes: "strings",
@@ -7232,7 +7375,7 @@ var RECORD_CONTRACTS = {
7232
7375
  },
7233
7376
  removedMembership: {
7234
7377
  fields: {
7235
- workspaceId: "~id",
7378
+ workspaceId: "id",
7236
7379
  role: "string"
7237
7380
  },
7238
7381
  nested: {}
@@ -7371,14 +7514,15 @@ var CREDENTIAL_FIELDS = /* @__PURE__ */ new Set([
7371
7514
 
7372
7515
  // src/server/utils/host-read.ts
7373
7516
  var MAX_BREADTH = 1e5;
7374
- function copiedUnder(seen, value, contract) {
7375
- return seen.get(value)?.get(contract);
7517
+ var MAX_NODES = 1e6;
7518
+ function copiedUnder(read, value, contract) {
7519
+ return read.copies.get(value)?.get(contract);
7376
7520
  }
7377
7521
  __name(copiedUnder, "copiedUnder");
7378
- function rememberUnder(seen, value, contract, copy) {
7379
- const copies = seen.get(value) ?? /* @__PURE__ */ new Map();
7522
+ function rememberUnder(read, value, contract, copy) {
7523
+ const copies = read.copies.get(value) ?? /* @__PURE__ */ new Map();
7380
7524
  copies.set(contract, copy);
7381
- seen.set(value, copies);
7525
+ read.copies.set(value, copies);
7382
7526
  }
7383
7527
  __name(rememberUnder, "rememberUnder");
7384
7528
  function readHostOptions(read) {
@@ -7424,10 +7568,11 @@ function define(copy, key, value, enumerable) {
7424
7568
  }
7425
7569
  __name(define, "define");
7426
7570
  var ENTITIES = /* @__PURE__ */ new WeakMap();
7427
- function refuseBreadth(size) {
7428
- if (size > MAX_BREADTH) throw new Error("the answer holds more than the library follows");
7571
+ function follow(read, size) {
7572
+ read.nodes -= size;
7573
+ if (size > MAX_BREADTH || read.nodes < 0) throw new Error("the answer holds more than the library follows");
7429
7574
  }
7430
- __name(refuseBreadth, "refuseBreadth");
7575
+ __name(follow, "follow");
7431
7576
  function isDateLike(value) {
7432
7577
  return types.isDate(value) || types.isProxy(value) && value instanceof Date;
7433
7578
  }
@@ -7449,17 +7594,22 @@ function isHostInstance(value) {
7449
7594
  return typeof value === "object" && value !== null && !Array.isArray(value) && !types.isBoxedPrimitive(value) && !isPlainObject(value);
7450
7595
  }
7451
7596
  __name(isHostInstance, "isHostInstance");
7597
+ function timeOf(date) {
7598
+ const real = types.isDate(date);
7599
+ return real ? Date.prototype.getTime.call(date) : date.getTime();
7600
+ }
7601
+ __name(timeOf, "timeOf");
7452
7602
  function copyDate(value) {
7453
7603
  if (typeof value !== "object" || value === null || !isDateLike(value)) throw new Error(WRONG_KIND);
7454
- const time = value.getTime();
7604
+ const time = timeOf(value);
7455
7605
  const copy = new Date(typeof time === "number" ? time : Number.NaN);
7456
7606
  if (Number.isNaN(copy.getTime())) throw new Error(NOT_A_TIME);
7457
7607
  return copy;
7458
7608
  }
7459
7609
  __name(copyDate, "copyDate");
7460
- function copyStrings(value) {
7610
+ function copyStrings(value, read) {
7461
7611
  if (!Array.isArray(value)) throw new Error(WRONG_KIND);
7462
- refuseBreadth(value.length);
7612
+ follow(read, value.length);
7463
7613
  const copy = [];
7464
7614
  for (let index = 0; index < value.length; index += 1) {
7465
7615
  const element = value[index];
@@ -7468,6 +7618,18 @@ function copyStrings(value) {
7468
7618
  return copy;
7469
7619
  }
7470
7620
  __name(copyStrings, "copyStrings");
7621
+ var NOT_AN_ID_TEXT = /* @__PURE__ */ new Set([
7622
+ "undefined",
7623
+ "null"
7624
+ ]);
7625
+ function readId(value) {
7626
+ if (typeof value === "number") return accept(Number.isSafeInteger(value), String(value));
7627
+ if (typeof value !== "string" && (!isHostInstance(value) || types.isDate(value) || types.isRegExp(value) || types.isNativeError(value) || types.isArrayBufferView(value))) throw new Error(WRONG_KIND);
7628
+ const text = String(value);
7629
+ const printed = typeof value !== "string";
7630
+ return accept(text.trim() !== "" && !NOT_AN_ID_TEXT.has(text) && !(printed && text.startsWith("[object ")), text);
7631
+ }
7632
+ __name(readId, "readId");
7471
7633
  function readInforming(value) {
7472
7634
  return accept(typeof value === "string" || Number.isFinite(value) || isHostInstance(value), value);
7473
7635
  }
@@ -7476,7 +7638,7 @@ function readInformingDate(value) {
7476
7638
  if (typeof value === "string" || Number.isFinite(value)) return value;
7477
7639
  if (!isHostInstance(value)) throw new Error(WRONG_KIND);
7478
7640
  if (!isDateLike(value)) return value;
7479
- const time = value.getTime();
7641
+ const time = timeOf(value);
7480
7642
  const copy = new Date(typeof time === "number" ? time : Number.NaN);
7481
7643
  return Number.isNaN(copy.getTime()) ? value : copy;
7482
7644
  }
@@ -7484,11 +7646,11 @@ __name(readInformingDate, "readInformingDate");
7484
7646
  var READERS = {
7485
7647
  boolean: /* @__PURE__ */ __name((value) => accept(typeof value === "boolean", value), "boolean"),
7486
7648
  string: /* @__PURE__ */ __name((value) => accept(typeof value === "string", value), "string"),
7649
+ id: readId,
7487
7650
  number: /* @__PURE__ */ __name((value) => accept(Number.isFinite(value), value), "number"),
7488
- id: /* @__PURE__ */ __name((value) => accept(typeof value === "string" || isHostInstance(value), value), "id"),
7489
7651
  date: copyDate,
7490
7652
  strings: copyStrings,
7491
- "~id": readInforming,
7653
+ "~id": readId,
7492
7654
  "~string": readInforming,
7493
7655
  "~date": readInformingDate
7494
7656
  };
@@ -7509,19 +7671,19 @@ function readNull(nullable) {
7509
7671
  return null;
7510
7672
  }
7511
7673
  __name(readNull, "readNull");
7512
- function readScalar(value, spec) {
7674
+ function readScalar(value, spec, run) {
7513
7675
  const { base, nullable } = parseSpec(spec);
7514
7676
  if (base === "void") return void 0;
7515
- return value === null ? readNull(nullable) : READERS[base](value);
7677
+ return value === null ? readNull(nullable) : READERS[base](value, run);
7516
7678
  }
7517
7679
  __name(readScalar, "readScalar");
7518
- function copyRecord(value, contract, seen) {
7680
+ function copyRecord(value, contract, run) {
7519
7681
  const copy = {};
7520
- rememberUnder(seen, value, contract, copy);
7682
+ rememberUnder(run, value, contract, copy);
7521
7683
  ENTITIES.set(copy, value);
7522
7684
  const source = value;
7523
7685
  const keys = Object.keys(value);
7524
- refuseBreadth(keys.length);
7686
+ follow(run, keys.length);
7525
7687
  for (const key of keys) {
7526
7688
  if (Object.hasOwn(contract.fields, key)) continue;
7527
7689
  const descriptor = Object.getOwnPropertyDescriptor(value, key);
@@ -7530,38 +7692,42 @@ function copyRecord(value, contract, seen) {
7530
7692
  const own = new Set(keys);
7531
7693
  for (const [field, spec] of Object.entries(contract.fields)) {
7532
7694
  const { base, nullable, optional } = parseSpec(spec);
7533
- const read = source[field];
7534
- if (read === void 0) {
7695
+ const held = source[field];
7696
+ if (held === void 0) {
7535
7697
  if (optional) continue;
7536
7698
  throw new Error(ABSENT);
7537
7699
  }
7538
- const copied = read === null ? readNull(nullable || optional) : base === "nested" ? applyContract(read, contract.nested[field], seen) : READERS[base](read);
7700
+ const copied = held === null ? readNull(nullable || optional) : base === "nested" ? applyContract(held, contract.nested[field], run) : READERS[base](held, run);
7539
7701
  define(copy, field, copied, own.has(field) || !CREDENTIAL_FIELDS.has(field));
7540
7702
  }
7541
7703
  return copy;
7542
7704
  }
7543
7705
  __name(copyRecord, "copyRecord");
7544
- function applyContract(value, contract, seen) {
7706
+ function applyContract(value, contract, run) {
7545
7707
  if (typeof value !== "object" || value === null) throw new Error(WRONG_KIND);
7546
- const known = copiedUnder(seen, value, contract);
7708
+ const known = copiedUnder(run, value, contract);
7547
7709
  if (known !== void 0) return known;
7548
7710
  if ("list" in contract) {
7549
7711
  if (!Array.isArray(value)) throw new Error("the answer is not the list its method promises");
7550
- refuseBreadth(value.length);
7712
+ follow(run, value.length);
7551
7713
  const copy = [];
7552
- rememberUnder(seen, value, contract, copy);
7553
- for (let index = 0; index < value.length; index += 1) copy.push(applyContract(value[index], contract.list, seen));
7714
+ rememberUnder(run, value, contract, copy);
7715
+ for (let index = 0; index < value.length; index += 1) copy.push(applyContract(value[index], contract.list, run));
7554
7716
  return copy;
7555
7717
  }
7556
7718
  if (Array.isArray(value)) throw new Error("the answer is not the record its method promises");
7557
- return copyRecord(value, contract, seen);
7719
+ return copyRecord(value, contract, run);
7558
7720
  }
7559
7721
  __name(applyContract, "applyContract");
7560
7722
  function copyHostRecord(record, contract) {
7561
7723
  try {
7562
- if (typeof contract === "string") return readScalar(record, contract);
7724
+ const run = {
7725
+ copies: /* @__PURE__ */ new WeakMap(),
7726
+ nodes: MAX_NODES
7727
+ };
7728
+ if (typeof contract === "string") return readScalar(record, contract, run);
7563
7729
  if ((record === null || record === void 0) && contract.nullable === true) return record;
7564
- return applyContract(record, contract, /* @__PURE__ */ new WeakMap());
7730
+ return applyContract(record, contract, run);
7565
7731
  } catch (error) {
7566
7732
  throw new AuthException(AUTH_ERROR_CODES.INTERNAL, void 0, {
7567
7733
  cause: error
@@ -8578,7 +8744,7 @@ var TokenManagerService = class _TokenManagerService {
8578
8744
  accessSignOptions() {
8579
8745
  return {
8580
8746
  expiresIn: this.options.jwt.accessExpiresIn,
8581
- algorithm: this.options.jwt.algorithm,
8747
+ ...signerOf(this.options),
8582
8748
  ...this.issuerAudience()
8583
8749
  };
8584
8750
  }
@@ -9364,7 +9530,7 @@ var TokenManagerService = class _TokenManagerService {
9364
9530
  };
9365
9531
  const token = this.jwtService.sign(payload, {
9366
9532
  expiresIn: `${MFA_TEMP_TOKEN_TTL_SECONDS}s`,
9367
- algorithm: this.options.jwt.algorithm,
9533
+ ...signerOf(this.options),
9368
9534
  // The challenge token is stamped and checked like every other: it grants no resource
9369
9535
  // access on its own, but it is still a token this backend minted, and a verifier that
9370
9536
  // exempted one shape would be a verifier an attacker aims at.
@@ -10389,13 +10555,13 @@ var AuthService = class _AuthService {
10389
10555
  await sleep(Math.max(0, ANTI_ENUM_MIN_MS - (Date.now() - start)));
10390
10556
  return;
10391
10557
  }
10392
- const user = tenantScoped(await this.userRepo.findByEmail({
10393
- email,
10394
- tenantId
10395
- }), tenantId);
10396
- if (user && !user.emailVerified) {
10397
- await this.sendVerificationOtp(tenantId, email);
10398
- }
10558
+ await releasingCooldownOnFailure(this.redis, this.logger, cooldownKey, async () => {
10559
+ const user = tenantScoped(await this.userRepo.findByEmail({
10560
+ email,
10561
+ tenantId
10562
+ }), tenantId);
10563
+ return user && !user.emailVerified ? this.sendVerificationOtp(tenantId, email) : void 0;
10564
+ });
10399
10565
  await sleep(Math.max(0, ANTI_ENUM_MIN_MS - (Date.now() - start)));
10400
10566
  }
10401
10567
  // ---------------------------------------------------------------------------
@@ -10645,12 +10811,12 @@ var AuthService = class _AuthService {
10645
10811
  logEvent(this.logger, "AUTH_PROVIDER_MISSING", {
10646
10812
  flow: "email_verification_otp"
10647
10813
  });
10648
- return;
10814
+ return true;
10649
10815
  }
10650
10816
  const identifier = this.otpIdentifier(tenantId, email);
10651
10817
  const otp = this.otpService.generate(6);
10652
10818
  const { otpTtlSeconds: ttl } = this.options.emailVerification;
10653
- if (!await storeVerificationCode(this.otpService, this.logger, identifier, otp, ttl)) return;
10819
+ if (!await storeVerificationCode(this.otpService, this.logger, identifier, otp, ttl)) return false;
10654
10820
  const provider = this.emailProvider;
10655
10821
  void (async () => {
10656
10822
  try {
@@ -10659,6 +10825,7 @@ var AuthService = class _AuthService {
10659
10825
  logDelivery(this.logger, "email_verification_otp", err);
10660
10826
  }
10661
10827
  })();
10828
+ return true;
10662
10829
  }
10663
10830
  };
10664
10831
  AuthService = _ts_decorate23([
@@ -18026,6 +18193,9 @@ var WorkspaceAccessService = class _WorkspaceAccessService {
18026
18193
  if (membership?.status !== "active" || workspace === null) return {
18027
18194
  kind: "denied"
18028
18195
  };
18196
+ if (workspace.tenantId !== ref.tenantId || membership.tenantId !== ref.tenantId || workspace.id !== ref.workspaceId || membership.workspaceId !== ref.workspaceId || membership.userId !== ref.userId) return {
18197
+ kind: "denied"
18198
+ };
18029
18199
  const member = {
18030
18200
  ...ref,
18031
18201
  role: membership.role
@@ -26774,9 +26944,8 @@ var BymaxAuthModule = class _BymaxAuthModule {
26774
26944
  ...includeApiKeys ? [
26775
26945
  DiscoveryModule
26776
26946
  ] : [],
26777
- // JwtModule reads the secret directly from the consumer factory (without re-running
26778
- // resolveOptions) to avoid double-validation on startup. Full validation happens once
26779
- // in the BYMAX_AUTH_OPTIONS provider above.
26947
+ // A second call of the consumer factory, not resolveOptions: what it answers is not what the
26948
+ // BYMAX_AUTH_OPTIONS provider validated, so every sign and verify names the resolved secret.
26780
26949
  // expiresIn is omitted — TokenManagerService sets it per-call via accessSignOptions().
26781
26950
  JwtModule.registerAsync({
26782
26951
  // The factory runs here too, so it needs the modules the consumer's `inject` tokens come from.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-auth",
3
- "version": "1.5.12",
3
+ "version": "1.5.14",
4
4
  "description": "Full-stack authentication and authorization package for NestJS, React and Next.js — JWT, MFA, OAuth, sessions, multi-tenant SaaS ready",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",
@@ -98,7 +98,7 @@
98
98
  "gen:openapi-schemas": "UPDATE_OPENAPI_SCHEMAS=1 jest src/server/openapi/request-schemas.conformance.spec.ts",
99
99
  "gen:openapi-security": "UPDATE_OPENAPI_SECURITY=1 jest src/server/openapi/operation-security.conformance.spec.ts",
100
100
  "format:check": "prettier --check .",
101
- "lint": "eslint src",
101
+ "lint": "eslint src && node --test scripts/check-dist-fresh.test.mjs",
102
102
  "lint:fix": "eslint src --fix",
103
103
  "mutation": "stryker run",
104
104
  "mutation:full": "node -e \"require('node:fs').rmSync('reports/stryker-incremental.json',{force:true,recursive:true})\" && stryker run",
@@ -106,7 +106,7 @@
106
106
  "prepare": "husky",
107
107
  "prepublishOnly": "pnpm clean && pnpm typecheck && pnpm lint && pnpm test:cov:all && pnpm build && pnpm size && pnpm check:exports && pnpm check:published && pnpm check:runtime",
108
108
  "release": "npm publish --provenance --access public",
109
- "size": "node scripts/check-size.mjs",
109
+ "size": "node scripts/check-dist-fresh.mjs --also tsup.config.ts --also package.json --also tsconfig.json --also tsconfig.build.json --also tsconfig.build.web.json && node scripts/check-size.mjs",
110
110
  "test": "jest",
111
111
  "test:all": "pnpm test && pnpm test:e2e",
112
112
  "test:cov": "jest --coverage",