@bymax-one/nest-auth 1.4.8 → 1.4.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.
package/CHANGELOG.md CHANGED
@@ -18,6 +18,53 @@ what moves, and that note is the compatibility contract until strict SemVer begi
18
18
 
19
19
  ## [Unreleased]
20
20
 
21
+ ## [1.4.10] - 2026-11-01
22
+
23
+ ### Apply to a derived backend
24
+
25
+ - **The account-status cache keys no longer carry the tenant and user id.** The `us:` (status) and
26
+ `uev:` (email-verified) entries were keyed by the percent-encoded tenant and user id; they are now
27
+ keyed by `HMAC-SHA-256(hmacKey, userSubject)` of the tenant-scoped dashboard subject, like the
28
+ session index, the token epoch and every other key that names an account. Both entries are
29
+ TTL'd cache values, so nothing needs migrating: the first read after the change misses and
30
+ refills. **Do not name these keys yourself**; `AccountStatusService.invalidate` is the supported
31
+ way to drop them and it already derives the new shape. A deployment that runs the old and the new
32
+ release side by side (a rolling deploy, or another backend on the old shape sharing the store)
33
+ can serve a changed status stale for **up to `userStatusCacheTtlSeconds`** (60 s by default),
34
+ because an invalidation issued by one side deletes a key the other does not read, and pays one
35
+ extra repository read per account. Drain the old release before the new one serves to avoid even
36
+ that.
37
+
38
+ ### Security
39
+
40
+ - The status cache no longer writes account identifiers into Redis keys in the clear.
41
+
42
+ ### Documentation
43
+
44
+ - **The account-status cache is part of the shared wire contract.** `conformance/wire-contract.json`
45
+ declares the `us` and `uev` prefixes and a `userStatusCache` section: the key derivation, the
46
+ value forms, the TTL source and the invalidation order (verified entry first), with vectors for
47
+ delimiter-bearing and multi-byte ids. A conformance test pins the library's behaviour to it.
48
+
49
+ ## [1.4.9] - 2026-11-01
50
+
51
+ ### Apply to a derived backend
52
+
53
+ - **`invite` can now answer `auth.insufficient_role` when the invitee index moved under it.** The
54
+ index is claimed before the record is written, and a revoke or a later invite landing in that gap
55
+ used to leave a redeemable record that nothing named, with the email already sent. `invite` now
56
+ repeats the claim after the write; if the index no longer names the invitation, it withdraws its
57
+ own record, sends no email and answers `auth.insufficient_role`, the code a lost supersede race
58
+ already used. A store failure on that repeat withdraws the record too and surfaces unchanged.
59
+ Nothing changes for an invite that is not racing a revoke.
60
+
61
+ ### Fixed
62
+
63
+ - **A revoke landing between the index claim and the record write left an orphan invitation.** The
64
+ invitation was redeemable for its whole TTL, the email was sent, and no later revoke could reach
65
+ it. The index TTL also started at the claim and the record's at the write, so the record outlived
66
+ the entry that names it; the repeated claim renews the index TTL after the write.
67
+
21
68
  ## [1.4.8] - 2026-10-31
22
69
 
23
70
  ### Apply to a derived backend
@@ -4076,7 +4123,9 @@ ever installable.
4076
4123
  - 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
4077
4124
  - 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
4078
4125
 
4079
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.8...HEAD
4126
+ [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.10...HEAD
4127
+ [1.4.10]: https://github.com/bymaxone/nest-auth/compare/v1.4.9...v1.4.10
4128
+ [1.4.9]: https://github.com/bymaxone/nest-auth/compare/v1.4.8...v1.4.9
4080
4129
  [1.4.8]: https://github.com/bymaxone/nest-auth/compare/v1.4.6...v1.4.8
4081
4130
  [1.4.6]: https://github.com/bymaxone/nest-auth/compare/v1.4.5...v1.4.6
4082
4131
  [1.4.5]: https://github.com/bymaxone/nest-auth/compare/v1.4.4...v1.4.5
@@ -3872,11 +3872,11 @@ function _ts_param7(paramIndex, decorator) {
3872
3872
  };
3873
3873
  }
3874
3874
  __name(_ts_param7, "_ts_param");
3875
- function cacheKeysFor(ref) {
3876
- const scope = `${encodeURIComponent(ref.tenantId)}:${encodeURIComponent(ref.userId)}`;
3875
+ function cacheKeysFor(ref, hmacKey) {
3876
+ const digest = hmacSha256(userSubject("dashboard", ref.userId, ref.tenantId), hmacKey);
3877
3877
  return {
3878
- statusKey: `us:${scope}`,
3879
- verifiedKey: `uev:${scope}`
3878
+ statusKey: `us:${digest}`,
3879
+ verifiedKey: `uev:${digest}`
3880
3880
  };
3881
3881
  }
3882
3882
  __name(cacheKeysFor, "cacheKeysFor");
@@ -3934,7 +3934,7 @@ exports.AccountStatusService = class AccountStatusService {
3934
3934
  *
3935
3935
  * @param ref - The account whose cached facts are now stale. Both fields must be non-empty.
3936
3936
  * @throws {TypeError} When either id is empty or blank. Refused rather than attempted: an empty
3937
- * tenant builds `us::{userId}`, which names no entry any read ever wrote, so the delete would
3937
+ * tenant derives a subject no read ever wrote, so the delete would
3938
3938
  * remove nothing and resolve normally — the caller's admin surface reports the suspension
3939
3939
  * applied while the cached `active` survives its full TTL. That is the exact silent failure
3940
3940
  * this method exists to eliminate, and an unset resolver value or a `undefined` coerced by a
@@ -3944,7 +3944,7 @@ exports.AccountStatusService = class AccountStatusService {
3944
3944
  if (ref.userId.trim() === "" || ref.tenantId.trim() === "") {
3945
3945
  throw new TypeError("invalidate: userId and tenantId must both be non-empty");
3946
3946
  }
3947
- const { statusKey, verifiedKey } = cacheKeysFor(ref);
3947
+ const { statusKey, verifiedKey } = cacheKeysFor(ref, this.options.hmacKey);
3948
3948
  await this.redis.del(verifiedKey);
3949
3949
  await this.redis.del(statusKey);
3950
3950
  }
@@ -3961,7 +3961,7 @@ exports.AccountStatusService = class AccountStatusService {
3961
3961
  */
3962
3962
  async assertDashboardAccountUsable(ref) {
3963
3963
  const { userId, tenantId } = ref;
3964
- const { statusKey, verifiedKey } = cacheKeysFor(ref);
3964
+ const { statusKey, verifiedKey } = cacheKeysFor(ref, this.options.hmacKey);
3965
3965
  const cacheTtl = this.options.userStatusCacheTtlSeconds;
3966
3966
  const requireVerified = this.options.emailVerification.required;
3967
3967
  let status = await this.redis.get(statusKey);
@@ -8766,6 +8766,17 @@ exports.InvitationService = class _InvitationService {
8766
8766
  await this.redis.del(`inv:${supersededHash}`);
8767
8767
  }
8768
8768
  await this.redis.set(tokenKey, JSON.stringify(stored), ttl);
8769
+ let stillNamed;
8770
+ try {
8771
+ stillNamed = await this.claimInviteeIndex(normalizedEmail, tenantId, tokenHash, ttl, tokenHash);
8772
+ } catch (err) {
8773
+ await this.withdrawRecord(tokenKey);
8774
+ throw err;
8775
+ }
8776
+ if (!stillNamed.claimed) {
8777
+ await this.withdrawRecord(tokenKey);
8778
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
8779
+ }
8769
8780
  const displayTenantName = tenantName ?? tenantId;
8770
8781
  const expiresAt = new Date(Date.now() + ttl * 1e3);
8771
8782
  try {
@@ -8892,6 +8903,21 @@ exports.InvitationService = class _InvitationService {
8892
8903
  throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
8893
8904
  }
8894
8905
  /**
8906
+ * Removes the invitation record this call wrote, best-effort.
8907
+ *
8908
+ * Used where the call is already ending in a refusal or a failure of its own, so a failing
8909
+ * delete must not replace that outcome: it is logged and the caller still raises the original.
8910
+ * The raw token has not been emailed at that point, so a record that survives is one nobody
8911
+ * holds the token for, until its TTL.
8912
+ *
8913
+ * @param tokenKey - The Redis key of the record written by this call.
8914
+ */
8915
+ async withdrawRecord(tokenKey) {
8916
+ await this.redis.del(tokenKey).catch((err) => {
8917
+ this.logger.warn(`invite: could not withdraw the record \u2014 ${describeChannelStatus(err)}`);
8918
+ });
8919
+ }
8920
+ /**
8895
8921
  * Atomically points the invitee index at `tokenHash`, answering with the hash it displaced.
8896
8922
  *
8897
8923
  * A compare-and-swap, not a plain write: the claim proceeds only when the index still holds
@@ -5674,7 +5674,7 @@ declare class TrustedOriginGuard implements CanActivate {
5674
5674
  * request — an access token's whole lifetime, a stream held open for hours — therefore has to ask
5675
5675
  * again, which is what this service exists to do.
5676
5676
  *
5677
- * It reads through a Redis cache (`us:{tenantId}:{userId}`, and `uev:` for the verified flag)
5677
+ * It reads through a Redis cache (`us:` for the status and `uev:` for the verified flag, each keyed by the account)
5678
5678
  * rather than the repository, so asking on every request or on every reconnect costs one `get`
5679
5679
  * rather than a database round trip. A miss resolves both facts from a single tenant-scoped read
5680
5680
  * and writes both back for `userStatusCacheTtlSeconds`.
@@ -5731,7 +5731,7 @@ declare class AccountStatusService {
5731
5731
  *
5732
5732
  * @param ref - The account whose cached facts are now stale. Both fields must be non-empty.
5733
5733
  * @throws {TypeError} When either id is empty or blank. Refused rather than attempted: an empty
5734
- * tenant builds `us::{userId}`, which names no entry any read ever wrote, so the delete would
5734
+ * tenant derives a subject no read ever wrote, so the delete would
5735
5735
  * remove nothing and resolve normally — the caller's admin surface reports the suspension
5736
5736
  * applied while the cached `active` survives its full TTL. That is the exact silent failure
5737
5737
  * this method exists to eliminate, and an unset resolver value or a `undefined` coerced by a
@@ -9319,6 +9319,17 @@ declare class InvitationService {
9319
9319
  * allowed to destroy whatever is there now.
9320
9320
  */
9321
9321
  private supersedeApprovedInvitation;
9322
+ /**
9323
+ * Removes the invitation record this call wrote, best-effort.
9324
+ *
9325
+ * Used where the call is already ending in a refusal or a failure of its own, so a failing
9326
+ * delete must not replace that outcome: it is logged and the caller still raises the original.
9327
+ * The raw token has not been emailed at that point, so a record that survives is one nobody
9328
+ * holds the token for, until its TTL.
9329
+ *
9330
+ * @param tokenKey - The Redis key of the record written by this call.
9331
+ */
9332
+ private withdrawRecord;
9322
9333
  /**
9323
9334
  * Atomically points the invitee index at `tokenHash`, answering with the hash it displaced.
9324
9335
  *
@@ -5674,7 +5674,7 @@ declare class TrustedOriginGuard implements CanActivate {
5674
5674
  * request — an access token's whole lifetime, a stream held open for hours — therefore has to ask
5675
5675
  * again, which is what this service exists to do.
5676
5676
  *
5677
- * It reads through a Redis cache (`us:{tenantId}:{userId}`, and `uev:` for the verified flag)
5677
+ * It reads through a Redis cache (`us:` for the status and `uev:` for the verified flag, each keyed by the account)
5678
5678
  * rather than the repository, so asking on every request or on every reconnect costs one `get`
5679
5679
  * rather than a database round trip. A miss resolves both facts from a single tenant-scoped read
5680
5680
  * and writes both back for `userStatusCacheTtlSeconds`.
@@ -5731,7 +5731,7 @@ declare class AccountStatusService {
5731
5731
  *
5732
5732
  * @param ref - The account whose cached facts are now stale. Both fields must be non-empty.
5733
5733
  * @throws {TypeError} When either id is empty or blank. Refused rather than attempted: an empty
5734
- * tenant builds `us::{userId}`, which names no entry any read ever wrote, so the delete would
5734
+ * tenant derives a subject no read ever wrote, so the delete would
5735
5735
  * remove nothing and resolve normally — the caller's admin surface reports the suspension
5736
5736
  * applied while the cached `active` survives its full TTL. That is the exact silent failure
5737
5737
  * this method exists to eliminate, and an unset resolver value or a `undefined` coerced by a
@@ -9319,6 +9319,17 @@ declare class InvitationService {
9319
9319
  * allowed to destroy whatever is there now.
9320
9320
  */
9321
9321
  private supersedeApprovedInvitation;
9322
+ /**
9323
+ * Removes the invitation record this call wrote, best-effort.
9324
+ *
9325
+ * Used where the call is already ending in a refusal or a failure of its own, so a failing
9326
+ * delete must not replace that outcome: it is logged and the caller still raises the original.
9327
+ * The raw token has not been emailed at that point, so a record that survives is one nobody
9328
+ * holds the token for, until its TTL.
9329
+ *
9330
+ * @param tokenKey - The Redis key of the record written by this call.
9331
+ */
9332
+ private withdrawRecord;
9322
9333
  /**
9323
9334
  * Atomically points the invitee index at `tokenHash`, answering with the hash it displaced.
9324
9335
  *
@@ -3870,11 +3870,11 @@ function _ts_param7(paramIndex, decorator) {
3870
3870
  };
3871
3871
  }
3872
3872
  __name(_ts_param7, "_ts_param");
3873
- function cacheKeysFor(ref) {
3874
- const scope = `${encodeURIComponent(ref.tenantId)}:${encodeURIComponent(ref.userId)}`;
3873
+ function cacheKeysFor(ref, hmacKey) {
3874
+ const digest = hmacSha256(userSubject("dashboard", ref.userId, ref.tenantId), hmacKey);
3875
3875
  return {
3876
- statusKey: `us:${scope}`,
3877
- verifiedKey: `uev:${scope}`
3876
+ statusKey: `us:${digest}`,
3877
+ verifiedKey: `uev:${digest}`
3878
3878
  };
3879
3879
  }
3880
3880
  __name(cacheKeysFor, "cacheKeysFor");
@@ -3932,7 +3932,7 @@ var AccountStatusService = class {
3932
3932
  *
3933
3933
  * @param ref - The account whose cached facts are now stale. Both fields must be non-empty.
3934
3934
  * @throws {TypeError} When either id is empty or blank. Refused rather than attempted: an empty
3935
- * tenant builds `us::{userId}`, which names no entry any read ever wrote, so the delete would
3935
+ * tenant derives a subject no read ever wrote, so the delete would
3936
3936
  * remove nothing and resolve normally — the caller's admin surface reports the suspension
3937
3937
  * applied while the cached `active` survives its full TTL. That is the exact silent failure
3938
3938
  * this method exists to eliminate, and an unset resolver value or a `undefined` coerced by a
@@ -3942,7 +3942,7 @@ var AccountStatusService = class {
3942
3942
  if (ref.userId.trim() === "" || ref.tenantId.trim() === "") {
3943
3943
  throw new TypeError("invalidate: userId and tenantId must both be non-empty");
3944
3944
  }
3945
- const { statusKey, verifiedKey } = cacheKeysFor(ref);
3945
+ const { statusKey, verifiedKey } = cacheKeysFor(ref, this.options.hmacKey);
3946
3946
  await this.redis.del(verifiedKey);
3947
3947
  await this.redis.del(statusKey);
3948
3948
  }
@@ -3959,7 +3959,7 @@ var AccountStatusService = class {
3959
3959
  */
3960
3960
  async assertDashboardAccountUsable(ref) {
3961
3961
  const { userId, tenantId } = ref;
3962
- const { statusKey, verifiedKey } = cacheKeysFor(ref);
3962
+ const { statusKey, verifiedKey } = cacheKeysFor(ref, this.options.hmacKey);
3963
3963
  const cacheTtl = this.options.userStatusCacheTtlSeconds;
3964
3964
  const requireVerified = this.options.emailVerification.required;
3965
3965
  let status = await this.redis.get(statusKey);
@@ -8764,6 +8764,17 @@ var InvitationService = class _InvitationService {
8764
8764
  await this.redis.del(`inv:${supersededHash}`);
8765
8765
  }
8766
8766
  await this.redis.set(tokenKey, JSON.stringify(stored), ttl);
8767
+ let stillNamed;
8768
+ try {
8769
+ stillNamed = await this.claimInviteeIndex(normalizedEmail, tenantId, tokenHash, ttl, tokenHash);
8770
+ } catch (err) {
8771
+ await this.withdrawRecord(tokenKey);
8772
+ throw err;
8773
+ }
8774
+ if (!stillNamed.claimed) {
8775
+ await this.withdrawRecord(tokenKey);
8776
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
8777
+ }
8767
8778
  const displayTenantName = tenantName ?? tenantId;
8768
8779
  const expiresAt = new Date(Date.now() + ttl * 1e3);
8769
8780
  try {
@@ -8890,6 +8901,21 @@ var InvitationService = class _InvitationService {
8890
8901
  throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
8891
8902
  }
8892
8903
  /**
8904
+ * Removes the invitation record this call wrote, best-effort.
8905
+ *
8906
+ * Used where the call is already ending in a refusal or a failure of its own, so a failing
8907
+ * delete must not replace that outcome: it is logged and the caller still raises the original.
8908
+ * The raw token has not been emailed at that point, so a record that survives is one nobody
8909
+ * holds the token for, until its TTL.
8910
+ *
8911
+ * @param tokenKey - The Redis key of the record written by this call.
8912
+ */
8913
+ async withdrawRecord(tokenKey) {
8914
+ await this.redis.del(tokenKey).catch((err) => {
8915
+ this.logger.warn(`invite: could not withdraw the record \u2014 ${describeChannelStatus(err)}`);
8916
+ });
8917
+ }
8918
+ /**
8893
8919
  * Atomically points the invitee index at `tokenHash`, answering with the hash it displaced.
8894
8920
  *
8895
8921
  * A compare-and-swap, not a plain write: the claim proceeds only when the index still holds
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-auth",
3
- "version": "1.4.8",
3
+ "version": "1.4.10",
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",