@bymax-one/nest-auth 1.4.15 → 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 +128 -1
- package/README.md +3 -1
- package/dist/client/index.d.cts +2 -1
- package/dist/client/index.d.ts +2 -1
- package/dist/nextjs/index.d.cts +2 -1
- package/dist/nextjs/index.d.ts +2 -1
- package/dist/react/index.d.cts +2 -1
- package/dist/react/index.d.ts +2 -1
- package/dist/server/index.cjs +323 -105
- package/dist/server/index.d.cts +125 -9
- package/dist/server/index.d.ts +125 -9
- package/dist/server/index.mjs +324 -106
- package/dist/shared/index.d.cts +2 -1
- package/dist/shared/index.d.ts +2 -1
- package/package.json +3 -3
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 ?? [];
|
|
@@ -3357,6 +3363,7 @@ function _ts_param4(paramIndex, decorator) {
|
|
|
3357
3363
|
}
|
|
3358
3364
|
__name(_ts_param4, "_ts_param");
|
|
3359
3365
|
var HOSTNAME_RE = /^[a-z0-9.-]+$/i;
|
|
3366
|
+
var REFRESH_TOKEN_MAX_LENGTH = 2048;
|
|
3360
3367
|
exports.TokenDeliveryService = class TokenDeliveryService {
|
|
3361
3368
|
static {
|
|
3362
3369
|
__name(this, "TokenDeliveryService");
|
|
@@ -3651,11 +3658,28 @@ exports.TokenDeliveryService = class TokenDeliveryService {
|
|
|
3651
3658
|
if (parts.length !== 2 || parts[0]?.toLowerCase() !== "bearer") return void 0;
|
|
3652
3659
|
return parts[1];
|
|
3653
3660
|
}
|
|
3654
|
-
/**
|
|
3661
|
+
/**
|
|
3662
|
+
* Reads the refresh token from the request body field.
|
|
3663
|
+
*
|
|
3664
|
+
* An omitted field and JSON `null` both mean "no token". Any other value that is not a string
|
|
3665
|
+
* of 1 to {@link REFRESH_TOKEN_MAX_LENGTH} characters is a malformed request, not a missing
|
|
3666
|
+
* token, and is refused before any caller acts on it.
|
|
3667
|
+
*
|
|
3668
|
+
* @throws {@link AuthException} `VALIDATION` when the field is present and malformed.
|
|
3669
|
+
*/
|
|
3655
3670
|
readBodyRefresh(req) {
|
|
3656
3671
|
const body = req.body;
|
|
3657
3672
|
const value = body?.["refreshToken"];
|
|
3658
|
-
|
|
3673
|
+
if (value === void 0 || value === null) return void 0;
|
|
3674
|
+
if (typeof value !== "string" || value.length === 0 || value.length > REFRESH_TOKEN_MAX_LENGTH) {
|
|
3675
|
+
throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
|
|
3676
|
+
{
|
|
3677
|
+
field: "refreshToken",
|
|
3678
|
+
message: `refreshToken must be a string of 1 to ${REFRESH_TOKEN_MAX_LENGTH} characters`
|
|
3679
|
+
}
|
|
3680
|
+
]);
|
|
3681
|
+
}
|
|
3682
|
+
return value;
|
|
3659
3683
|
}
|
|
3660
3684
|
};
|
|
3661
3685
|
exports.TokenDeliveryService = _ts_decorate8([
|
|
@@ -4844,6 +4868,34 @@ PasswordService = _ts_decorate16([
|
|
|
4844
4868
|
typeof IPasswordBreachChecker === "undefined" ? Object : IPasswordBreachChecker
|
|
4845
4869
|
])
|
|
4846
4870
|
], PasswordService);
|
|
4871
|
+
|
|
4872
|
+
// src/server/utils/settle-writes.ts
|
|
4873
|
+
async function settleWrites(writes) {
|
|
4874
|
+
const failures = [];
|
|
4875
|
+
for (const write of writes) {
|
|
4876
|
+
try {
|
|
4877
|
+
await write();
|
|
4878
|
+
} catch (err) {
|
|
4879
|
+
failures.push(err);
|
|
4880
|
+
}
|
|
4881
|
+
}
|
|
4882
|
+
return failures;
|
|
4883
|
+
}
|
|
4884
|
+
__name(settleWrites, "settleWrites");
|
|
4885
|
+
function raiseFirst(failures) {
|
|
4886
|
+
const [first] = failures;
|
|
4887
|
+
if (failures.length > 0) throw first;
|
|
4888
|
+
}
|
|
4889
|
+
__name(raiseFirst, "raiseFirst");
|
|
4890
|
+
function settleAfter(first, followUps) {
|
|
4891
|
+
return async () => {
|
|
4892
|
+
await first();
|
|
4893
|
+
raiseFirst(await settleWrites(followUps));
|
|
4894
|
+
};
|
|
4895
|
+
}
|
|
4896
|
+
__name(settleAfter, "settleAfter");
|
|
4897
|
+
|
|
4898
|
+
// src/server/services/session.service.ts
|
|
4847
4899
|
function _ts_decorate17(decorators, target, key, desc) {
|
|
4848
4900
|
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4849
4901
|
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
|
|
@@ -4885,6 +4937,25 @@ redis.call('DEL', KEYS[1])
|
|
|
4885
4937
|
redis.call('SET', KEYS[2], ARGV[1], 'EX', ARGV[2])
|
|
4886
4938
|
return 1
|
|
4887
4939
|
`;
|
|
4940
|
+
function parseStoredDetail(raw) {
|
|
4941
|
+
try {
|
|
4942
|
+
const parsed = JSON.parse(raw);
|
|
4943
|
+
const p = parsed;
|
|
4944
|
+
if (
|
|
4945
|
+
// Stryker disable next-line ConditionalExpression,LogicalOperator: `parsed === null` is subsumed by the adjacent `typeof parsed !== 'object'` clause (typeof null is 'object' but the field reads below reject it identically)
|
|
4946
|
+
parsed === null || // Stryker disable next-line ConditionalExpression: equivalent — a non-object
|
|
4947
|
+
// parsed value reaches the field reads below as `undefined` on every property,
|
|
4948
|
+
// which reject it with the identical outcome
|
|
4949
|
+
typeof parsed !== "object" || typeof p["device"] !== "string" || typeof p["ip"] !== "string" || typeof p["createdAt"] !== "number" || typeof p["lastActivityAt"] !== "number"
|
|
4950
|
+
) {
|
|
4951
|
+
return null;
|
|
4952
|
+
}
|
|
4953
|
+
return parsed;
|
|
4954
|
+
} catch {
|
|
4955
|
+
return null;
|
|
4956
|
+
}
|
|
4957
|
+
}
|
|
4958
|
+
__name(parseStoredDetail, "parseStoredDetail");
|
|
4888
4959
|
function parseUserAgent(ua) {
|
|
4889
4960
|
let browser = "Unknown Browser";
|
|
4890
4961
|
if (/Edg\//.test(ua)) {
|
|
@@ -5034,16 +5105,19 @@ exports.SessionService = class _SessionService {
|
|
|
5034
5105
|
*
|
|
5035
5106
|
* Reads all `rt:`-prefixed members from `sess:{userId}`, fetches the
|
|
5036
5107
|
* corresponding `sd:{hash}` detail records, and marks the caller's own
|
|
5037
|
-
* session via `isCurrent`. A member whose detail record is missing
|
|
5038
|
-
*
|
|
5039
|
-
*
|
|
5040
|
-
*
|
|
5041
|
-
*
|
|
5108
|
+
* session via `isCurrent`. A member whose detail record is missing or malformed
|
|
5109
|
+
* is excluded from the result. A member whose record cannot be read at all is not
|
|
5110
|
+
* left out quietly: the call rejects, because a session missing from the list is
|
|
5111
|
+
* one the caller cannot revoke. Either way the member is offered to a
|
|
5112
|
+
* fire-and-forget prune that removes it from the SET only if its `rt:` key is
|
|
5113
|
+
* also gone — see {@link AuthRedisService.pruneDeadMembers} for why the detail
|
|
5114
|
+
* record alone does not settle it.
|
|
5042
5115
|
*
|
|
5043
5116
|
* Results are sorted by `createdAt` descending (newest session first).
|
|
5044
5117
|
*
|
|
5045
5118
|
* @param params - See {@link ListSessionsParams}.
|
|
5046
5119
|
* @returns Array of {@link SessionInfo} sorted newest-first.
|
|
5120
|
+
* @throws The store's error when a session's detail record cannot be read.
|
|
5047
5121
|
*/
|
|
5048
5122
|
async listSessions({ userId, tenantId, currentSessionHash }) {
|
|
5049
5123
|
this.assertTenant(tenantId);
|
|
@@ -5052,42 +5126,50 @@ exports.SessionService = class _SessionService {
|
|
|
5052
5126
|
});
|
|
5053
5127
|
const members = await this.redis.smembers(this.indexKey(userId, tenantId));
|
|
5054
5128
|
const rtMembers = members.filter((m) => m.startsWith("rt:"));
|
|
5129
|
+
const reads = await Promise.all(rtMembers.map((member) => this.readSession(member, currentSessionHash)));
|
|
5055
5130
|
const results = [];
|
|
5056
5131
|
const staleKeys = [];
|
|
5057
|
-
|
|
5058
|
-
|
|
5059
|
-
|
|
5060
|
-
|
|
5061
|
-
|
|
5062
|
-
|
|
5063
|
-
|
|
5064
|
-
|
|
5065
|
-
|
|
5066
|
-
|
|
5067
|
-
|
|
5068
|
-
|
|
5069
|
-
|
|
5070
|
-
|
|
5071
|
-
|
|
5072
|
-
|
|
5073
|
-
|
|
5074
|
-
|
|
5075
|
-
|
|
5076
|
-
|
|
5077
|
-
|
|
5078
|
-
|
|
5079
|
-
|
|
5080
|
-
|
|
5081
|
-
|
|
5082
|
-
|
|
5083
|
-
|
|
5084
|
-
|
|
5085
|
-
|
|
5086
|
-
|
|
5087
|
-
|
|
5088
|
-
|
|
5089
|
-
|
|
5090
|
-
|
|
5132
|
+
const failures = [];
|
|
5133
|
+
for (const read of reads) {
|
|
5134
|
+
if (read.kind === "session") results.push(read.info);
|
|
5135
|
+
else staleKeys.push(read.member);
|
|
5136
|
+
if (read.kind === "failed") failures.push(read.error);
|
|
5137
|
+
}
|
|
5138
|
+
void this.redis.pruneDeadMembers(this.indexKey(userId, tenantId), staleKeys).catch((err) => {
|
|
5139
|
+
this.logger.error(`listSessions: failed to prune ${staleKeys.length} dead member(s): ${describeChannelStatus(err)}`);
|
|
5140
|
+
});
|
|
5141
|
+
raiseFirst(failures);
|
|
5142
|
+
results.sort((a, b) => b.createdAt - a.createdAt);
|
|
5143
|
+
return results;
|
|
5144
|
+
}
|
|
5145
|
+
/**
|
|
5146
|
+
* Reads one index member's session detail and shapes it for the listing.
|
|
5147
|
+
*
|
|
5148
|
+
* @param member - The `rt:{hash}` index member.
|
|
5149
|
+
* @param currentSessionHash - Hash of the caller's own refresh token, when it sent one.
|
|
5150
|
+
* @returns The session, or why this member is not one: a data state or a read fault.
|
|
5151
|
+
*/
|
|
5152
|
+
async readSession(member, currentSessionHash) {
|
|
5153
|
+
const hash = member.slice(3);
|
|
5154
|
+
let raw;
|
|
5155
|
+
try {
|
|
5156
|
+
raw = await this.redis.get(`sd:${hash}`);
|
|
5157
|
+
} catch (error) {
|
|
5158
|
+
this.logger.warn(`listSessions: session detail read failed hash=${hash.slice(0, 8)}`);
|
|
5159
|
+
return {
|
|
5160
|
+
kind: "failed",
|
|
5161
|
+
member,
|
|
5162
|
+
error
|
|
5163
|
+
};
|
|
5164
|
+
}
|
|
5165
|
+
const detail = raw === null ? null : parseStoredDetail(raw);
|
|
5166
|
+
if (detail === null) return {
|
|
5167
|
+
kind: "stale",
|
|
5168
|
+
member
|
|
5169
|
+
};
|
|
5170
|
+
return {
|
|
5171
|
+
kind: "session",
|
|
5172
|
+
info: {
|
|
5091
5173
|
id: hash.slice(0, 8),
|
|
5092
5174
|
sessionHash: hash,
|
|
5093
5175
|
device: detail.device,
|
|
@@ -5098,13 +5180,8 @@ exports.SessionService = class _SessionService {
|
|
|
5098
5180
|
isCurrent: timingSafeCompare(hash, currentSessionHash ?? ""),
|
|
5099
5181
|
createdAt: detail.createdAt,
|
|
5100
5182
|
lastActivityAt: detail.lastActivityAt
|
|
5101
|
-
}
|
|
5102
|
-
}
|
|
5103
|
-
void this.redis.pruneDeadMembers(this.indexKey(userId, tenantId), staleKeys).catch((err) => {
|
|
5104
|
-
this.logger.error(`listSessions: failed to prune ${staleKeys.length} dead member(s): ${describeChannelStatus(err)}`);
|
|
5105
|
-
});
|
|
5106
|
-
results.sort((a, b) => b.createdAt - a.createdAt);
|
|
5107
|
-
return results;
|
|
5183
|
+
}
|
|
5184
|
+
};
|
|
5108
5185
|
}
|
|
5109
5186
|
/**
|
|
5110
5187
|
* Revokes a single session belonging to the specified user.
|
|
@@ -5166,11 +5243,47 @@ exports.SessionService = class _SessionService {
|
|
|
5166
5243
|
await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
|
|
5167
5244
|
}
|
|
5168
5245
|
/**
|
|
5246
|
+
* Refuses a session hash that names no live session of this user.
|
|
5247
|
+
*
|
|
5248
|
+
* For an operation that keeps one session and ends the rest and so has to be told which one,
|
|
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.
|
|
5251
|
+
*
|
|
5252
|
+
* @param params - See {@link LiveSessionParams}.
|
|
5253
|
+
* @throws {@link AuthException} `SESSION_NOT_FOUND` when the hash is not a live session.
|
|
5254
|
+
*/
|
|
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 }) {
|
|
5275
|
+
this.assertTenant(tenantId);
|
|
5276
|
+
this.assertValidSessionHash(sessionHash, "sessionHash");
|
|
5277
|
+
return this.resolveLiveMember(await this.redis.smembers(this.indexKey(userId, tenantId)), sessionHash);
|
|
5278
|
+
}
|
|
5279
|
+
/**
|
|
5169
5280
|
* Revokes all sessions for a user except the caller's current session.
|
|
5170
5281
|
*
|
|
5171
5282
|
* Reads all `rt:`-prefixed members from `sess:{userId}` and calls
|
|
5172
5283
|
* {@link revokeSession} for each session whose hash differs from
|
|
5173
|
-
* `currentSessionHash`. The current session is always preserved
|
|
5284
|
+
* `currentSessionHash`. The current session is always preserved, and it has to exist: a hash
|
|
5285
|
+
* that names no live session of this user is refused before anything is revoked, since keeping
|
|
5286
|
+
* nothing would revoke every session the account has, the caller's own included.
|
|
5174
5287
|
*
|
|
5175
5288
|
* The user's token epoch is advanced as part of this, which is what makes the revocation
|
|
5176
5289
|
* take effect *now* rather than whenever each device's access token happens to expire.
|
|
@@ -5189,6 +5302,8 @@ exports.SessionService = class _SessionService {
|
|
|
5189
5302
|
*
|
|
5190
5303
|
* @param userId - Internal user ID whose other sessions are being revoked.
|
|
5191
5304
|
* @param currentSessionHash - SHA-256 hash of the session to preserve.
|
|
5305
|
+
* @throws {@link AuthException} `SESSION_NOT_FOUND` when `currentSessionHash` names no live
|
|
5306
|
+
* session of this user.
|
|
5192
5307
|
* @throws {unknown} Propagates any error thrown by `revokeSession` — including
|
|
5193
5308
|
* {@link AuthException} with various codes, Redis errors, or other runtime errors.
|
|
5194
5309
|
*/
|
|
@@ -5196,10 +5311,11 @@ exports.SessionService = class _SessionService {
|
|
|
5196
5311
|
this.assertTenant(tenantId);
|
|
5197
5312
|
this.assertValidSessionHash(currentSessionHash, "currentSessionHash");
|
|
5198
5313
|
const members = await this.redis.smembers(this.indexKey(userId, tenantId));
|
|
5314
|
+
const keptHash = await this.resolveLiveMember(members, currentSessionHash);
|
|
5199
5315
|
const rtMembers = members.filter((m) => m.startsWith("rt:"));
|
|
5200
5316
|
for (const member of rtMembers) {
|
|
5201
5317
|
const hash = member.slice(3);
|
|
5202
|
-
if (timingSafeCompare(hash,
|
|
5318
|
+
if (timingSafeCompare(hash, keptHash)) continue;
|
|
5203
5319
|
try {
|
|
5204
5320
|
await this.revokeSession({
|
|
5205
5321
|
userId,
|
|
@@ -5320,6 +5436,35 @@ exports.SessionService = class _SessionService {
|
|
|
5320
5436
|
}
|
|
5321
5437
|
}
|
|
5322
5438
|
/**
|
|
5439
|
+
* The hash of the live refresh session `sessionHash` stands for within `members`.
|
|
5440
|
+
*
|
|
5441
|
+
* @throws {@link AuthException} `SESSION_NOT_FOUND`.
|
|
5442
|
+
*/
|
|
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;
|
|
5466
|
+
}
|
|
5467
|
+
/**
|
|
5323
5468
|
* The Redis key of this user's session index.
|
|
5324
5469
|
*
|
|
5325
5470
|
* Derived rather than interpolated, and tenant-scoped: `IUserRepository.findById` takes a
|
|
@@ -5362,28 +5507,18 @@ exports.SessionService = class _SessionService {
|
|
|
5362
5507
|
const rtMembers = members.filter((m) => m.startsWith("rt:"));
|
|
5363
5508
|
const limit = await this.resolveSessionLimit(userId, tenantId);
|
|
5364
5509
|
if (rtMembers.length <= limit) return;
|
|
5365
|
-
|
|
5366
|
-
|
|
5367
|
-
|
|
5368
|
-
try {
|
|
5369
|
-
const raw = await this.redis.get(`sd:${memberHash}`);
|
|
5370
|
-
if (raw !== null) {
|
|
5371
|
-
const parsed = JSON.parse(raw);
|
|
5372
|
-
if (
|
|
5373
|
-
// Stryker disable next-line ConditionalExpression: defensive `parsed !== null` guard masked by the surrounding try/catch fallback, yielding the same result
|
|
5374
|
-
parsed !== null && typeof parsed === "object" && "createdAt" in parsed && typeof parsed["createdAt"] === "number"
|
|
5375
|
-
) {
|
|
5376
|
-
createdAt = parsed.createdAt;
|
|
5377
|
-
}
|
|
5378
|
-
}
|
|
5379
|
-
} catch {
|
|
5380
|
-
}
|
|
5381
|
-
return {
|
|
5510
|
+
let withTimestamps;
|
|
5511
|
+
try {
|
|
5512
|
+
withTimestamps = await Promise.all(rtMembers.map(async (member) => ({
|
|
5382
5513
|
member,
|
|
5383
|
-
|
|
5384
|
-
|
|
5385
|
-
|
|
5386
|
-
|
|
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
|
+
}
|
|
5387
5522
|
withTimestamps.sort((a, b) => a.createdAt - b.createdAt);
|
|
5388
5523
|
const evictCount = rtMembers.length - limit;
|
|
5389
5524
|
const toEvict = withTimestamps.filter((entry) => entry.memberHash !== newHash).slice(0, evictCount);
|
|
@@ -5412,6 +5547,29 @@ exports.SessionService = class _SessionService {
|
|
|
5412
5547
|
}
|
|
5413
5548
|
}
|
|
5414
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
|
+
/**
|
|
5415
5573
|
* Resolves the maximum number of concurrent sessions allowed for a user.
|
|
5416
5574
|
*
|
|
5417
5575
|
* When `options.sessions.maxSessionsResolver` is configured, it is called with
|
|
@@ -6482,32 +6640,6 @@ function safeLogLine(line, secrets) {
|
|
|
6482
6640
|
}
|
|
6483
6641
|
__name(safeLogLine, "safeLogLine");
|
|
6484
6642
|
|
|
6485
|
-
// src/server/utils/settle-writes.ts
|
|
6486
|
-
async function settleWrites(writes) {
|
|
6487
|
-
const failures = [];
|
|
6488
|
-
for (const write of writes) {
|
|
6489
|
-
try {
|
|
6490
|
-
await write();
|
|
6491
|
-
} catch (err) {
|
|
6492
|
-
failures.push(err);
|
|
6493
|
-
}
|
|
6494
|
-
}
|
|
6495
|
-
return failures;
|
|
6496
|
-
}
|
|
6497
|
-
__name(settleWrites, "settleWrites");
|
|
6498
|
-
function raiseFirst(failures) {
|
|
6499
|
-
const [first] = failures;
|
|
6500
|
-
if (failures.length > 0) throw first;
|
|
6501
|
-
}
|
|
6502
|
-
__name(raiseFirst, "raiseFirst");
|
|
6503
|
-
function settleAfter(first, followUps) {
|
|
6504
|
-
return async () => {
|
|
6505
|
-
await first();
|
|
6506
|
-
raiseFirst(await settleWrites(followUps));
|
|
6507
|
-
};
|
|
6508
|
-
}
|
|
6509
|
-
__name(settleAfter, "settleAfter");
|
|
6510
|
-
|
|
6511
6643
|
// src/server/utils/tenant-scoped.ts
|
|
6512
6644
|
function tenantScoped(user, tenantId) {
|
|
6513
6645
|
if (user === null) return null;
|
|
@@ -12061,6 +12193,7 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
12061
12193
|
throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
|
|
12062
12194
|
}
|
|
12063
12195
|
await this.bruteForce.resetFailures(bfIdentifier);
|
|
12196
|
+
const keptHash = await this.resolveCurrentSession(userId, user.tenantId, currentRefreshToken);
|
|
12064
12197
|
await this.passwordService.assertAcceptable(dto.newPassword, "newPassword");
|
|
12065
12198
|
const passwordHash = await this.passwordService.hash(dto.newPassword);
|
|
12066
12199
|
await this.userRepo.updatePassword({
|
|
@@ -12068,17 +12201,51 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
12068
12201
|
tenantId,
|
|
12069
12202
|
passwordHash
|
|
12070
12203
|
});
|
|
12071
|
-
|
|
12204
|
+
await this.endOtherSessions(userId, user.tenantId, keptHash);
|
|
12205
|
+
await this.notifyPasswordChanged(user);
|
|
12206
|
+
}
|
|
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({
|
|
12215
|
+
userId,
|
|
12216
|
+
tenantId,
|
|
12217
|
+
sessionHash: sha256(currentRefreshToken)
|
|
12218
|
+
});
|
|
12219
|
+
}
|
|
12220
|
+
/**
|
|
12221
|
+
* Ends every session but the one to keep, once the new password is already written.
|
|
12222
|
+
*
|
|
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.
|
|
12228
|
+
*/
|
|
12229
|
+
async endOtherSessions(userId, tenantId, keptHash) {
|
|
12230
|
+
if (keptHash === void 0) {
|
|
12231
|
+
return this.endAllSessions(userId, tenantId);
|
|
12232
|
+
}
|
|
12233
|
+
try {
|
|
12072
12234
|
await this.sessionService.revokeAllExceptCurrent({
|
|
12073
12235
|
userId,
|
|
12074
|
-
tenantId
|
|
12075
|
-
currentSessionHash:
|
|
12236
|
+
tenantId,
|
|
12237
|
+
currentSessionHash: keptHash
|
|
12076
12238
|
});
|
|
12077
|
-
}
|
|
12078
|
-
|
|
12079
|
-
|
|
12239
|
+
} catch (err) {
|
|
12240
|
+
const body = err instanceof AuthException ? err.getResponse() : void 0;
|
|
12241
|
+
if (body?.error?.code !== AUTH_ERROR_CODES.SESSION_NOT_FOUND) throw err;
|
|
12242
|
+
await this.endAllSessions(userId, tenantId);
|
|
12080
12243
|
}
|
|
12081
|
-
|
|
12244
|
+
}
|
|
12245
|
+
/** Ends every session the account has and advances its token epoch. */
|
|
12246
|
+
async endAllSessions(userId, tenantId) {
|
|
12247
|
+
await this.redis.invalidateUserSessions(userId, tenantId, "dashboard");
|
|
12248
|
+
await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
|
|
12082
12249
|
}
|
|
12083
12250
|
/**
|
|
12084
12251
|
* Sends the "your password changed" notice, fire-and-forget.
|
|
@@ -18414,6 +18581,35 @@ function isAuthEnvelope(body) {
|
|
|
18414
18581
|
return typeof error === "object" && error !== null && "code" in error;
|
|
18415
18582
|
}
|
|
18416
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");
|
|
18417
18613
|
exports.AuthExceptionFilter = class _AuthExceptionFilter {
|
|
18418
18614
|
static {
|
|
18419
18615
|
__name(this, "AuthExceptionFilter");
|
|
@@ -18426,7 +18622,8 @@ exports.AuthExceptionFilter = class _AuthExceptionFilter {
|
|
|
18426
18622
|
* @param host - The arguments host, used to reach the HTTP response.
|
|
18427
18623
|
*/
|
|
18428
18624
|
catch(exception, host) {
|
|
18429
|
-
const
|
|
18625
|
+
const http = host.switchToHttp();
|
|
18626
|
+
const res = http.getResponse();
|
|
18430
18627
|
if (exception instanceof AuthException) {
|
|
18431
18628
|
res.status(exception.getStatus()).json(exception.getResponse());
|
|
18432
18629
|
return;
|
|
@@ -18437,6 +18634,16 @@ exports.AuthExceptionFilter = class _AuthExceptionFilter {
|
|
|
18437
18634
|
res.status(exception.getStatus()).json(body);
|
|
18438
18635
|
return;
|
|
18439
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
|
+
}
|
|
18440
18647
|
const message = typeof body === "string" ? body : exception.message;
|
|
18441
18648
|
res.status(exception.getStatus()).json({
|
|
18442
18649
|
error: {
|
|
@@ -18447,6 +18654,17 @@ exports.AuthExceptionFilter = class _AuthExceptionFilter {
|
|
|
18447
18654
|
});
|
|
18448
18655
|
return;
|
|
18449
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
|
+
}
|
|
18450
18668
|
this.logger.error(`unhandled exception: ${describeChannelStatus(exception)}`);
|
|
18451
18669
|
res.status(common.HttpStatus.INTERNAL_SERVER_ERROR).json({
|
|
18452
18670
|
error: {
|