@bymax-one/nest-auth 1.5.3 → 1.5.5

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.
@@ -2274,7 +2274,17 @@ var AUTH_ERROR_CODES = {
2274
2274
  * answers with. Without the filter the framework's own 500 shape stands, which is the
2275
2275
  * behaviour this library had before it existed.
2276
2276
  */
2277
- INTERNAL: "auth.internal"
2277
+ INTERNAL: "auth.internal",
2278
+ /**
2279
+ * A store this request depends on, Redis, did not answer in time or could not be reached, so
2280
+ * the request was refused and nothing was admitted. Retrying later may succeed; nothing here
2281
+ * knows when, so the answer carries no `Retry-After`.
2282
+ *
2283
+ * Raised by the library's Redis wrapper, not only by {@link AuthExceptionFilter}: it is a typed
2284
+ * exception, so any host filter that renders an `HttpException` answers it as a 503. The ioredis
2285
+ * error rides on the exception as `cause` and is never serialized.
2286
+ */
2287
+ SERVICE_UNAVAILABLE: "auth.service_unavailable"
2278
2288
  };
2279
2289
  var AUTH_ERROR_STATUS = {
2280
2290
  "auth.invalid_credentials": 401,
@@ -2326,7 +2336,8 @@ var AUTH_ERROR_STATUS = {
2326
2336
  "auth.registration_closed": 403,
2327
2337
  "auth.workspace_limit_reached": 403,
2328
2338
  "auth.workspace_pending_deletion": 409,
2329
- "auth.internal": 500
2339
+ "auth.internal": 500,
2340
+ "auth.service_unavailable": 503
2330
2341
  };
2331
2342
  var AUTH_ERROR_MESSAGES = {
2332
2343
  "auth.invalid_credentials": "Invalid email or password",
@@ -2378,7 +2389,8 @@ var AUTH_ERROR_MESSAGES = {
2378
2389
  "auth.registration_closed": "Registration is closed",
2379
2390
  "auth.workspace_limit_reached": "Workspace limit reached. Workspaces pending deletion count toward the limit.",
2380
2391
  "auth.workspace_pending_deletion": "Workspace is scheduled for deletion",
2381
- "auth.internal": "Internal server error"
2392
+ "auth.internal": "Internal server error",
2393
+ "auth.service_unavailable": "Service temporarily unavailable"
2382
2394
  };
2383
2395
  var MESSAGE_BY_CODE = new Map(Object.entries(AUTH_ERROR_MESSAGES));
2384
2396
  var STATUS_BY_CODE = new Map(Object.entries(AUTH_ERROR_STATUS));
@@ -2392,8 +2404,10 @@ var AuthException = class extends HttpException {
2392
2404
  * @param details - Optional structured payload attached to the error body under
2393
2405
  * `error.details`. An array where the failure is a list — `auth.validation` renders its
2394
2406
  * per-field failures that way, matching what rust-auth serializes for the same code.
2407
+ * @param options - `cause`: the error this one reports, kept on the exception for a host's
2408
+ * logger and never serialized into the body.
2395
2409
  */
2396
- constructor(code, details) {
2410
+ constructor(code, details, options) {
2397
2411
  super(
2398
2412
  {
2399
2413
  error: {
@@ -2406,11 +2420,88 @@ var AuthException = class extends HttpException {
2406
2420
  // A code with no entry is a programming error on the throwing side, not something the
2407
2421
  // caller did — 500 says so, and says it with a number rather than the `undefined` an
2408
2422
  // unguarded lookup used to hand to Express.
2409
- STATUS_BY_CODE.get(code) ?? HttpStatus.INTERNAL_SERVER_ERROR
2423
+ STATUS_BY_CODE.get(code) ?? HttpStatus.INTERNAL_SERVER_ERROR,
2424
+ options?.cause === void 0 ? void 0 : {
2425
+ cause: options.cause
2426
+ }
2410
2427
  );
2411
2428
  }
2412
2429
  };
2413
2430
 
2431
+ // src/server/redis/redis-outage.ts
2432
+ var MESSAGE_KINDS = /* @__PURE__ */ new Map([
2433
+ [
2434
+ "Command timed out",
2435
+ "timeout"
2436
+ ],
2437
+ [
2438
+ "Connection is closed.",
2439
+ "closed"
2440
+ ],
2441
+ [
2442
+ "Stream isn't writeable and enableOfflineQueue options is false",
2443
+ "closed"
2444
+ ]
2445
+ ]);
2446
+ var NETWORK_CODES = /* @__PURE__ */ new Set([
2447
+ "ECONNREFUSED",
2448
+ "ECONNRESET",
2449
+ "ETIMEDOUT",
2450
+ "EPIPE",
2451
+ "ENOTFOUND",
2452
+ "EAI_AGAIN",
2453
+ "EHOSTUNREACH",
2454
+ "ENETUNREACH"
2455
+ ]);
2456
+ var UNAVAILABLE_REPLIES = /* @__PURE__ */ new Set([
2457
+ "READONLY",
2458
+ "LOADING",
2459
+ "MASTERDOWN",
2460
+ "CLUSTERDOWN",
2461
+ "TRYAGAIN"
2462
+ ]);
2463
+ function redisOutageKindOf(error) {
2464
+ if (!(error instanceof Error)) return void 0;
2465
+ if (error.name === "MaxRetriesPerRequestError") return "unreachable";
2466
+ if (error.name === "ReplyError") {
2467
+ return UNAVAILABLE_REPLIES.has(error.message.split(" ", 1)[0]) ? "unavailable" : void 0;
2468
+ }
2469
+ const { code } = error;
2470
+ if (typeof code === "string" && NETWORK_CODES.has(code)) return "unreachable";
2471
+ return MESSAGE_KINDS.get(error.message);
2472
+ }
2473
+ __name(redisOutageKindOf, "redisOutageKindOf");
2474
+ function rethrowAsOutage(error) {
2475
+ if (redisOutageKindOf(error) === void 0) throw error;
2476
+ throw new AuthException(AUTH_ERROR_CODES.SERVICE_UNAVAILABLE, void 0, {
2477
+ cause: error
2478
+ });
2479
+ }
2480
+ __name(rethrowAsOutage, "rethrowAsOutage");
2481
+ function isServiceUnavailable(error) {
2482
+ if (!(error instanceof AuthException)) return false;
2483
+ const body = error.getResponse();
2484
+ return body.error?.code === AUTH_ERROR_CODES.SERVICE_UNAVAILABLE;
2485
+ }
2486
+ __name(isServiceUnavailable, "isServiceUnavailable");
2487
+ function isThenable(value) {
2488
+ return typeof value === "object" && value !== null && typeof value.then === "function";
2489
+ }
2490
+ __name(isThenable, "isThenable");
2491
+ function mappingOutages(redis) {
2492
+ return new Proxy(redis, {
2493
+ get(target, property) {
2494
+ const value = Reflect.get(target, property, target);
2495
+ if (typeof value !== "function") return value;
2496
+ return (...args) => {
2497
+ const result = Reflect.apply(value, target, args);
2498
+ return isThenable(result) ? result.then(void 0, rethrowAsOutage) : result;
2499
+ };
2500
+ }
2501
+ });
2502
+ }
2503
+ __name(mappingOutages, "mappingOutages");
2504
+
2414
2505
  // src/server/constants/user-subject.ts
2415
2506
  function userSubject(plane, userId, tenantId) {
2416
2507
  if (plane === "platform") return `platform:${userId}`;
@@ -2458,7 +2549,6 @@ function _ts_param(paramIndex, decorator) {
2458
2549
  };
2459
2550
  }
2460
2551
  __name(_ts_param, "_ts_param");
2461
- var EPOCH_TTL_SECONDS = TOKEN_EPOCH_RETENTION_SECONDS;
2462
2552
  var WS_TICKET_ENTROPY_BYTES = 32;
2463
2553
  var GRACE_TAG = "GRACE:";
2464
2554
  var REUSED_TAG = "REUSED:";
@@ -2626,7 +2716,7 @@ var AuthRedisService = class {
2626
2716
  */
2627
2717
  #hmacKey;
2628
2718
  constructor(redis, options) {
2629
- this.#redis = redis;
2719
+ this.#redis = mappingOutages(redis);
2630
2720
  this.namespace = options.redisNamespace;
2631
2721
  this.#hmacKey = options.hmacKey;
2632
2722
  }
@@ -3332,7 +3422,7 @@ var AuthRedisService = class {
3332
3422
  return v`, [
3333
3423
  key
3334
3424
  ], [
3335
- String(EPOCH_TTL_SECONDS)
3425
+ String(TOKEN_EPOCH_RETENTION_SECONDS)
3336
3426
  ]);
3337
3427
  return typeof result === "number" ? result : 0;
3338
3428
  }
@@ -6343,6 +6433,9 @@ function _ts_param13(paramIndex, decorator) {
6343
6433
  __name(_ts_param13, "_ts_param");
6344
6434
  var MFA_TEMP_TOKEN_TTL_SECONDS = 300;
6345
6435
  var MAX_SESSION_FIELD_LENGTH = 45;
6436
+ var CREDENTIAL_PROVED = {
6437
+ credentialProved: true
6438
+ };
6346
6439
  var TokenManagerService = class _TokenManagerService {
6347
6440
  static {
6348
6441
  __name(this, "TokenManagerService");
@@ -6440,8 +6533,8 @@ var TokenManagerService = class _TokenManagerService {
6440
6533
  * @param user - Safe user object (credential fields excluded).
6441
6534
  * @param ip - Client IP address (for session audit).
6442
6535
  * @param userAgent - User-Agent header value (for session description).
6443
- * @param overrides - Optional JWT claim overrides. Use `{ mfaVerified: true }` when
6444
- * issuing tokens after a successful MFA challenge.
6536
+ * @param overrides - Optional JWT claim overrides: `{ mfaVerified: true }` after an MFA challenge;
6537
+ * `credentialProved` (default `false`) is what lets the recent-authentication mark be written.
6445
6538
  * @returns Full auth result containing access token, raw refresh token, and user.
6446
6539
  */
6447
6540
  async issueTokens(user, ip, userAgent, overrides) {
@@ -6470,7 +6563,9 @@ var TokenManagerService = class _TokenManagerService {
6470
6563
  userId: user.id,
6471
6564
  refreshTtl: ttl
6472
6565
  });
6473
- await this.redis.set(recentAuthKey("dashboard", user.id, this.options.hmacKey, user.tenantId), "1", RECENT_AUTH_TTL_SECONDS);
6566
+ if (overrides?.credentialProved === true) {
6567
+ await this.redis.set(recentAuthKey("dashboard", user.id, this.options.hmacKey, user.tenantId), "1", RECENT_AUTH_TTL_SECONDS);
6568
+ }
6474
6569
  return {
6475
6570
  user,
6476
6571
  accessToken,
@@ -7304,7 +7399,7 @@ async function settlePendingLogout(redis, key, fromSession, owner, ttlSeconds, l
7304
7399
  return fromSession || removed;
7305
7400
  } catch (err) {
7306
7401
  logger.warn(`logout: the retry marker could not be cleared \u2014 ${describeChannelStatus(err)}`);
7307
- if (!fromSession) throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
7402
+ if (!fromSession) throw isServiceUnavailable(err) ? err : new AuthException(AUTH_ERROR_CODES.INTERNAL);
7308
7403
  return confirmNoStaleMarker(redis, key, owner, ttlSeconds, logger);
7309
7404
  }
7310
7405
  }
@@ -7312,8 +7407,9 @@ __name(settlePendingLogout, "settlePendingLogout");
7312
7407
  async function confirmNoStaleMarker(redis, key, owner, ttlSeconds, logger) {
7313
7408
  try {
7314
7409
  if (await redis.get(key) === null) return true;
7315
- } catch {
7410
+ } catch (err) {
7316
7411
  await rememberPendingLogout(redis, key, owner, ttlSeconds, logger);
7412
+ if (isServiceUnavailable(err)) throw err;
7317
7413
  }
7318
7414
  throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
7319
7415
  }
@@ -7584,7 +7680,7 @@ var AuthService = class _AuthService {
7584
7680
  await this.sendVerificationOtp(tenantId, dto.email, newUser.id);
7585
7681
  }
7586
7682
  const safeUser = toSafeUser2(newUser);
7587
- const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
7683
+ const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent, CREDENTIAL_PROVED);
7588
7684
  if (this.options.sessions.enabled) {
7589
7685
  await this.sessionService.createSession({
7590
7686
  userId: safeUser.id,
@@ -7708,7 +7804,7 @@ var AuthService = class _AuthService {
7708
7804
  };
7709
7805
  }
7710
7806
  const safeUser = toSafeUser2(user);
7711
- const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
7807
+ const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent, CREDENTIAL_PROVED);
7712
7808
  if (this.options.sessions.enabled) {
7713
7809
  await this.sessionService.createSession({
7714
7810
  userId: safeUser.id,
@@ -8041,7 +8137,7 @@ var AuthService = class _AuthService {
8041
8137
  * instead — issuing tokens with `mfaVerified: false` would let the
8042
8138
  * dashboard's `MfaRequiredGuard` lock the user out on every request.
8043
8139
  *
8044
- * Side effects mirror `login()`:
8140
+ * Unlike `login()`, the session is not a recent authentication. Other side effects mirror it:
8045
8141
  * - Concurrent-session limit enforced via `sessionService.createSession`
8046
8142
  * when `sessions.enabled`.
8047
8143
  * - `userRepo.updateLastLogin` runs non-blocking.
@@ -10109,7 +10205,7 @@ var InvitationService = class _InvitationService {
10109
10205
  emailVerified: true
10110
10206
  });
10111
10207
  const { passwordHash: _ph, mfaSecret: _ms, mfaRecoveryCodes: _mrc, ...safeUser } = authUser;
10112
- const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
10208
+ const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent, CREDENTIAL_PROVED);
10113
10209
  if (this.options.sessions.enabled) {
10114
10210
  await this.sessionService.createSession({
10115
10211
  userId: safeUser.id,
@@ -11307,7 +11403,8 @@ var MfaChallengeService = class {
11307
11403
  async issueDashboardSession(user, userId, ip, userAgent) {
11308
11404
  const safeUser = toSafeUser3(user);
11309
11405
  const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent, {
11310
- mfaVerified: true
11406
+ mfaVerified: true,
11407
+ credentialProved: true
11311
11408
  });
11312
11409
  if (this.options.sessions.enabled) {
11313
11410
  await this.sessionService.createSession({
@@ -12994,7 +13091,7 @@ async function answerResetRequest(deps, request) {
12994
13091
  } catch (err) {
12995
13092
  logger.error(`${label}: cooldown store failed: ${describeChannelStatus(err)}`);
12996
13093
  await holdFloor();
12997
- throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
13094
+ throw isServiceUnavailable(err) ? err : new AuthException(AUTH_ERROR_CODES.INTERNAL);
12998
13095
  }
12999
13096
  if (!claimed) {
13000
13097
  await holdFloor();
@@ -13121,10 +13218,9 @@ var PasswordResetService = class _PasswordResetService {
13121
13218
  * - The account is blocked.
13122
13219
  * - Issuing or storing the code, or the email provider, fails for an account that exists.
13123
13220
  *
13124
- * A failure that is the same for every address, the resend-cooldown store or the account
13125
- * lookup, throws `INTERNAL` (500) after the floor, and the cooldown this call took is
13126
- * released. This anti-enumeration design ensures the response cannot be used to probe
13127
- * whether an email address is registered.
13221
+ * What a failure answers, and when the cooldown this call took is released, is decided in one
13222
+ * place, {@link answerResetRequest}. The response cannot be used to probe whether an email
13223
+ * address is registered.
13128
13224
  *
13129
13225
  * Timing normalization: the method always takes at least {@link ANTI_ENUM_MIN_MS}
13130
13226
  * milliseconds to respond, regardless of whether the user was found.
@@ -13232,8 +13328,8 @@ var PasswordResetService = class _PasswordResetService {
13232
13328
  *
13233
13329
  * Subject to an atomic 60-second cooldown enforced via a Redis NX key to
13234
13330
  * prevent OTP flooding. Resolves the same way whether or not the user exists —
13235
- * anti-enumeration principle; a failure of the cooldown store or the account lookup
13236
- * throws `INTERNAL` (500) after the floor and releases the cooldown.
13331
+ * anti-enumeration principle; what a failure answers is decided in one place,
13332
+ * {@link answerResetRequest}.
13237
13333
  *
13238
13334
  * Timing normalization: always takes at least {@link ANTI_ENUM_MIN_MS} ms.
13239
13335
  *
@@ -13731,8 +13827,8 @@ var PasswordResetController = class {
13731
13827
  *
13732
13828
  * Sends a reset token or OTP to the user's email if the account exists and
13733
13829
  * is eligible. Answers `200 OK` with an empty JSON object whether or not the account exists
13734
- * (anti-enumeration; the body is pinned by the wire contract). Only a failure that is the same
13735
- * for every address, the cooldown store or the account lookup, answers `500` `auth.internal`.
13830
+ * (anti-enumeration; the body is pinned by the wire contract). What a failure answers is
13831
+ * decided in one place, `answerResetRequest` (utils/answer-reset-request.ts).
13736
13832
  *
13737
13833
  * @param dto - Validated DTO with `email` and `tenantId`.
13738
13834
  * @returns An empty object.
@@ -13820,8 +13916,8 @@ var PasswordResetController = class {
13820
13916
  *
13821
13917
  * Subject to a 60-second atomic cooldown per `(tenantId, email)` pair.
13822
13918
  * Answers `200 OK` with an empty JSON object whether or not the account exists
13823
- * (anti-enumeration; the body is pinned by the wire contract). Only a failure that is the same
13824
- * for every address, the cooldown store or the account lookup, answers `500` `auth.internal`.
13919
+ * (anti-enumeration; the body is pinned by the wire contract). What a failure answers is
13920
+ * decided in one place, `answerResetRequest` (utils/answer-reset-request.ts).
13825
13921
  *
13826
13922
  * @param dto - Validated DTO with `email` and `tenantId`.
13827
13923
  * @returns An empty object.
@@ -17227,7 +17323,7 @@ var WorkspaceInvitationAcceptService = class _WorkspaceInvitationAcceptService {
17227
17323
  }
17228
17324
  /** Issues the new account's session as a sign-in does, and fires the host's hook. */
17229
17325
  async signIn(user, request, context) {
17230
- const result = await this.tokens.issueTokens(user, request.ip, request.userAgent);
17326
+ const result = await this.tokens.issueTokens(user, request.ip, request.userAgent, CREDENTIAL_PROVED);
17231
17327
  if (this.options.sessions.enabled) {
17232
17328
  await this.sessions.createSession({
17233
17329
  userId: user.id,
@@ -20581,7 +20677,7 @@ var OAuthService = class _OAuthService {
20581
20677
  */
20582
20678
  async openSession(authUser, provider, hookResult, hookContext, ip, userAgent) {
20583
20679
  const safeUser = toSafeUser5(authUser);
20584
- const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
20680
+ const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent, CREDENTIAL_PROVED);
20585
20681
  if (this.options.sessions.enabled) {
20586
20682
  await this.sessionService.createSession({
20587
20683
  userId: safeUser.id,
@@ -100,7 +100,12 @@ var AUTH_ERROR_CODES = {
100
100
  * An unexpected internal failure. Raised only by the server's optional `AuthExceptionFilter`,
101
101
  * which gives unhandled failures the same envelope everything else answers with.
102
102
  */
103
- INTERNAL: "auth.internal"
103
+ INTERNAL: "auth.internal",
104
+ /**
105
+ * A store the request depends on, Redis, did not answer in time or could not be reached, so
106
+ * the request was refused and nothing was admitted. A client may retry later.
107
+ */
108
+ SERVICE_UNAVAILABLE: "auth.service_unavailable"
104
109
  };
105
110
  var AUTH_ERROR_STATUS = {
106
111
  "auth.invalid_credentials": 401,
@@ -152,7 +157,8 @@ var AUTH_ERROR_STATUS = {
152
157
  "auth.registration_closed": 403,
153
158
  "auth.workspace_limit_reached": 403,
154
159
  "auth.workspace_pending_deletion": 409,
155
- "auth.internal": 500
160
+ "auth.internal": 500,
161
+ "auth.service_unavailable": 503
156
162
  };
157
163
 
158
164
  // src/shared/utils/fill-route.ts
@@ -150,6 +150,11 @@ declare const AUTH_ERROR_CODES: {
150
150
  * which gives unhandled failures the same envelope everything else answers with.
151
151
  */
152
152
  readonly INTERNAL: "auth.internal";
153
+ /**
154
+ * A store the request depends on, Redis, did not answer in time or could not be reached, so
155
+ * the request was refused and nothing was admitted. A client may retry later.
156
+ */
157
+ readonly SERVICE_UNAVAILABLE: "auth.service_unavailable";
153
158
  };
154
159
  /**
155
160
  * String literal union of every `AUTH_ERROR_CODES` value.
@@ -150,6 +150,11 @@ declare const AUTH_ERROR_CODES: {
150
150
  * which gives unhandled failures the same envelope everything else answers with.
151
151
  */
152
152
  readonly INTERNAL: "auth.internal";
153
+ /**
154
+ * A store the request depends on, Redis, did not answer in time or could not be reached, so
155
+ * the request was refused and nothing was admitted. A client may retry later.
156
+ */
157
+ readonly SERVICE_UNAVAILABLE: "auth.service_unavailable";
153
158
  };
154
159
  /**
155
160
  * String literal union of every `AUTH_ERROR_CODES` value.
@@ -98,7 +98,12 @@ var AUTH_ERROR_CODES = {
98
98
  * An unexpected internal failure. Raised only by the server's optional `AuthExceptionFilter`,
99
99
  * which gives unhandled failures the same envelope everything else answers with.
100
100
  */
101
- INTERNAL: "auth.internal"
101
+ INTERNAL: "auth.internal",
102
+ /**
103
+ * A store the request depends on, Redis, did not answer in time or could not be reached, so
104
+ * the request was refused and nothing was admitted. A client may retry later.
105
+ */
106
+ SERVICE_UNAVAILABLE: "auth.service_unavailable"
102
107
  };
103
108
  var AUTH_ERROR_STATUS = {
104
109
  "auth.invalid_credentials": 401,
@@ -150,7 +155,8 @@ var AUTH_ERROR_STATUS = {
150
155
  "auth.registration_closed": 403,
151
156
  "auth.workspace_limit_reached": 403,
152
157
  "auth.workspace_pending_deletion": 409,
153
- "auth.internal": 500
158
+ "auth.internal": 500,
159
+ "auth.service_unavailable": 503
154
160
  };
155
161
 
156
162
  // src/shared/utils/fill-route.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-auth",
3
- "version": "1.5.3",
3
+ "version": "1.5.5",
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",
@@ -228,7 +228,7 @@
228
228
  "reflect-metadata": "^0.2.2",
229
229
  "socket.io": "^4.8.3",
230
230
  "socket.io-client": "^4.8.3",
231
- "supertest": "^7.2.2",
231
+ "supertest": "^7.3.1",
232
232
  "testcontainers": "^12.2.1",
233
233
  "ts-jest": "^29.4.9",
234
234
  "ts-node": "^10.9.2",