@bymax-one/nest-auth 1.4.16 → 1.4.17
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 +60 -1
- package/dist/server/index.cjs +160 -47
- package/dist/server/index.d.cts +61 -13
- package/dist/server/index.d.ts +61 -13
- package/dist/server/index.mjs +161 -48
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -18,6 +18,64 @@ what moves, and that note is the compatibility contract until strict SemVer begi
|
|
|
18
18
|
|
|
19
19
|
## [Unreleased]
|
|
20
20
|
|
|
21
|
+
## [1.4.17] - 2026-11-07
|
|
22
|
+
|
|
23
|
+
### Apply to a derived backend
|
|
24
|
+
|
|
25
|
+
- **`AuthExceptionFilter` now answers a request the HTTP layer refused with a client-error
|
|
26
|
+
envelope, not `auth.internal`.** Applies only where the filter is registered, and only on
|
|
27
|
+
Express (the filter writes through Express's `Response`; nothing here is defined for Fastify).
|
|
28
|
+
A malformed JSON body, a bare JSON string or number, a form body nested past the parser's
|
|
29
|
+
depth limit, and a path that cannot be decoded now answer `400 auth.validation` with the fixed
|
|
30
|
+
message `Malformed request`; the parser's own text, which could quote the start of the body, is
|
|
31
|
+
no longer in the response. An oversized body answers `413` and an unsupported charset or
|
|
32
|
+
content-encoding `415`, both `auth.validation`, where they answered `500 auth.internal`. A client that branched on `auth.internal` for these must branch on
|
|
33
|
+
`auth.validation` and the status. The 400 is recognised by having been raised before any route
|
|
34
|
+
matched (`req.route` unset), so a `BadRequestException` thrown by the application's own
|
|
35
|
+
middleware that runs before routing is answered the same generic way; one thrown from a
|
|
36
|
+
handler, guard, pipe or service keeps its message and `auth.internal`. The new `transportErrors`
|
|
37
|
+
section of `conformance/wire-contract.json` lists the rows; `errorCatalog.statuses` still holds
|
|
38
|
+
one status per code. No public member is added or changed.
|
|
39
|
+
- **A production deployment can no longer start with `secureCookies: false`.** `environment` is
|
|
40
|
+
`'production'` when unset, so a configuration that sets `secureCookies: false` without declaring
|
|
41
|
+
`environment: 'development'` or `'test'` now throws at startup, after the `SameSite=None` check,
|
|
42
|
+
with a message that contains "secureCookies is false but environment is 'production' (the default
|
|
43
|
+
when unset)." Remove the option, set it to `true`, or declare the environment. A session cookie
|
|
44
|
+
without `Secure` travels over plain HTTP, and a TLS-terminating proxy still serves HTTPS to the
|
|
45
|
+
browser. Omitting `secureCookies` and setting it to `true` are unchanged. No public member is
|
|
46
|
+
added or changed.
|
|
47
|
+
- **A refresh token that rotated a moment ago now stands for the session that replaced it, on
|
|
48
|
+
`POST /password/change` and `POST /sessions/revoke-all`.** A refresh of the caller's own session
|
|
49
|
+
that landed while the request was being handled turned the token it carried into a rotation
|
|
50
|
+
predecessor, and both routes answered `404 auth.session_not_found`; a password change left the
|
|
51
|
+
password unchanged. A presented token now counts when it is a live session or when its grace
|
|
52
|
+
pointer (`rp:{hash}`) names a live successor, and that successor is the session kept. It is one
|
|
53
|
+
hop, the pointer is read and never consumed or extended, and a token past the grace window is
|
|
54
|
+
still refused with `404`. The current password still gates the change. When the session to keep
|
|
55
|
+
cannot be resolved after the new password is written, every session still ends, as before; a
|
|
56
|
+
session that rotated while the new password was being hashed is no longer among them, since it
|
|
57
|
+
is the caller's device and now survives. `SessionService` gains a public
|
|
58
|
+
`resolveLiveSession(params)` returning the hash to keep, `assertLiveSession` takes
|
|
59
|
+
`params: LiveSessionParams`, and private `isLiveMember`, `resolveLiveMember` and `graceSuccessor`
|
|
60
|
+
replace the private `requireLiveMember`. In `PasswordResetService` the private `requireLiveCurrentSession` becomes
|
|
61
|
+
`resolveCurrentSession`, and `endOtherSessions` now takes the hash to keep.
|
|
62
|
+
- **A login no longer evicts a session when the store fails to read a session record.** The
|
|
63
|
+
session limit ranks sessions by the creation time in each one's detail record; a read the store
|
|
64
|
+
failed was ranked as the oldest, so a transient Redis fault could end a live, newest device. Now
|
|
65
|
+
no session is evicted by that login, one error is logged without any key or hash, and the limit
|
|
66
|
+
is checked again by the next login. An absent or unparseable detail record is not a fault and
|
|
67
|
+
still ranks as the oldest. While such reads fail no login evicts, so the limit is unenforced.
|
|
68
|
+
A private `readCreatedAt` appears in the `SessionService` declarations.
|
|
69
|
+
|
|
70
|
+
### Fixed
|
|
71
|
+
|
|
72
|
+
- **Requests refused by the body parser no longer answer `500` or echo the body.** See the note
|
|
73
|
+
above.
|
|
74
|
+
- **A password change or revoke-all no longer fails when the caller refreshes the session
|
|
75
|
+
concurrently.** See the note above.
|
|
76
|
+
- **A store fault while ranking sessions no longer evicts a live session.** See the note above.
|
|
77
|
+
- **`secureCookies: false` in a production deployment is refused at startup.** See the note above.
|
|
78
|
+
|
|
21
79
|
## [1.4.16] - 2026-11-06
|
|
22
80
|
|
|
23
81
|
### Apply to a derived backend
|
|
@@ -4360,7 +4418,8 @@ ever installable.
|
|
|
4360
4418
|
- 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
|
|
4361
4419
|
- 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
|
|
4362
4420
|
|
|
4363
|
-
[Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.
|
|
4421
|
+
[Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.17...HEAD
|
|
4422
|
+
[1.4.17]: https://github.com/bymaxone/nest-auth/compare/v1.4.16...v1.4.17
|
|
4364
4423
|
[1.4.16]: https://github.com/bymaxone/nest-auth/compare/v1.4.15...v1.4.16
|
|
4365
4424
|
[1.4.15]: https://github.com/bymaxone/nest-auth/compare/v1.4.14...v1.4.15
|
|
4366
4425
|
[1.4.14]: https://github.com/bymaxone/nest-auth/compare/v1.4.13...v1.4.14
|
package/dist/server/index.cjs
CHANGED
|
@@ -353,6 +353,7 @@ function resolveOptions(userOptions) {
|
|
|
353
353
|
validateOAuthErrorRedirectUrl(userOptions);
|
|
354
354
|
validateRefreshCookiePath(userOptions.routePrefix, userOptions.cookies);
|
|
355
355
|
validateSameSiteNoneRequiresSecure(userOptions);
|
|
356
|
+
validateProductionCookiesAreSecure(userOptions);
|
|
356
357
|
validateCookiePrefixes(userOptions);
|
|
357
358
|
validateTrustedOrigins(userOptions);
|
|
358
359
|
validateRefreshGraceWindow(userOptions.jwt);
|
|
@@ -913,6 +914,11 @@ function validateSameSiteNoneRequiresSecure(userOptions) {
|
|
|
913
914
|
}
|
|
914
915
|
}
|
|
915
916
|
__name(validateSameSiteNoneRequiresSecure, "validateSameSiteNoneRequiresSecure");
|
|
917
|
+
function validateProductionCookiesAreSecure(userOptions) {
|
|
918
|
+
if (userOptions.secureCookies !== false || !isProductionDeployment(userOptions)) return;
|
|
919
|
+
throw new Error(`[BymaxAuthModule] secureCookies is false but environment is 'production' (the default when unset). A session cookie without the Secure attribute is sent over plain HTTP. Set secureCookies: true (a TLS-terminating proxy still serves HTTPS to the browser), or declare environment: 'development' or 'test' for local HTTP.`);
|
|
920
|
+
}
|
|
921
|
+
__name(validateProductionCookiesAreSecure, "validateProductionCookiesAreSecure");
|
|
916
922
|
function validateTrustedOrigins(userOptions) {
|
|
917
923
|
const sameSite = userOptions.cookies?.sameSite ?? DEFAULT_OPTIONS.cookies.sameSite;
|
|
918
924
|
const trustedOrigins = userOptions.cookies?.trustedOrigins ?? [];
|
|
@@ -5240,16 +5246,35 @@ exports.SessionService = class _SessionService {
|
|
|
5240
5246
|
* Refuses a session hash that names no live session of this user.
|
|
5241
5247
|
*
|
|
5242
5248
|
* For an operation that keeps one session and ends the rest and so has to be told which one,
|
|
5243
|
-
* checked before it changes anything. The membership test is the
|
|
5244
|
-
*
|
|
5249
|
+
* checked before it changes anything. The membership test is the one {@link resolveLiveSession}
|
|
5250
|
+
* applies, so a token that has just rotated is accepted here exactly as it is there.
|
|
5245
5251
|
*
|
|
5246
5252
|
* @param params - See {@link LiveSessionParams}.
|
|
5247
5253
|
* @throws {@link AuthException} `SESSION_NOT_FOUND` when the hash is not a live session.
|
|
5248
5254
|
*/
|
|
5249
|
-
async assertLiveSession(
|
|
5255
|
+
async assertLiveSession(params) {
|
|
5256
|
+
await this.resolveLiveSession(params);
|
|
5257
|
+
}
|
|
5258
|
+
/**
|
|
5259
|
+
* Names the live session a presented refresh-token hash stands for.
|
|
5260
|
+
*
|
|
5261
|
+
* The hash itself when it is a live session. When it is a token that rotated away moments ago,
|
|
5262
|
+
* the session the rotation produced: the rotation grace pointer `rp:{hash}` names that successor,
|
|
5263
|
+
* and the presented token still identifies the same device. A request that carries a refresh
|
|
5264
|
+
* token can lose a race to a refresh of the same session, and an operation that must keep "the
|
|
5265
|
+
* caller's session" would otherwise refuse the caller for having been refreshed. The pointer is
|
|
5266
|
+
* read, never consumed, and the successor has to be live in the index too, so a pointer left
|
|
5267
|
+
* behind by a session that was since revoked names nothing.
|
|
5268
|
+
*
|
|
5269
|
+
* @param params - See {@link LiveSessionParams}.
|
|
5270
|
+
* @returns The hash of the live session to keep: `sessionHash`, or its live successor.
|
|
5271
|
+
* @throws {@link AuthException} `SESSION_NOT_FOUND` when the hash is neither a live session nor
|
|
5272
|
+
* the predecessor of one.
|
|
5273
|
+
*/
|
|
5274
|
+
async resolveLiveSession({ userId, tenantId, sessionHash }) {
|
|
5250
5275
|
this.assertTenant(tenantId);
|
|
5251
5276
|
this.assertValidSessionHash(sessionHash, "sessionHash");
|
|
5252
|
-
this.
|
|
5277
|
+
return this.resolveLiveMember(await this.redis.smembers(this.indexKey(userId, tenantId)), sessionHash);
|
|
5253
5278
|
}
|
|
5254
5279
|
/**
|
|
5255
5280
|
* Revokes all sessions for a user except the caller's current session.
|
|
@@ -5286,11 +5311,11 @@ exports.SessionService = class _SessionService {
|
|
|
5286
5311
|
this.assertTenant(tenantId);
|
|
5287
5312
|
this.assertValidSessionHash(currentSessionHash, "currentSessionHash");
|
|
5288
5313
|
const members = await this.redis.smembers(this.indexKey(userId, tenantId));
|
|
5289
|
-
this.
|
|
5314
|
+
const keptHash = await this.resolveLiveMember(members, currentSessionHash);
|
|
5290
5315
|
const rtMembers = members.filter((m) => m.startsWith("rt:"));
|
|
5291
5316
|
for (const member of rtMembers) {
|
|
5292
5317
|
const hash = member.slice(3);
|
|
5293
|
-
if (timingSafeCompare(hash,
|
|
5318
|
+
if (timingSafeCompare(hash, keptHash)) continue;
|
|
5294
5319
|
try {
|
|
5295
5320
|
await this.revokeSession({
|
|
5296
5321
|
userId,
|
|
@@ -5411,13 +5436,33 @@ exports.SessionService = class _SessionService {
|
|
|
5411
5436
|
}
|
|
5412
5437
|
}
|
|
5413
5438
|
/**
|
|
5414
|
-
*
|
|
5439
|
+
* The hash of the live refresh session `sessionHash` stands for within `members`.
|
|
5415
5440
|
*
|
|
5416
5441
|
* @throws {@link AuthException} `SESSION_NOT_FOUND`.
|
|
5417
5442
|
*/
|
|
5418
|
-
|
|
5419
|
-
|
|
5420
|
-
|
|
5443
|
+
async resolveLiveMember(members, sessionHash) {
|
|
5444
|
+
if (this.isLiveMember(members, sessionHash)) return sessionHash;
|
|
5445
|
+
const successor = await this.graceSuccessor(sessionHash);
|
|
5446
|
+
if (successor !== void 0 && this.isLiveMember(members, successor)) return successor;
|
|
5447
|
+
throw new AuthException(AUTH_ERROR_CODES.SESSION_NOT_FOUND);
|
|
5448
|
+
}
|
|
5449
|
+
/** Whether `members` holds a live refresh session with this hash. */
|
|
5450
|
+
isLiveMember(members, sessionHash) {
|
|
5451
|
+
return members.some((member) => member.startsWith("rt:") && timingSafeCompare(member.slice(3), sessionHash));
|
|
5452
|
+
}
|
|
5453
|
+
/**
|
|
5454
|
+
* The successor hash a rotation grace pointer names, or `undefined` when there is none.
|
|
5455
|
+
*
|
|
5456
|
+
* The pointer's value is `{successorHash}:{record}`, split on the first colon exactly as the
|
|
5457
|
+
* rotation script writes it.
|
|
5458
|
+
*/
|
|
5459
|
+
async graceSuccessor(sessionHash) {
|
|
5460
|
+
const pointer = await this.redis.get(`rp:${sessionHash}`);
|
|
5461
|
+
if (pointer === null) return void 0;
|
|
5462
|
+
const separator = pointer.indexOf(":");
|
|
5463
|
+
if (separator < 0) return void 0;
|
|
5464
|
+
const successor = pointer.slice(0, separator);
|
|
5465
|
+
return SESSION_HASH_RE.test(successor) ? successor : void 0;
|
|
5421
5466
|
}
|
|
5422
5467
|
/**
|
|
5423
5468
|
* The Redis key of this user's session index.
|
|
@@ -5462,28 +5507,18 @@ exports.SessionService = class _SessionService {
|
|
|
5462
5507
|
const rtMembers = members.filter((m) => m.startsWith("rt:"));
|
|
5463
5508
|
const limit = await this.resolveSessionLimit(userId, tenantId);
|
|
5464
5509
|
if (rtMembers.length <= limit) return;
|
|
5465
|
-
|
|
5466
|
-
|
|
5467
|
-
|
|
5468
|
-
try {
|
|
5469
|
-
const raw = await this.redis.get(`sd:${memberHash}`);
|
|
5470
|
-
if (raw !== null) {
|
|
5471
|
-
const parsed = JSON.parse(raw);
|
|
5472
|
-
if (
|
|
5473
|
-
// Stryker disable next-line ConditionalExpression: defensive `parsed !== null` guard masked by the surrounding try/catch fallback, yielding the same result
|
|
5474
|
-
parsed !== null && typeof parsed === "object" && "createdAt" in parsed && typeof parsed["createdAt"] === "number"
|
|
5475
|
-
) {
|
|
5476
|
-
createdAt = parsed.createdAt;
|
|
5477
|
-
}
|
|
5478
|
-
}
|
|
5479
|
-
} catch {
|
|
5480
|
-
}
|
|
5481
|
-
return {
|
|
5510
|
+
let withTimestamps;
|
|
5511
|
+
try {
|
|
5512
|
+
withTimestamps = await Promise.all(rtMembers.map(async (member) => ({
|
|
5482
5513
|
member,
|
|
5483
|
-
|
|
5484
|
-
|
|
5485
|
-
|
|
5486
|
-
|
|
5514
|
+
// member is "rt:{hash}" — extract just the hash portion.
|
|
5515
|
+
memberHash: member.slice(3),
|
|
5516
|
+
createdAt: await this.readCreatedAt(member.slice(3))
|
|
5517
|
+
})));
|
|
5518
|
+
} catch (err) {
|
|
5519
|
+
this.logger.error(`enforceSessionLimit: eviction skipped for user ${logSafe(userId)}, a session record could not be read: ${describeChannelStatus(err)}`);
|
|
5520
|
+
return;
|
|
5521
|
+
}
|
|
5487
5522
|
withTimestamps.sort((a, b) => a.createdAt - b.createdAt);
|
|
5488
5523
|
const evictCount = rtMembers.length - limit;
|
|
5489
5524
|
const toEvict = withTimestamps.filter((entry) => entry.memberHash !== newHash).slice(0, evictCount);
|
|
@@ -5512,6 +5547,29 @@ exports.SessionService = class _SessionService {
|
|
|
5512
5547
|
}
|
|
5513
5548
|
}
|
|
5514
5549
|
/**
|
|
5550
|
+
* The creation time of a session, for ranking sessions by age.
|
|
5551
|
+
*
|
|
5552
|
+
* An absent record and one that is not a detail record both rank as `0`, the oldest: a state the
|
|
5553
|
+
* store reported, not a fault. A read the store fails propagates, because no age can be named.
|
|
5554
|
+
*
|
|
5555
|
+
* @param memberHash - SHA-256 hash of the session's refresh token.
|
|
5556
|
+
*/
|
|
5557
|
+
async readCreatedAt(memberHash) {
|
|
5558
|
+
const raw = await this.redis.get(`sd:${memberHash}`);
|
|
5559
|
+
if (raw === null) return 0;
|
|
5560
|
+
try {
|
|
5561
|
+
const parsed = JSON.parse(raw);
|
|
5562
|
+
if (
|
|
5563
|
+
// Stryker disable next-line ConditionalExpression: defensive `parsed !== null` guard masked by the surrounding try/catch fallback, yielding the same result
|
|
5564
|
+
parsed !== null && typeof parsed === "object" && "createdAt" in parsed && typeof parsed["createdAt"] === "number"
|
|
5565
|
+
) {
|
|
5566
|
+
return parsed.createdAt;
|
|
5567
|
+
}
|
|
5568
|
+
} catch {
|
|
5569
|
+
}
|
|
5570
|
+
return 0;
|
|
5571
|
+
}
|
|
5572
|
+
/**
|
|
5515
5573
|
* Resolves the maximum number of concurrent sessions allowed for a user.
|
|
5516
5574
|
*
|
|
5517
5575
|
* When `options.sessions.maxSessionsResolver` is configured, it is called with
|
|
@@ -12135,7 +12193,7 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
12135
12193
|
throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
|
|
12136
12194
|
}
|
|
12137
12195
|
await this.bruteForce.resetFailures(bfIdentifier);
|
|
12138
|
-
await this.
|
|
12196
|
+
const keptHash = await this.resolveCurrentSession(userId, user.tenantId, currentRefreshToken);
|
|
12139
12197
|
await this.passwordService.assertAcceptable(dto.newPassword, "newPassword");
|
|
12140
12198
|
const passwordHash = await this.passwordService.hash(dto.newPassword);
|
|
12141
12199
|
await this.userRepo.updatePassword({
|
|
@@ -12143,36 +12201,40 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
12143
12201
|
tenantId,
|
|
12144
12202
|
passwordHash
|
|
12145
12203
|
});
|
|
12146
|
-
await this.endOtherSessions(userId, user.tenantId,
|
|
12204
|
+
await this.endOtherSessions(userId, user.tenantId, keptHash);
|
|
12147
12205
|
await this.notifyPasswordChanged(user);
|
|
12148
12206
|
}
|
|
12149
|
-
/**
|
|
12150
|
-
|
|
12151
|
-
|
|
12152
|
-
|
|
12207
|
+
/**
|
|
12208
|
+
* The hash of the live session a presented refresh token stands for, or `undefined` when the
|
|
12209
|
+
* request carried none. Refuses a token that names no live session of the account; a token that
|
|
12210
|
+
* rotated away while the password was being verified stands for the session that replaced it.
|
|
12211
|
+
*/
|
|
12212
|
+
async resolveCurrentSession(userId, tenantId, currentRefreshToken) {
|
|
12213
|
+
if (currentRefreshToken === void 0 || currentRefreshToken.length === 0) return void 0;
|
|
12214
|
+
return this.sessionService.resolveLiveSession({
|
|
12153
12215
|
userId,
|
|
12154
12216
|
tenantId,
|
|
12155
12217
|
sessionHash: sha256(currentRefreshToken)
|
|
12156
12218
|
});
|
|
12157
12219
|
}
|
|
12158
12220
|
/**
|
|
12159
|
-
* Ends every session but the
|
|
12221
|
+
* Ends every session but the one to keep, once the new password is already written.
|
|
12160
12222
|
*
|
|
12161
|
-
* With no
|
|
12162
|
-
*
|
|
12163
|
-
* no current session left to
|
|
12164
|
-
* change safe is never aborted by the session it was told to spare. Any other failure of
|
|
12165
|
-
* sweep propagates.
|
|
12223
|
+
* With no session to keep every session ends. A kept session can rotate away while the new
|
|
12224
|
+
* password is hashed; the sweep follows it to its successor, and when it cannot be followed
|
|
12225
|
+
* there is no current session left to spare, so every session ends and the cleanup that makes
|
|
12226
|
+
* the change safe is never aborted by the session it was told to spare. Any other failure of
|
|
12227
|
+
* the sweep propagates.
|
|
12166
12228
|
*/
|
|
12167
|
-
async endOtherSessions(userId, tenantId,
|
|
12168
|
-
if (
|
|
12229
|
+
async endOtherSessions(userId, tenantId, keptHash) {
|
|
12230
|
+
if (keptHash === void 0) {
|
|
12169
12231
|
return this.endAllSessions(userId, tenantId);
|
|
12170
12232
|
}
|
|
12171
12233
|
try {
|
|
12172
12234
|
await this.sessionService.revokeAllExceptCurrent({
|
|
12173
12235
|
userId,
|
|
12174
12236
|
tenantId,
|
|
12175
|
-
currentSessionHash:
|
|
12237
|
+
currentSessionHash: keptHash
|
|
12176
12238
|
});
|
|
12177
12239
|
} catch (err) {
|
|
12178
12240
|
const body = err instanceof AuthException ? err.getResponse() : void 0;
|
|
@@ -18519,6 +18581,35 @@ function isAuthEnvelope(body) {
|
|
|
18519
18581
|
return typeof error === "object" && error !== null && "code" in error;
|
|
18520
18582
|
}
|
|
18521
18583
|
__name(isAuthEnvelope, "isAuthEnvelope");
|
|
18584
|
+
var BODY_PARSER_ERROR_TYPES = /* @__PURE__ */ new Set([
|
|
18585
|
+
"entity.parse.failed",
|
|
18586
|
+
"entity.too.large",
|
|
18587
|
+
"entity.verify.failed",
|
|
18588
|
+
"charset.unsupported",
|
|
18589
|
+
"encoding.unsupported",
|
|
18590
|
+
"request.aborted",
|
|
18591
|
+
"request.size.invalid",
|
|
18592
|
+
"querystring.parse.rangeError",
|
|
18593
|
+
"parameters.too.many"
|
|
18594
|
+
]);
|
|
18595
|
+
var MALFORMED_REQUEST_MESSAGE = "Malformed request";
|
|
18596
|
+
function bodyParserStatus(exception) {
|
|
18597
|
+
if (typeof exception !== "object" || exception === null) return void 0;
|
|
18598
|
+
const { type, status } = exception;
|
|
18599
|
+
if (typeof type !== "string" || !BODY_PARSER_ERROR_TYPES.has(type)) return void 0;
|
|
18600
|
+
return typeof status === "number" && status >= 400 && status < 500 ? status : void 0;
|
|
18601
|
+
}
|
|
18602
|
+
__name(bodyParserStatus, "bodyParserStatus");
|
|
18603
|
+
function bodyParserMessage(status) {
|
|
18604
|
+
if (status === common.HttpStatus.PAYLOAD_TOO_LARGE) return "Request entity too large";
|
|
18605
|
+
if (status === common.HttpStatus.UNSUPPORTED_MEDIA_TYPE) return "Unsupported media type";
|
|
18606
|
+
return MALFORMED_REQUEST_MESSAGE;
|
|
18607
|
+
}
|
|
18608
|
+
__name(bodyParserMessage, "bodyParserMessage");
|
|
18609
|
+
function isPreRoutingBadRequest(exception, req) {
|
|
18610
|
+
return exception instanceof common.BadRequestException && req.route === void 0;
|
|
18611
|
+
}
|
|
18612
|
+
__name(isPreRoutingBadRequest, "isPreRoutingBadRequest");
|
|
18522
18613
|
exports.AuthExceptionFilter = class _AuthExceptionFilter {
|
|
18523
18614
|
static {
|
|
18524
18615
|
__name(this, "AuthExceptionFilter");
|
|
@@ -18531,7 +18622,8 @@ exports.AuthExceptionFilter = class _AuthExceptionFilter {
|
|
|
18531
18622
|
* @param host - The arguments host, used to reach the HTTP response.
|
|
18532
18623
|
*/
|
|
18533
18624
|
catch(exception, host) {
|
|
18534
|
-
const
|
|
18625
|
+
const http = host.switchToHttp();
|
|
18626
|
+
const res = http.getResponse();
|
|
18535
18627
|
if (exception instanceof AuthException) {
|
|
18536
18628
|
res.status(exception.getStatus()).json(exception.getResponse());
|
|
18537
18629
|
return;
|
|
@@ -18542,6 +18634,16 @@ exports.AuthExceptionFilter = class _AuthExceptionFilter {
|
|
|
18542
18634
|
res.status(exception.getStatus()).json(body);
|
|
18543
18635
|
return;
|
|
18544
18636
|
}
|
|
18637
|
+
if (isPreRoutingBadRequest(exception, http.getRequest())) {
|
|
18638
|
+
res.status(common.HttpStatus.BAD_REQUEST).json({
|
|
18639
|
+
error: {
|
|
18640
|
+
code: AUTH_ERROR_CODES.VALIDATION,
|
|
18641
|
+
message: MALFORMED_REQUEST_MESSAGE,
|
|
18642
|
+
details: null
|
|
18643
|
+
}
|
|
18644
|
+
});
|
|
18645
|
+
return;
|
|
18646
|
+
}
|
|
18545
18647
|
const message = typeof body === "string" ? body : exception.message;
|
|
18546
18648
|
res.status(exception.getStatus()).json({
|
|
18547
18649
|
error: {
|
|
@@ -18552,6 +18654,17 @@ exports.AuthExceptionFilter = class _AuthExceptionFilter {
|
|
|
18552
18654
|
});
|
|
18553
18655
|
return;
|
|
18554
18656
|
}
|
|
18657
|
+
const refusedStatus = bodyParserStatus(exception);
|
|
18658
|
+
if (refusedStatus !== void 0) {
|
|
18659
|
+
res.status(refusedStatus).json({
|
|
18660
|
+
error: {
|
|
18661
|
+
code: AUTH_ERROR_CODES.VALIDATION,
|
|
18662
|
+
message: bodyParserMessage(refusedStatus),
|
|
18663
|
+
details: null
|
|
18664
|
+
}
|
|
18665
|
+
});
|
|
18666
|
+
return;
|
|
18667
|
+
}
|
|
18555
18668
|
this.logger.error(`unhandled exception: ${describeChannelStatus(exception)}`);
|
|
18556
18669
|
res.status(common.HttpStatus.INTERNAL_SERVER_ERROR).json({
|
|
18557
18670
|
error: {
|
package/dist/server/index.d.cts
CHANGED
|
@@ -772,6 +772,10 @@ interface BymaxAuthModuleOptions {
|
|
|
772
772
|
* @remarks
|
|
773
773
|
* Set this explicitly to `true` in a non-production environment that is nonetheless served
|
|
774
774
|
* over HTTPS, so the cookies are marked `Secure` there too.
|
|
775
|
+
*
|
|
776
|
+
* `false` is refused at startup unless {@link BymaxAuthModuleOptions.environment} is
|
|
777
|
+
* `'development'` or `'test'`: a session cookie without `Secure` travels over plain HTTP, and a
|
|
778
|
+
* TLS-terminating proxy does not change that for the browser's side of the connection.
|
|
775
779
|
*/
|
|
776
780
|
secureCookies?: boolean;
|
|
777
781
|
/**
|
|
@@ -6069,6 +6073,11 @@ declare class WsJwtGuard implements CanActivate, OnModuleInit {
|
|
|
6069
6073
|
* stack detail or a connection string reaches a response body, so the answer carries the
|
|
6070
6074
|
* generic code and nothing else.
|
|
6071
6075
|
*
|
|
6076
|
+
* Requests the HTTP layer refused before any route ran — a malformed body, an oversized one, an
|
|
6077
|
+
* unsupported charset or content-encoding — answer `auth.validation` with a fixed message and the
|
|
6078
|
+
* status the transport reported, never the parser's text. Express only: the filter writes through
|
|
6079
|
+
* Express's `Response` and reads `req.route`, so its behaviour on another adapter is not defined.
|
|
6080
|
+
*
|
|
6072
6081
|
* **Do not register this alongside `@bymax-one/nest-core`'s envelope filter.** They are mutually
|
|
6073
6082
|
* exclusive in practice and this one wins: `useGlobalFilters` binds ahead of an `APP_FILTER`
|
|
6074
6083
|
* provider, and `@Catch()` with no argument catches everything, so nest-core's filter never runs.
|
|
@@ -7494,13 +7503,30 @@ declare class SessionService {
|
|
|
7494
7503
|
* Refuses a session hash that names no live session of this user.
|
|
7495
7504
|
*
|
|
7496
7505
|
* For an operation that keeps one session and ends the rest and so has to be told which one,
|
|
7497
|
-
* checked before it changes anything. The membership test is the
|
|
7498
|
-
*
|
|
7506
|
+
* checked before it changes anything. The membership test is the one {@link resolveLiveSession}
|
|
7507
|
+
* applies, so a token that has just rotated is accepted here exactly as it is there.
|
|
7499
7508
|
*
|
|
7500
7509
|
* @param params - See {@link LiveSessionParams}.
|
|
7501
7510
|
* @throws {@link AuthException} `SESSION_NOT_FOUND` when the hash is not a live session.
|
|
7502
7511
|
*/
|
|
7503
|
-
assertLiveSession(
|
|
7512
|
+
assertLiveSession(params: LiveSessionParams): Promise<void>;
|
|
7513
|
+
/**
|
|
7514
|
+
* Names the live session a presented refresh-token hash stands for.
|
|
7515
|
+
*
|
|
7516
|
+
* The hash itself when it is a live session. When it is a token that rotated away moments ago,
|
|
7517
|
+
* the session the rotation produced: the rotation grace pointer `rp:{hash}` names that successor,
|
|
7518
|
+
* and the presented token still identifies the same device. A request that carries a refresh
|
|
7519
|
+
* token can lose a race to a refresh of the same session, and an operation that must keep "the
|
|
7520
|
+
* caller's session" would otherwise refuse the caller for having been refreshed. The pointer is
|
|
7521
|
+
* read, never consumed, and the successor has to be live in the index too, so a pointer left
|
|
7522
|
+
* behind by a session that was since revoked names nothing.
|
|
7523
|
+
*
|
|
7524
|
+
* @param params - See {@link LiveSessionParams}.
|
|
7525
|
+
* @returns The hash of the live session to keep: `sessionHash`, or its live successor.
|
|
7526
|
+
* @throws {@link AuthException} `SESSION_NOT_FOUND` when the hash is neither a live session nor
|
|
7527
|
+
* the predecessor of one.
|
|
7528
|
+
*/
|
|
7529
|
+
resolveLiveSession({ userId, tenantId, sessionHash }: LiveSessionParams): Promise<string>;
|
|
7504
7530
|
/**
|
|
7505
7531
|
* Revokes all sessions for a user except the caller's current session.
|
|
7506
7532
|
*
|
|
@@ -7585,11 +7611,20 @@ declare class SessionService {
|
|
|
7585
7611
|
*/
|
|
7586
7612
|
private assertValidSessionHash;
|
|
7587
7613
|
/**
|
|
7588
|
-
*
|
|
7614
|
+
* The hash of the live refresh session `sessionHash` stands for within `members`.
|
|
7589
7615
|
*
|
|
7590
7616
|
* @throws {@link AuthException} `SESSION_NOT_FOUND`.
|
|
7591
7617
|
*/
|
|
7592
|
-
private
|
|
7618
|
+
private resolveLiveMember;
|
|
7619
|
+
/** Whether `members` holds a live refresh session with this hash. */
|
|
7620
|
+
private isLiveMember;
|
|
7621
|
+
/**
|
|
7622
|
+
* The successor hash a rotation grace pointer names, or `undefined` when there is none.
|
|
7623
|
+
*
|
|
7624
|
+
* The pointer's value is `{successorHash}:{record}`, split on the first colon exactly as the
|
|
7625
|
+
* rotation script writes it.
|
|
7626
|
+
*/
|
|
7627
|
+
private graceSuccessor;
|
|
7593
7628
|
/**
|
|
7594
7629
|
* The Redis key of this user's session index.
|
|
7595
7630
|
*
|
|
@@ -7626,6 +7661,15 @@ declare class SessionService {
|
|
|
7626
7661
|
* @param userAgent - User-Agent string (forwarded to the `onSessionEvicted` hook context).
|
|
7627
7662
|
*/
|
|
7628
7663
|
private enforceSessionLimit;
|
|
7664
|
+
/**
|
|
7665
|
+
* The creation time of a session, for ranking sessions by age.
|
|
7666
|
+
*
|
|
7667
|
+
* An absent record and one that is not a detail record both rank as `0`, the oldest: a state the
|
|
7668
|
+
* store reported, not a fault. A read the store fails propagates, because no age can be named.
|
|
7669
|
+
*
|
|
7670
|
+
* @param memberHash - SHA-256 hash of the session's refresh token.
|
|
7671
|
+
*/
|
|
7672
|
+
private readCreatedAt;
|
|
7629
7673
|
/**
|
|
7630
7674
|
* Resolves the maximum number of concurrent sessions allowed for a user.
|
|
7631
7675
|
*
|
|
@@ -9779,16 +9823,20 @@ declare class PasswordResetService {
|
|
|
9779
9823
|
* the configured breach checker.
|
|
9780
9824
|
*/
|
|
9781
9825
|
changePassword(userId: string, tenantId: string, dto: ChangePasswordDto, currentRefreshToken?: string): Promise<void>;
|
|
9782
|
-
/** Refuses a presented refresh token that names no live session of the account. */
|
|
9783
|
-
private requireLiveCurrentSession;
|
|
9784
9826
|
/**
|
|
9785
|
-
*
|
|
9827
|
+
* The hash of the live session a presented refresh token stands for, or `undefined` when the
|
|
9828
|
+
* request carried none. Refuses a token that names no live session of the account; a token that
|
|
9829
|
+
* rotated away while the password was being verified stands for the session that replaced it.
|
|
9830
|
+
*/
|
|
9831
|
+
private resolveCurrentSession;
|
|
9832
|
+
/**
|
|
9833
|
+
* Ends every session but the one to keep, once the new password is already written.
|
|
9786
9834
|
*
|
|
9787
|
-
* With no
|
|
9788
|
-
*
|
|
9789
|
-
* no current session left to
|
|
9790
|
-
* change safe is never aborted by the session it was told to spare. Any other failure of
|
|
9791
|
-
* sweep propagates.
|
|
9835
|
+
* With no session to keep every session ends. A kept session can rotate away while the new
|
|
9836
|
+
* password is hashed; the sweep follows it to its successor, and when it cannot be followed
|
|
9837
|
+
* there is no current session left to spare, so every session ends and the cleanup that makes
|
|
9838
|
+
* the change safe is never aborted by the session it was told to spare. Any other failure of
|
|
9839
|
+
* the sweep propagates.
|
|
9792
9840
|
*/
|
|
9793
9841
|
private endOtherSessions;
|
|
9794
9842
|
/** Ends every session the account has and advances its token epoch. */
|
package/dist/server/index.d.ts
CHANGED
|
@@ -772,6 +772,10 @@ interface BymaxAuthModuleOptions {
|
|
|
772
772
|
* @remarks
|
|
773
773
|
* Set this explicitly to `true` in a non-production environment that is nonetheless served
|
|
774
774
|
* over HTTPS, so the cookies are marked `Secure` there too.
|
|
775
|
+
*
|
|
776
|
+
* `false` is refused at startup unless {@link BymaxAuthModuleOptions.environment} is
|
|
777
|
+
* `'development'` or `'test'`: a session cookie without `Secure` travels over plain HTTP, and a
|
|
778
|
+
* TLS-terminating proxy does not change that for the browser's side of the connection.
|
|
775
779
|
*/
|
|
776
780
|
secureCookies?: boolean;
|
|
777
781
|
/**
|
|
@@ -6069,6 +6073,11 @@ declare class WsJwtGuard implements CanActivate, OnModuleInit {
|
|
|
6069
6073
|
* stack detail or a connection string reaches a response body, so the answer carries the
|
|
6070
6074
|
* generic code and nothing else.
|
|
6071
6075
|
*
|
|
6076
|
+
* Requests the HTTP layer refused before any route ran — a malformed body, an oversized one, an
|
|
6077
|
+
* unsupported charset or content-encoding — answer `auth.validation` with a fixed message and the
|
|
6078
|
+
* status the transport reported, never the parser's text. Express only: the filter writes through
|
|
6079
|
+
* Express's `Response` and reads `req.route`, so its behaviour on another adapter is not defined.
|
|
6080
|
+
*
|
|
6072
6081
|
* **Do not register this alongside `@bymax-one/nest-core`'s envelope filter.** They are mutually
|
|
6073
6082
|
* exclusive in practice and this one wins: `useGlobalFilters` binds ahead of an `APP_FILTER`
|
|
6074
6083
|
* provider, and `@Catch()` with no argument catches everything, so nest-core's filter never runs.
|
|
@@ -7494,13 +7503,30 @@ declare class SessionService {
|
|
|
7494
7503
|
* Refuses a session hash that names no live session of this user.
|
|
7495
7504
|
*
|
|
7496
7505
|
* For an operation that keeps one session and ends the rest and so has to be told which one,
|
|
7497
|
-
* checked before it changes anything. The membership test is the
|
|
7498
|
-
*
|
|
7506
|
+
* checked before it changes anything. The membership test is the one {@link resolveLiveSession}
|
|
7507
|
+
* applies, so a token that has just rotated is accepted here exactly as it is there.
|
|
7499
7508
|
*
|
|
7500
7509
|
* @param params - See {@link LiveSessionParams}.
|
|
7501
7510
|
* @throws {@link AuthException} `SESSION_NOT_FOUND` when the hash is not a live session.
|
|
7502
7511
|
*/
|
|
7503
|
-
assertLiveSession(
|
|
7512
|
+
assertLiveSession(params: LiveSessionParams): Promise<void>;
|
|
7513
|
+
/**
|
|
7514
|
+
* Names the live session a presented refresh-token hash stands for.
|
|
7515
|
+
*
|
|
7516
|
+
* The hash itself when it is a live session. When it is a token that rotated away moments ago,
|
|
7517
|
+
* the session the rotation produced: the rotation grace pointer `rp:{hash}` names that successor,
|
|
7518
|
+
* and the presented token still identifies the same device. A request that carries a refresh
|
|
7519
|
+
* token can lose a race to a refresh of the same session, and an operation that must keep "the
|
|
7520
|
+
* caller's session" would otherwise refuse the caller for having been refreshed. The pointer is
|
|
7521
|
+
* read, never consumed, and the successor has to be live in the index too, so a pointer left
|
|
7522
|
+
* behind by a session that was since revoked names nothing.
|
|
7523
|
+
*
|
|
7524
|
+
* @param params - See {@link LiveSessionParams}.
|
|
7525
|
+
* @returns The hash of the live session to keep: `sessionHash`, or its live successor.
|
|
7526
|
+
* @throws {@link AuthException} `SESSION_NOT_FOUND` when the hash is neither a live session nor
|
|
7527
|
+
* the predecessor of one.
|
|
7528
|
+
*/
|
|
7529
|
+
resolveLiveSession({ userId, tenantId, sessionHash }: LiveSessionParams): Promise<string>;
|
|
7504
7530
|
/**
|
|
7505
7531
|
* Revokes all sessions for a user except the caller's current session.
|
|
7506
7532
|
*
|
|
@@ -7585,11 +7611,20 @@ declare class SessionService {
|
|
|
7585
7611
|
*/
|
|
7586
7612
|
private assertValidSessionHash;
|
|
7587
7613
|
/**
|
|
7588
|
-
*
|
|
7614
|
+
* The hash of the live refresh session `sessionHash` stands for within `members`.
|
|
7589
7615
|
*
|
|
7590
7616
|
* @throws {@link AuthException} `SESSION_NOT_FOUND`.
|
|
7591
7617
|
*/
|
|
7592
|
-
private
|
|
7618
|
+
private resolveLiveMember;
|
|
7619
|
+
/** Whether `members` holds a live refresh session with this hash. */
|
|
7620
|
+
private isLiveMember;
|
|
7621
|
+
/**
|
|
7622
|
+
* The successor hash a rotation grace pointer names, or `undefined` when there is none.
|
|
7623
|
+
*
|
|
7624
|
+
* The pointer's value is `{successorHash}:{record}`, split on the first colon exactly as the
|
|
7625
|
+
* rotation script writes it.
|
|
7626
|
+
*/
|
|
7627
|
+
private graceSuccessor;
|
|
7593
7628
|
/**
|
|
7594
7629
|
* The Redis key of this user's session index.
|
|
7595
7630
|
*
|
|
@@ -7626,6 +7661,15 @@ declare class SessionService {
|
|
|
7626
7661
|
* @param userAgent - User-Agent string (forwarded to the `onSessionEvicted` hook context).
|
|
7627
7662
|
*/
|
|
7628
7663
|
private enforceSessionLimit;
|
|
7664
|
+
/**
|
|
7665
|
+
* The creation time of a session, for ranking sessions by age.
|
|
7666
|
+
*
|
|
7667
|
+
* An absent record and one that is not a detail record both rank as `0`, the oldest: a state the
|
|
7668
|
+
* store reported, not a fault. A read the store fails propagates, because no age can be named.
|
|
7669
|
+
*
|
|
7670
|
+
* @param memberHash - SHA-256 hash of the session's refresh token.
|
|
7671
|
+
*/
|
|
7672
|
+
private readCreatedAt;
|
|
7629
7673
|
/**
|
|
7630
7674
|
* Resolves the maximum number of concurrent sessions allowed for a user.
|
|
7631
7675
|
*
|
|
@@ -9779,16 +9823,20 @@ declare class PasswordResetService {
|
|
|
9779
9823
|
* the configured breach checker.
|
|
9780
9824
|
*/
|
|
9781
9825
|
changePassword(userId: string, tenantId: string, dto: ChangePasswordDto, currentRefreshToken?: string): Promise<void>;
|
|
9782
|
-
/** Refuses a presented refresh token that names no live session of the account. */
|
|
9783
|
-
private requireLiveCurrentSession;
|
|
9784
9826
|
/**
|
|
9785
|
-
*
|
|
9827
|
+
* The hash of the live session a presented refresh token stands for, or `undefined` when the
|
|
9828
|
+
* request carried none. Refuses a token that names no live session of the account; a token that
|
|
9829
|
+
* rotated away while the password was being verified stands for the session that replaced it.
|
|
9830
|
+
*/
|
|
9831
|
+
private resolveCurrentSession;
|
|
9832
|
+
/**
|
|
9833
|
+
* Ends every session but the one to keep, once the new password is already written.
|
|
9786
9834
|
*
|
|
9787
|
-
* With no
|
|
9788
|
-
*
|
|
9789
|
-
* no current session left to
|
|
9790
|
-
* change safe is never aborted by the session it was told to spare. Any other failure of
|
|
9791
|
-
* sweep propagates.
|
|
9835
|
+
* With no session to keep every session ends. A kept session can rotate away while the new
|
|
9836
|
+
* password is hashed; the sweep follows it to its successor, and when it cannot be followed
|
|
9837
|
+
* there is no current session left to spare, so every session ends and the cleanup that makes
|
|
9838
|
+
* the change safe is never aborted by the session it was told to spare. Any other failure of
|
|
9839
|
+
* the sweep propagates.
|
|
9792
9840
|
*/
|
|
9793
9841
|
private endOtherSessions;
|
|
9794
9842
|
/** Ends every session the account has and advances its token epoch. */
|
package/dist/server/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createParamDecorator, HttpException, HttpStatus, Injectable, Inject, Logger, Optional, ValidationPipe, Post, Body, Req, Res, HttpCode, UseGuards, Get, UseInterceptors, Controller, UsePipes, Delete, Param, Query, Module, SetMetadata, Catch, applyDecorators } from '@nestjs/common';
|
|
1
|
+
import { createParamDecorator, HttpException, HttpStatus, Injectable, Inject, Logger, Optional, ValidationPipe, Post, Body, Req, Res, HttpCode, UseGuards, Get, UseInterceptors, Controller, UsePipes, Delete, Param, Query, Module, SetMetadata, Catch, BadRequestException, applyDecorators } from '@nestjs/common';
|
|
2
2
|
import { Reflector, DiscoveryService, MetadataScanner, DiscoveryModule } from '@nestjs/core';
|
|
3
3
|
import { JwtService, JwtModule } from '@nestjs/jwt';
|
|
4
4
|
import { randomInt, scrypt as scrypt$1, randomBytes, timingSafeEqual, randomUUID, createHash, createHmac, createCipheriv, createDecipheriv } from 'crypto';
|
|
@@ -351,6 +351,7 @@ function resolveOptions(userOptions) {
|
|
|
351
351
|
validateOAuthErrorRedirectUrl(userOptions);
|
|
352
352
|
validateRefreshCookiePath(userOptions.routePrefix, userOptions.cookies);
|
|
353
353
|
validateSameSiteNoneRequiresSecure(userOptions);
|
|
354
|
+
validateProductionCookiesAreSecure(userOptions);
|
|
354
355
|
validateCookiePrefixes(userOptions);
|
|
355
356
|
validateTrustedOrigins(userOptions);
|
|
356
357
|
validateRefreshGraceWindow(userOptions.jwt);
|
|
@@ -911,6 +912,11 @@ function validateSameSiteNoneRequiresSecure(userOptions) {
|
|
|
911
912
|
}
|
|
912
913
|
}
|
|
913
914
|
__name(validateSameSiteNoneRequiresSecure, "validateSameSiteNoneRequiresSecure");
|
|
915
|
+
function validateProductionCookiesAreSecure(userOptions) {
|
|
916
|
+
if (userOptions.secureCookies !== false || !isProductionDeployment(userOptions)) return;
|
|
917
|
+
throw new Error(`[BymaxAuthModule] secureCookies is false but environment is 'production' (the default when unset). A session cookie without the Secure attribute is sent over plain HTTP. Set secureCookies: true (a TLS-terminating proxy still serves HTTPS to the browser), or declare environment: 'development' or 'test' for local HTTP.`);
|
|
918
|
+
}
|
|
919
|
+
__name(validateProductionCookiesAreSecure, "validateProductionCookiesAreSecure");
|
|
914
920
|
function validateTrustedOrigins(userOptions) {
|
|
915
921
|
const sameSite = userOptions.cookies?.sameSite ?? DEFAULT_OPTIONS.cookies.sameSite;
|
|
916
922
|
const trustedOrigins = userOptions.cookies?.trustedOrigins ?? [];
|
|
@@ -5238,16 +5244,35 @@ var SessionService = class _SessionService {
|
|
|
5238
5244
|
* Refuses a session hash that names no live session of this user.
|
|
5239
5245
|
*
|
|
5240
5246
|
* For an operation that keeps one session and ends the rest and so has to be told which one,
|
|
5241
|
-
* checked before it changes anything. The membership test is the
|
|
5242
|
-
*
|
|
5247
|
+
* checked before it changes anything. The membership test is the one {@link resolveLiveSession}
|
|
5248
|
+
* applies, so a token that has just rotated is accepted here exactly as it is there.
|
|
5243
5249
|
*
|
|
5244
5250
|
* @param params - See {@link LiveSessionParams}.
|
|
5245
5251
|
* @throws {@link AuthException} `SESSION_NOT_FOUND` when the hash is not a live session.
|
|
5246
5252
|
*/
|
|
5247
|
-
async assertLiveSession(
|
|
5253
|
+
async assertLiveSession(params) {
|
|
5254
|
+
await this.resolveLiveSession(params);
|
|
5255
|
+
}
|
|
5256
|
+
/**
|
|
5257
|
+
* Names the live session a presented refresh-token hash stands for.
|
|
5258
|
+
*
|
|
5259
|
+
* The hash itself when it is a live session. When it is a token that rotated away moments ago,
|
|
5260
|
+
* the session the rotation produced: the rotation grace pointer `rp:{hash}` names that successor,
|
|
5261
|
+
* and the presented token still identifies the same device. A request that carries a refresh
|
|
5262
|
+
* token can lose a race to a refresh of the same session, and an operation that must keep "the
|
|
5263
|
+
* caller's session" would otherwise refuse the caller for having been refreshed. The pointer is
|
|
5264
|
+
* read, never consumed, and the successor has to be live in the index too, so a pointer left
|
|
5265
|
+
* behind by a session that was since revoked names nothing.
|
|
5266
|
+
*
|
|
5267
|
+
* @param params - See {@link LiveSessionParams}.
|
|
5268
|
+
* @returns The hash of the live session to keep: `sessionHash`, or its live successor.
|
|
5269
|
+
* @throws {@link AuthException} `SESSION_NOT_FOUND` when the hash is neither a live session nor
|
|
5270
|
+
* the predecessor of one.
|
|
5271
|
+
*/
|
|
5272
|
+
async resolveLiveSession({ userId, tenantId, sessionHash }) {
|
|
5248
5273
|
this.assertTenant(tenantId);
|
|
5249
5274
|
this.assertValidSessionHash(sessionHash, "sessionHash");
|
|
5250
|
-
this.
|
|
5275
|
+
return this.resolveLiveMember(await this.redis.smembers(this.indexKey(userId, tenantId)), sessionHash);
|
|
5251
5276
|
}
|
|
5252
5277
|
/**
|
|
5253
5278
|
* Revokes all sessions for a user except the caller's current session.
|
|
@@ -5284,11 +5309,11 @@ var SessionService = class _SessionService {
|
|
|
5284
5309
|
this.assertTenant(tenantId);
|
|
5285
5310
|
this.assertValidSessionHash(currentSessionHash, "currentSessionHash");
|
|
5286
5311
|
const members = await this.redis.smembers(this.indexKey(userId, tenantId));
|
|
5287
|
-
this.
|
|
5312
|
+
const keptHash = await this.resolveLiveMember(members, currentSessionHash);
|
|
5288
5313
|
const rtMembers = members.filter((m) => m.startsWith("rt:"));
|
|
5289
5314
|
for (const member of rtMembers) {
|
|
5290
5315
|
const hash = member.slice(3);
|
|
5291
|
-
if (timingSafeCompare(hash,
|
|
5316
|
+
if (timingSafeCompare(hash, keptHash)) continue;
|
|
5292
5317
|
try {
|
|
5293
5318
|
await this.revokeSession({
|
|
5294
5319
|
userId,
|
|
@@ -5409,13 +5434,33 @@ var SessionService = class _SessionService {
|
|
|
5409
5434
|
}
|
|
5410
5435
|
}
|
|
5411
5436
|
/**
|
|
5412
|
-
*
|
|
5437
|
+
* The hash of the live refresh session `sessionHash` stands for within `members`.
|
|
5413
5438
|
*
|
|
5414
5439
|
* @throws {@link AuthException} `SESSION_NOT_FOUND`.
|
|
5415
5440
|
*/
|
|
5416
|
-
|
|
5417
|
-
|
|
5418
|
-
|
|
5441
|
+
async resolveLiveMember(members, sessionHash) {
|
|
5442
|
+
if (this.isLiveMember(members, sessionHash)) return sessionHash;
|
|
5443
|
+
const successor = await this.graceSuccessor(sessionHash);
|
|
5444
|
+
if (successor !== void 0 && this.isLiveMember(members, successor)) return successor;
|
|
5445
|
+
throw new AuthException(AUTH_ERROR_CODES.SESSION_NOT_FOUND);
|
|
5446
|
+
}
|
|
5447
|
+
/** Whether `members` holds a live refresh session with this hash. */
|
|
5448
|
+
isLiveMember(members, sessionHash) {
|
|
5449
|
+
return members.some((member) => member.startsWith("rt:") && timingSafeCompare(member.slice(3), sessionHash));
|
|
5450
|
+
}
|
|
5451
|
+
/**
|
|
5452
|
+
* The successor hash a rotation grace pointer names, or `undefined` when there is none.
|
|
5453
|
+
*
|
|
5454
|
+
* The pointer's value is `{successorHash}:{record}`, split on the first colon exactly as the
|
|
5455
|
+
* rotation script writes it.
|
|
5456
|
+
*/
|
|
5457
|
+
async graceSuccessor(sessionHash) {
|
|
5458
|
+
const pointer = await this.redis.get(`rp:${sessionHash}`);
|
|
5459
|
+
if (pointer === null) return void 0;
|
|
5460
|
+
const separator = pointer.indexOf(":");
|
|
5461
|
+
if (separator < 0) return void 0;
|
|
5462
|
+
const successor = pointer.slice(0, separator);
|
|
5463
|
+
return SESSION_HASH_RE.test(successor) ? successor : void 0;
|
|
5419
5464
|
}
|
|
5420
5465
|
/**
|
|
5421
5466
|
* The Redis key of this user's session index.
|
|
@@ -5460,28 +5505,18 @@ var SessionService = class _SessionService {
|
|
|
5460
5505
|
const rtMembers = members.filter((m) => m.startsWith("rt:"));
|
|
5461
5506
|
const limit = await this.resolveSessionLimit(userId, tenantId);
|
|
5462
5507
|
if (rtMembers.length <= limit) return;
|
|
5463
|
-
|
|
5464
|
-
|
|
5465
|
-
|
|
5466
|
-
try {
|
|
5467
|
-
const raw = await this.redis.get(`sd:${memberHash}`);
|
|
5468
|
-
if (raw !== null) {
|
|
5469
|
-
const parsed = JSON.parse(raw);
|
|
5470
|
-
if (
|
|
5471
|
-
// Stryker disable next-line ConditionalExpression: defensive `parsed !== null` guard masked by the surrounding try/catch fallback, yielding the same result
|
|
5472
|
-
parsed !== null && typeof parsed === "object" && "createdAt" in parsed && typeof parsed["createdAt"] === "number"
|
|
5473
|
-
) {
|
|
5474
|
-
createdAt = parsed.createdAt;
|
|
5475
|
-
}
|
|
5476
|
-
}
|
|
5477
|
-
} catch {
|
|
5478
|
-
}
|
|
5479
|
-
return {
|
|
5508
|
+
let withTimestamps;
|
|
5509
|
+
try {
|
|
5510
|
+
withTimestamps = await Promise.all(rtMembers.map(async (member) => ({
|
|
5480
5511
|
member,
|
|
5481
|
-
|
|
5482
|
-
|
|
5483
|
-
|
|
5484
|
-
|
|
5512
|
+
// member is "rt:{hash}" — extract just the hash portion.
|
|
5513
|
+
memberHash: member.slice(3),
|
|
5514
|
+
createdAt: await this.readCreatedAt(member.slice(3))
|
|
5515
|
+
})));
|
|
5516
|
+
} catch (err) {
|
|
5517
|
+
this.logger.error(`enforceSessionLimit: eviction skipped for user ${logSafe(userId)}, a session record could not be read: ${describeChannelStatus(err)}`);
|
|
5518
|
+
return;
|
|
5519
|
+
}
|
|
5485
5520
|
withTimestamps.sort((a, b) => a.createdAt - b.createdAt);
|
|
5486
5521
|
const evictCount = rtMembers.length - limit;
|
|
5487
5522
|
const toEvict = withTimestamps.filter((entry) => entry.memberHash !== newHash).slice(0, evictCount);
|
|
@@ -5510,6 +5545,29 @@ var SessionService = class _SessionService {
|
|
|
5510
5545
|
}
|
|
5511
5546
|
}
|
|
5512
5547
|
/**
|
|
5548
|
+
* The creation time of a session, for ranking sessions by age.
|
|
5549
|
+
*
|
|
5550
|
+
* An absent record and one that is not a detail record both rank as `0`, the oldest: a state the
|
|
5551
|
+
* store reported, not a fault. A read the store fails propagates, because no age can be named.
|
|
5552
|
+
*
|
|
5553
|
+
* @param memberHash - SHA-256 hash of the session's refresh token.
|
|
5554
|
+
*/
|
|
5555
|
+
async readCreatedAt(memberHash) {
|
|
5556
|
+
const raw = await this.redis.get(`sd:${memberHash}`);
|
|
5557
|
+
if (raw === null) return 0;
|
|
5558
|
+
try {
|
|
5559
|
+
const parsed = JSON.parse(raw);
|
|
5560
|
+
if (
|
|
5561
|
+
// Stryker disable next-line ConditionalExpression: defensive `parsed !== null` guard masked by the surrounding try/catch fallback, yielding the same result
|
|
5562
|
+
parsed !== null && typeof parsed === "object" && "createdAt" in parsed && typeof parsed["createdAt"] === "number"
|
|
5563
|
+
) {
|
|
5564
|
+
return parsed.createdAt;
|
|
5565
|
+
}
|
|
5566
|
+
} catch {
|
|
5567
|
+
}
|
|
5568
|
+
return 0;
|
|
5569
|
+
}
|
|
5570
|
+
/**
|
|
5513
5571
|
* Resolves the maximum number of concurrent sessions allowed for a user.
|
|
5514
5572
|
*
|
|
5515
5573
|
* When `options.sessions.maxSessionsResolver` is configured, it is called with
|
|
@@ -12133,7 +12191,7 @@ var PasswordResetService = class _PasswordResetService {
|
|
|
12133
12191
|
throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
|
|
12134
12192
|
}
|
|
12135
12193
|
await this.bruteForce.resetFailures(bfIdentifier);
|
|
12136
|
-
await this.
|
|
12194
|
+
const keptHash = await this.resolveCurrentSession(userId, user.tenantId, currentRefreshToken);
|
|
12137
12195
|
await this.passwordService.assertAcceptable(dto.newPassword, "newPassword");
|
|
12138
12196
|
const passwordHash = await this.passwordService.hash(dto.newPassword);
|
|
12139
12197
|
await this.userRepo.updatePassword({
|
|
@@ -12141,36 +12199,40 @@ var PasswordResetService = class _PasswordResetService {
|
|
|
12141
12199
|
tenantId,
|
|
12142
12200
|
passwordHash
|
|
12143
12201
|
});
|
|
12144
|
-
await this.endOtherSessions(userId, user.tenantId,
|
|
12202
|
+
await this.endOtherSessions(userId, user.tenantId, keptHash);
|
|
12145
12203
|
await this.notifyPasswordChanged(user);
|
|
12146
12204
|
}
|
|
12147
|
-
/**
|
|
12148
|
-
|
|
12149
|
-
|
|
12150
|
-
|
|
12205
|
+
/**
|
|
12206
|
+
* The hash of the live session a presented refresh token stands for, or `undefined` when the
|
|
12207
|
+
* request carried none. Refuses a token that names no live session of the account; a token that
|
|
12208
|
+
* rotated away while the password was being verified stands for the session that replaced it.
|
|
12209
|
+
*/
|
|
12210
|
+
async resolveCurrentSession(userId, tenantId, currentRefreshToken) {
|
|
12211
|
+
if (currentRefreshToken === void 0 || currentRefreshToken.length === 0) return void 0;
|
|
12212
|
+
return this.sessionService.resolveLiveSession({
|
|
12151
12213
|
userId,
|
|
12152
12214
|
tenantId,
|
|
12153
12215
|
sessionHash: sha256(currentRefreshToken)
|
|
12154
12216
|
});
|
|
12155
12217
|
}
|
|
12156
12218
|
/**
|
|
12157
|
-
* Ends every session but the
|
|
12219
|
+
* Ends every session but the one to keep, once the new password is already written.
|
|
12158
12220
|
*
|
|
12159
|
-
* With no
|
|
12160
|
-
*
|
|
12161
|
-
* no current session left to
|
|
12162
|
-
* change safe is never aborted by the session it was told to spare. Any other failure of
|
|
12163
|
-
* sweep propagates.
|
|
12221
|
+
* With no session to keep every session ends. A kept session can rotate away while the new
|
|
12222
|
+
* password is hashed; the sweep follows it to its successor, and when it cannot be followed
|
|
12223
|
+
* there is no current session left to spare, so every session ends and the cleanup that makes
|
|
12224
|
+
* the change safe is never aborted by the session it was told to spare. Any other failure of
|
|
12225
|
+
* the sweep propagates.
|
|
12164
12226
|
*/
|
|
12165
|
-
async endOtherSessions(userId, tenantId,
|
|
12166
|
-
if (
|
|
12227
|
+
async endOtherSessions(userId, tenantId, keptHash) {
|
|
12228
|
+
if (keptHash === void 0) {
|
|
12167
12229
|
return this.endAllSessions(userId, tenantId);
|
|
12168
12230
|
}
|
|
12169
12231
|
try {
|
|
12170
12232
|
await this.sessionService.revokeAllExceptCurrent({
|
|
12171
12233
|
userId,
|
|
12172
12234
|
tenantId,
|
|
12173
|
-
currentSessionHash:
|
|
12235
|
+
currentSessionHash: keptHash
|
|
12174
12236
|
});
|
|
12175
12237
|
} catch (err) {
|
|
12176
12238
|
const body = err instanceof AuthException ? err.getResponse() : void 0;
|
|
@@ -18517,6 +18579,35 @@ function isAuthEnvelope(body) {
|
|
|
18517
18579
|
return typeof error === "object" && error !== null && "code" in error;
|
|
18518
18580
|
}
|
|
18519
18581
|
__name(isAuthEnvelope, "isAuthEnvelope");
|
|
18582
|
+
var BODY_PARSER_ERROR_TYPES = /* @__PURE__ */ new Set([
|
|
18583
|
+
"entity.parse.failed",
|
|
18584
|
+
"entity.too.large",
|
|
18585
|
+
"entity.verify.failed",
|
|
18586
|
+
"charset.unsupported",
|
|
18587
|
+
"encoding.unsupported",
|
|
18588
|
+
"request.aborted",
|
|
18589
|
+
"request.size.invalid",
|
|
18590
|
+
"querystring.parse.rangeError",
|
|
18591
|
+
"parameters.too.many"
|
|
18592
|
+
]);
|
|
18593
|
+
var MALFORMED_REQUEST_MESSAGE = "Malformed request";
|
|
18594
|
+
function bodyParserStatus(exception) {
|
|
18595
|
+
if (typeof exception !== "object" || exception === null) return void 0;
|
|
18596
|
+
const { type, status } = exception;
|
|
18597
|
+
if (typeof type !== "string" || !BODY_PARSER_ERROR_TYPES.has(type)) return void 0;
|
|
18598
|
+
return typeof status === "number" && status >= 400 && status < 500 ? status : void 0;
|
|
18599
|
+
}
|
|
18600
|
+
__name(bodyParserStatus, "bodyParserStatus");
|
|
18601
|
+
function bodyParserMessage(status) {
|
|
18602
|
+
if (status === HttpStatus.PAYLOAD_TOO_LARGE) return "Request entity too large";
|
|
18603
|
+
if (status === HttpStatus.UNSUPPORTED_MEDIA_TYPE) return "Unsupported media type";
|
|
18604
|
+
return MALFORMED_REQUEST_MESSAGE;
|
|
18605
|
+
}
|
|
18606
|
+
__name(bodyParserMessage, "bodyParserMessage");
|
|
18607
|
+
function isPreRoutingBadRequest(exception, req) {
|
|
18608
|
+
return exception instanceof BadRequestException && req.route === void 0;
|
|
18609
|
+
}
|
|
18610
|
+
__name(isPreRoutingBadRequest, "isPreRoutingBadRequest");
|
|
18520
18611
|
var AuthExceptionFilter = class _AuthExceptionFilter {
|
|
18521
18612
|
static {
|
|
18522
18613
|
__name(this, "AuthExceptionFilter");
|
|
@@ -18529,7 +18620,8 @@ var AuthExceptionFilter = class _AuthExceptionFilter {
|
|
|
18529
18620
|
* @param host - The arguments host, used to reach the HTTP response.
|
|
18530
18621
|
*/
|
|
18531
18622
|
catch(exception, host) {
|
|
18532
|
-
const
|
|
18623
|
+
const http = host.switchToHttp();
|
|
18624
|
+
const res = http.getResponse();
|
|
18533
18625
|
if (exception instanceof AuthException) {
|
|
18534
18626
|
res.status(exception.getStatus()).json(exception.getResponse());
|
|
18535
18627
|
return;
|
|
@@ -18540,6 +18632,16 @@ var AuthExceptionFilter = class _AuthExceptionFilter {
|
|
|
18540
18632
|
res.status(exception.getStatus()).json(body);
|
|
18541
18633
|
return;
|
|
18542
18634
|
}
|
|
18635
|
+
if (isPreRoutingBadRequest(exception, http.getRequest())) {
|
|
18636
|
+
res.status(HttpStatus.BAD_REQUEST).json({
|
|
18637
|
+
error: {
|
|
18638
|
+
code: AUTH_ERROR_CODES.VALIDATION,
|
|
18639
|
+
message: MALFORMED_REQUEST_MESSAGE,
|
|
18640
|
+
details: null
|
|
18641
|
+
}
|
|
18642
|
+
});
|
|
18643
|
+
return;
|
|
18644
|
+
}
|
|
18543
18645
|
const message = typeof body === "string" ? body : exception.message;
|
|
18544
18646
|
res.status(exception.getStatus()).json({
|
|
18545
18647
|
error: {
|
|
@@ -18550,6 +18652,17 @@ var AuthExceptionFilter = class _AuthExceptionFilter {
|
|
|
18550
18652
|
});
|
|
18551
18653
|
return;
|
|
18552
18654
|
}
|
|
18655
|
+
const refusedStatus = bodyParserStatus(exception);
|
|
18656
|
+
if (refusedStatus !== void 0) {
|
|
18657
|
+
res.status(refusedStatus).json({
|
|
18658
|
+
error: {
|
|
18659
|
+
code: AUTH_ERROR_CODES.VALIDATION,
|
|
18660
|
+
message: bodyParserMessage(refusedStatus),
|
|
18661
|
+
details: null
|
|
18662
|
+
}
|
|
18663
|
+
});
|
|
18664
|
+
return;
|
|
18665
|
+
}
|
|
18553
18666
|
this.logger.error(`unhandled exception: ${describeChannelStatus(exception)}`);
|
|
18554
18667
|
res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
|
|
18555
18668
|
error: {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bymax-one/nest-auth",
|
|
3
|
-
"version": "1.4.
|
|
3
|
+
"version": "1.4.17",
|
|
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",
|