@bymax-one/nest-auth 1.4.14 → 1.4.16
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 +104 -1
- package/README.md +32 -2
- 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 +203 -85
- package/dist/server/index.d.cts +85 -10
- package/dist/server/index.d.ts +85 -10
- package/dist/server/index.mjs +203 -85
- package/dist/shared/index.d.cts +2 -1
- package/dist/shared/index.d.ts +2 -1
- package/package.json +4 -3
package/dist/server/index.cjs
CHANGED
|
@@ -3357,6 +3357,7 @@ function _ts_param4(paramIndex, decorator) {
|
|
|
3357
3357
|
}
|
|
3358
3358
|
__name(_ts_param4, "_ts_param");
|
|
3359
3359
|
var HOSTNAME_RE = /^[a-z0-9.-]+$/i;
|
|
3360
|
+
var REFRESH_TOKEN_MAX_LENGTH = 2048;
|
|
3360
3361
|
exports.TokenDeliveryService = class TokenDeliveryService {
|
|
3361
3362
|
static {
|
|
3362
3363
|
__name(this, "TokenDeliveryService");
|
|
@@ -3651,11 +3652,28 @@ exports.TokenDeliveryService = class TokenDeliveryService {
|
|
|
3651
3652
|
if (parts.length !== 2 || parts[0]?.toLowerCase() !== "bearer") return void 0;
|
|
3652
3653
|
return parts[1];
|
|
3653
3654
|
}
|
|
3654
|
-
/**
|
|
3655
|
+
/**
|
|
3656
|
+
* Reads the refresh token from the request body field.
|
|
3657
|
+
*
|
|
3658
|
+
* An omitted field and JSON `null` both mean "no token". Any other value that is not a string
|
|
3659
|
+
* of 1 to {@link REFRESH_TOKEN_MAX_LENGTH} characters is a malformed request, not a missing
|
|
3660
|
+
* token, and is refused before any caller acts on it.
|
|
3661
|
+
*
|
|
3662
|
+
* @throws {@link AuthException} `VALIDATION` when the field is present and malformed.
|
|
3663
|
+
*/
|
|
3655
3664
|
readBodyRefresh(req) {
|
|
3656
3665
|
const body = req.body;
|
|
3657
3666
|
const value = body?.["refreshToken"];
|
|
3658
|
-
|
|
3667
|
+
if (value === void 0 || value === null) return void 0;
|
|
3668
|
+
if (typeof value !== "string" || value.length === 0 || value.length > REFRESH_TOKEN_MAX_LENGTH) {
|
|
3669
|
+
throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
|
|
3670
|
+
{
|
|
3671
|
+
field: "refreshToken",
|
|
3672
|
+
message: `refreshToken must be a string of 1 to ${REFRESH_TOKEN_MAX_LENGTH} characters`
|
|
3673
|
+
}
|
|
3674
|
+
]);
|
|
3675
|
+
}
|
|
3676
|
+
return value;
|
|
3659
3677
|
}
|
|
3660
3678
|
};
|
|
3661
3679
|
exports.TokenDeliveryService = _ts_decorate8([
|
|
@@ -4844,6 +4862,34 @@ PasswordService = _ts_decorate16([
|
|
|
4844
4862
|
typeof IPasswordBreachChecker === "undefined" ? Object : IPasswordBreachChecker
|
|
4845
4863
|
])
|
|
4846
4864
|
], PasswordService);
|
|
4865
|
+
|
|
4866
|
+
// src/server/utils/settle-writes.ts
|
|
4867
|
+
async function settleWrites(writes) {
|
|
4868
|
+
const failures = [];
|
|
4869
|
+
for (const write of writes) {
|
|
4870
|
+
try {
|
|
4871
|
+
await write();
|
|
4872
|
+
} catch (err) {
|
|
4873
|
+
failures.push(err);
|
|
4874
|
+
}
|
|
4875
|
+
}
|
|
4876
|
+
return failures;
|
|
4877
|
+
}
|
|
4878
|
+
__name(settleWrites, "settleWrites");
|
|
4879
|
+
function raiseFirst(failures) {
|
|
4880
|
+
const [first] = failures;
|
|
4881
|
+
if (failures.length > 0) throw first;
|
|
4882
|
+
}
|
|
4883
|
+
__name(raiseFirst, "raiseFirst");
|
|
4884
|
+
function settleAfter(first, followUps) {
|
|
4885
|
+
return async () => {
|
|
4886
|
+
await first();
|
|
4887
|
+
raiseFirst(await settleWrites(followUps));
|
|
4888
|
+
};
|
|
4889
|
+
}
|
|
4890
|
+
__name(settleAfter, "settleAfter");
|
|
4891
|
+
|
|
4892
|
+
// src/server/services/session.service.ts
|
|
4847
4893
|
function _ts_decorate17(decorators, target, key, desc) {
|
|
4848
4894
|
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4849
4895
|
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
|
|
@@ -4885,6 +4931,25 @@ redis.call('DEL', KEYS[1])
|
|
|
4885
4931
|
redis.call('SET', KEYS[2], ARGV[1], 'EX', ARGV[2])
|
|
4886
4932
|
return 1
|
|
4887
4933
|
`;
|
|
4934
|
+
function parseStoredDetail(raw) {
|
|
4935
|
+
try {
|
|
4936
|
+
const parsed = JSON.parse(raw);
|
|
4937
|
+
const p = parsed;
|
|
4938
|
+
if (
|
|
4939
|
+
// 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)
|
|
4940
|
+
parsed === null || // Stryker disable next-line ConditionalExpression: equivalent — a non-object
|
|
4941
|
+
// parsed value reaches the field reads below as `undefined` on every property,
|
|
4942
|
+
// which reject it with the identical outcome
|
|
4943
|
+
typeof parsed !== "object" || typeof p["device"] !== "string" || typeof p["ip"] !== "string" || typeof p["createdAt"] !== "number" || typeof p["lastActivityAt"] !== "number"
|
|
4944
|
+
) {
|
|
4945
|
+
return null;
|
|
4946
|
+
}
|
|
4947
|
+
return parsed;
|
|
4948
|
+
} catch {
|
|
4949
|
+
return null;
|
|
4950
|
+
}
|
|
4951
|
+
}
|
|
4952
|
+
__name(parseStoredDetail, "parseStoredDetail");
|
|
4888
4953
|
function parseUserAgent(ua) {
|
|
4889
4954
|
let browser = "Unknown Browser";
|
|
4890
4955
|
if (/Edg\//.test(ua)) {
|
|
@@ -5034,16 +5099,19 @@ exports.SessionService = class _SessionService {
|
|
|
5034
5099
|
*
|
|
5035
5100
|
* Reads all `rt:`-prefixed members from `sess:{userId}`, fetches the
|
|
5036
5101
|
* 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
|
-
*
|
|
5102
|
+
* session via `isCurrent`. A member whose detail record is missing or malformed
|
|
5103
|
+
* is excluded from the result. A member whose record cannot be read at all is not
|
|
5104
|
+
* left out quietly: the call rejects, because a session missing from the list is
|
|
5105
|
+
* one the caller cannot revoke. Either way the member is offered to a
|
|
5106
|
+
* fire-and-forget prune that removes it from the SET only if its `rt:` key is
|
|
5107
|
+
* also gone — see {@link AuthRedisService.pruneDeadMembers} for why the detail
|
|
5108
|
+
* record alone does not settle it.
|
|
5042
5109
|
*
|
|
5043
5110
|
* Results are sorted by `createdAt` descending (newest session first).
|
|
5044
5111
|
*
|
|
5045
5112
|
* @param params - See {@link ListSessionsParams}.
|
|
5046
5113
|
* @returns Array of {@link SessionInfo} sorted newest-first.
|
|
5114
|
+
* @throws The store's error when a session's detail record cannot be read.
|
|
5047
5115
|
*/
|
|
5048
5116
|
async listSessions({ userId, tenantId, currentSessionHash }) {
|
|
5049
5117
|
this.assertTenant(tenantId);
|
|
@@ -5052,42 +5120,50 @@ exports.SessionService = class _SessionService {
|
|
|
5052
5120
|
});
|
|
5053
5121
|
const members = await this.redis.smembers(this.indexKey(userId, tenantId));
|
|
5054
5122
|
const rtMembers = members.filter((m) => m.startsWith("rt:"));
|
|
5123
|
+
const reads = await Promise.all(rtMembers.map((member) => this.readSession(member, currentSessionHash)));
|
|
5055
5124
|
const results = [];
|
|
5056
5125
|
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
|
-
|
|
5126
|
+
const failures = [];
|
|
5127
|
+
for (const read of reads) {
|
|
5128
|
+
if (read.kind === "session") results.push(read.info);
|
|
5129
|
+
else staleKeys.push(read.member);
|
|
5130
|
+
if (read.kind === "failed") failures.push(read.error);
|
|
5131
|
+
}
|
|
5132
|
+
void this.redis.pruneDeadMembers(this.indexKey(userId, tenantId), staleKeys).catch((err) => {
|
|
5133
|
+
this.logger.error(`listSessions: failed to prune ${staleKeys.length} dead member(s): ${describeChannelStatus(err)}`);
|
|
5134
|
+
});
|
|
5135
|
+
raiseFirst(failures);
|
|
5136
|
+
results.sort((a, b) => b.createdAt - a.createdAt);
|
|
5137
|
+
return results;
|
|
5138
|
+
}
|
|
5139
|
+
/**
|
|
5140
|
+
* Reads one index member's session detail and shapes it for the listing.
|
|
5141
|
+
*
|
|
5142
|
+
* @param member - The `rt:{hash}` index member.
|
|
5143
|
+
* @param currentSessionHash - Hash of the caller's own refresh token, when it sent one.
|
|
5144
|
+
* @returns The session, or why this member is not one: a data state or a read fault.
|
|
5145
|
+
*/
|
|
5146
|
+
async readSession(member, currentSessionHash) {
|
|
5147
|
+
const hash = member.slice(3);
|
|
5148
|
+
let raw;
|
|
5149
|
+
try {
|
|
5150
|
+
raw = await this.redis.get(`sd:${hash}`);
|
|
5151
|
+
} catch (error) {
|
|
5152
|
+
this.logger.warn(`listSessions: session detail read failed hash=${hash.slice(0, 8)}`);
|
|
5153
|
+
return {
|
|
5154
|
+
kind: "failed",
|
|
5155
|
+
member,
|
|
5156
|
+
error
|
|
5157
|
+
};
|
|
5158
|
+
}
|
|
5159
|
+
const detail = raw === null ? null : parseStoredDetail(raw);
|
|
5160
|
+
if (detail === null) return {
|
|
5161
|
+
kind: "stale",
|
|
5162
|
+
member
|
|
5163
|
+
};
|
|
5164
|
+
return {
|
|
5165
|
+
kind: "session",
|
|
5166
|
+
info: {
|
|
5091
5167
|
id: hash.slice(0, 8),
|
|
5092
5168
|
sessionHash: hash,
|
|
5093
5169
|
device: detail.device,
|
|
@@ -5098,13 +5174,8 @@ exports.SessionService = class _SessionService {
|
|
|
5098
5174
|
isCurrent: timingSafeCompare(hash, currentSessionHash ?? ""),
|
|
5099
5175
|
createdAt: detail.createdAt,
|
|
5100
5176
|
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;
|
|
5177
|
+
}
|
|
5178
|
+
};
|
|
5108
5179
|
}
|
|
5109
5180
|
/**
|
|
5110
5181
|
* Revokes a single session belonging to the specified user.
|
|
@@ -5166,11 +5237,28 @@ exports.SessionService = class _SessionService {
|
|
|
5166
5237
|
await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
|
|
5167
5238
|
}
|
|
5168
5239
|
/**
|
|
5240
|
+
* Refuses a session hash that names no live session of this user.
|
|
5241
|
+
*
|
|
5242
|
+
* 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 same one
|
|
5244
|
+
* {@link revokeAllExceptCurrent} applies.
|
|
5245
|
+
*
|
|
5246
|
+
* @param params - See {@link LiveSessionParams}.
|
|
5247
|
+
* @throws {@link AuthException} `SESSION_NOT_FOUND` when the hash is not a live session.
|
|
5248
|
+
*/
|
|
5249
|
+
async assertLiveSession({ userId, tenantId, sessionHash }) {
|
|
5250
|
+
this.assertTenant(tenantId);
|
|
5251
|
+
this.assertValidSessionHash(sessionHash, "sessionHash");
|
|
5252
|
+
this.requireLiveMember(await this.redis.smembers(this.indexKey(userId, tenantId)), sessionHash);
|
|
5253
|
+
}
|
|
5254
|
+
/**
|
|
5169
5255
|
* Revokes all sessions for a user except the caller's current session.
|
|
5170
5256
|
*
|
|
5171
5257
|
* Reads all `rt:`-prefixed members from `sess:{userId}` and calls
|
|
5172
5258
|
* {@link revokeSession} for each session whose hash differs from
|
|
5173
|
-
* `currentSessionHash`. The current session is always preserved
|
|
5259
|
+
* `currentSessionHash`. The current session is always preserved, and it has to exist: a hash
|
|
5260
|
+
* that names no live session of this user is refused before anything is revoked, since keeping
|
|
5261
|
+
* nothing would revoke every session the account has, the caller's own included.
|
|
5174
5262
|
*
|
|
5175
5263
|
* The user's token epoch is advanced as part of this, which is what makes the revocation
|
|
5176
5264
|
* take effect *now* rather than whenever each device's access token happens to expire.
|
|
@@ -5189,6 +5277,8 @@ exports.SessionService = class _SessionService {
|
|
|
5189
5277
|
*
|
|
5190
5278
|
* @param userId - Internal user ID whose other sessions are being revoked.
|
|
5191
5279
|
* @param currentSessionHash - SHA-256 hash of the session to preserve.
|
|
5280
|
+
* @throws {@link AuthException} `SESSION_NOT_FOUND` when `currentSessionHash` names no live
|
|
5281
|
+
* session of this user.
|
|
5192
5282
|
* @throws {unknown} Propagates any error thrown by `revokeSession` — including
|
|
5193
5283
|
* {@link AuthException} with various codes, Redis errors, or other runtime errors.
|
|
5194
5284
|
*/
|
|
@@ -5196,6 +5286,7 @@ exports.SessionService = class _SessionService {
|
|
|
5196
5286
|
this.assertTenant(tenantId);
|
|
5197
5287
|
this.assertValidSessionHash(currentSessionHash, "currentSessionHash");
|
|
5198
5288
|
const members = await this.redis.smembers(this.indexKey(userId, tenantId));
|
|
5289
|
+
this.requireLiveMember(members, currentSessionHash);
|
|
5199
5290
|
const rtMembers = members.filter((m) => m.startsWith("rt:"));
|
|
5200
5291
|
for (const member of rtMembers) {
|
|
5201
5292
|
const hash = member.slice(3);
|
|
@@ -5320,6 +5411,15 @@ exports.SessionService = class _SessionService {
|
|
|
5320
5411
|
}
|
|
5321
5412
|
}
|
|
5322
5413
|
/**
|
|
5414
|
+
* Throws unless `members` holds a live refresh session with this hash.
|
|
5415
|
+
*
|
|
5416
|
+
* @throws {@link AuthException} `SESSION_NOT_FOUND`.
|
|
5417
|
+
*/
|
|
5418
|
+
requireLiveMember(members, sessionHash) {
|
|
5419
|
+
const live = members.some((member) => member.startsWith("rt:") && timingSafeCompare(member.slice(3), sessionHash));
|
|
5420
|
+
if (!live) throw new AuthException(AUTH_ERROR_CODES.SESSION_NOT_FOUND);
|
|
5421
|
+
}
|
|
5422
|
+
/**
|
|
5323
5423
|
* The Redis key of this user's session index.
|
|
5324
5424
|
*
|
|
5325
5425
|
* Derived rather than interpolated, and tenant-scoped: `IUserRepository.findById` takes a
|
|
@@ -6482,32 +6582,6 @@ function safeLogLine(line, secrets) {
|
|
|
6482
6582
|
}
|
|
6483
6583
|
__name(safeLogLine, "safeLogLine");
|
|
6484
6584
|
|
|
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
6585
|
// src/server/utils/tenant-scoped.ts
|
|
6512
6586
|
function tenantScoped(user, tenantId) {
|
|
6513
6587
|
if (user === null) return null;
|
|
@@ -11389,6 +11463,9 @@ var ChangePasswordDto = class {
|
|
|
11389
11463
|
* `whitelist: true`, which STRIPPED the property before the controller's own pipe could refuse
|
|
11390
11464
|
* it — so the suite exercised a request production never sees. Optional, because under cookie
|
|
11391
11465
|
* delivery the credential arrives in the cookie and no body field exists to declare.
|
|
11466
|
+
*
|
|
11467
|
+
* A present value is held to the contract's opaque-token bound (1 to 2048 characters), so an
|
|
11468
|
+
* empty string is refused instead of being read as "no token".
|
|
11392
11469
|
*/
|
|
11393
11470
|
refreshToken;
|
|
11394
11471
|
};
|
|
@@ -11407,7 +11484,8 @@ _ts_decorate38([
|
|
|
11407
11484
|
_ts_decorate38([
|
|
11408
11485
|
classValidator.IsOptional(),
|
|
11409
11486
|
classValidator.IsString(),
|
|
11410
|
-
classValidator.
|
|
11487
|
+
classValidator.IsNotEmpty(),
|
|
11488
|
+
classValidator.MaxLength(2048),
|
|
11411
11489
|
_ts_metadata37("design:type", String)
|
|
11412
11490
|
], ChangePasswordDto.prototype, "refreshToken", void 0);
|
|
11413
11491
|
function _ts_decorate39(decorators, target, key, desc) {
|
|
@@ -12057,6 +12135,7 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
12057
12135
|
throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
|
|
12058
12136
|
}
|
|
12059
12137
|
await this.bruteForce.resetFailures(bfIdentifier);
|
|
12138
|
+
await this.requireLiveCurrentSession(userId, user.tenantId, currentRefreshToken);
|
|
12060
12139
|
await this.passwordService.assertAcceptable(dto.newPassword, "newPassword");
|
|
12061
12140
|
const passwordHash = await this.passwordService.hash(dto.newPassword);
|
|
12062
12141
|
await this.userRepo.updatePassword({
|
|
@@ -12064,17 +12143,47 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
12064
12143
|
tenantId,
|
|
12065
12144
|
passwordHash
|
|
12066
12145
|
});
|
|
12067
|
-
|
|
12146
|
+
await this.endOtherSessions(userId, user.tenantId, currentRefreshToken);
|
|
12147
|
+
await this.notifyPasswordChanged(user);
|
|
12148
|
+
}
|
|
12149
|
+
/** Refuses a presented refresh token that names no live session of the account. */
|
|
12150
|
+
async requireLiveCurrentSession(userId, tenantId, currentRefreshToken) {
|
|
12151
|
+
if (currentRefreshToken === void 0 || currentRefreshToken.length === 0) return;
|
|
12152
|
+
await this.sessionService.assertLiveSession({
|
|
12153
|
+
userId,
|
|
12154
|
+
tenantId,
|
|
12155
|
+
sessionHash: sha256(currentRefreshToken)
|
|
12156
|
+
});
|
|
12157
|
+
}
|
|
12158
|
+
/**
|
|
12159
|
+
* Ends every session but the caller's, once the new password is already written.
|
|
12160
|
+
*
|
|
12161
|
+
* With no presented token there is no session to spare and every session ends. A token that was
|
|
12162
|
+
* live when it was checked can rotate away while the new password is hashed, and then there is
|
|
12163
|
+
* no current session left to keep either: every session ends, so the cleanup that makes the
|
|
12164
|
+
* change safe is never aborted by the session it was told to spare. Any other failure of the
|
|
12165
|
+
* sweep propagates.
|
|
12166
|
+
*/
|
|
12167
|
+
async endOtherSessions(userId, tenantId, currentRefreshToken) {
|
|
12168
|
+
if (currentRefreshToken === void 0 || currentRefreshToken.length === 0) {
|
|
12169
|
+
return this.endAllSessions(userId, tenantId);
|
|
12170
|
+
}
|
|
12171
|
+
try {
|
|
12068
12172
|
await this.sessionService.revokeAllExceptCurrent({
|
|
12069
12173
|
userId,
|
|
12070
|
-
tenantId
|
|
12174
|
+
tenantId,
|
|
12071
12175
|
currentSessionHash: sha256(currentRefreshToken)
|
|
12072
12176
|
});
|
|
12073
|
-
}
|
|
12074
|
-
|
|
12075
|
-
|
|
12177
|
+
} catch (err) {
|
|
12178
|
+
const body = err instanceof AuthException ? err.getResponse() : void 0;
|
|
12179
|
+
if (body?.error?.code !== AUTH_ERROR_CODES.SESSION_NOT_FOUND) throw err;
|
|
12180
|
+
await this.endAllSessions(userId, tenantId);
|
|
12076
12181
|
}
|
|
12077
|
-
|
|
12182
|
+
}
|
|
12183
|
+
/** Ends every session the account has and advances its token epoch. */
|
|
12184
|
+
async endAllSessions(userId, tenantId) {
|
|
12185
|
+
await this.redis.invalidateUserSessions(userId, tenantId, "dashboard");
|
|
12186
|
+
await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
|
|
12078
12187
|
}
|
|
12079
12188
|
/**
|
|
12080
12189
|
* Sends the "your password changed" notice, fire-and-forget.
|
|
@@ -12356,12 +12465,15 @@ var PasswordResetController = class {
|
|
|
12356
12465
|
* Initiates a password reset for the given email address.
|
|
12357
12466
|
*
|
|
12358
12467
|
* Sends a reset token or OTP to the user's email if the account exists and
|
|
12359
|
-
* is eligible. Always returns `200 OK` regardless of outcome
|
|
12468
|
+
* is eligible. Always returns `200 OK` with an empty JSON object regardless of outcome
|
|
12469
|
+
* (anti-enumeration; the body is pinned by the wire contract).
|
|
12360
12470
|
*
|
|
12361
12471
|
* @param dto - Validated DTO with `email` and `tenantId`.
|
|
12472
|
+
* @returns An empty object.
|
|
12362
12473
|
*/
|
|
12363
12474
|
async forgotPassword(dto, req) {
|
|
12364
12475
|
await this.passwordResetService.initiateReset(dto, req);
|
|
12476
|
+
return {};
|
|
12365
12477
|
}
|
|
12366
12478
|
// ---------------------------------------------------------------------------
|
|
12367
12479
|
// POST /password/reset-password
|
|
@@ -12441,12 +12553,15 @@ var PasswordResetController = class {
|
|
|
12441
12553
|
* Re-sends the password-reset OTP for the given email address.
|
|
12442
12554
|
*
|
|
12443
12555
|
* Subject to a 60-second atomic cooldown per `(tenantId, email)` pair.
|
|
12444
|
-
* Always returns `200 OK` regardless of outcome (anti-enumeration
|
|
12556
|
+
* Always returns `200 OK` with an empty JSON object regardless of outcome (anti-enumeration;
|
|
12557
|
+
* the body is pinned by the wire contract).
|
|
12445
12558
|
*
|
|
12446
12559
|
* @param dto - Validated DTO with `email` and `tenantId`.
|
|
12560
|
+
* @returns An empty object.
|
|
12447
12561
|
*/
|
|
12448
12562
|
async resendOtp(dto, req) {
|
|
12449
12563
|
await this.passwordResetService.resendOtp(dto, req);
|
|
12564
|
+
return {};
|
|
12450
12565
|
}
|
|
12451
12566
|
};
|
|
12452
12567
|
_ts_decorate44([
|
|
@@ -15483,7 +15598,8 @@ var REQUEST_SCHEMAS = {
|
|
|
15483
15598
|
},
|
|
15484
15599
|
"refreshToken": {
|
|
15485
15600
|
"type": "string",
|
|
15486
|
-
"maxLength":
|
|
15601
|
+
"maxLength": 2048,
|
|
15602
|
+
"minLength": 1
|
|
15487
15603
|
}
|
|
15488
15604
|
},
|
|
15489
15605
|
"required": [
|
|
@@ -17521,6 +17637,8 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
|
|
|
17521
17637
|
// in the BYMAX_AUTH_OPTIONS provider above.
|
|
17522
17638
|
// expiresIn is omitted — TokenManagerService sets it per-call via accessSignOptions().
|
|
17523
17639
|
jwt.JwtModule.registerAsync({
|
|
17640
|
+
// The factory runs here too, so it needs the modules the consumer's `inject` tokens come from.
|
|
17641
|
+
imports: options.imports ?? [],
|
|
17524
17642
|
useFactory: /* @__PURE__ */ __name(async (...args) => {
|
|
17525
17643
|
const userOptions = await options.useFactory(...args);
|
|
17526
17644
|
return {
|
package/dist/server/index.d.cts
CHANGED
|
@@ -1476,8 +1476,12 @@ interface AuthModuleAsyncOptions {
|
|
|
1476
1476
|
/**
|
|
1477
1477
|
* Factory function that produces `BymaxAuthModuleOptions`.
|
|
1478
1478
|
* Receives injected dependencies as arguments.
|
|
1479
|
+
*
|
|
1480
|
+
* The parameters are typed `never[]` so a factory may declare the types of what it injects,
|
|
1481
|
+
* `(config: ConfigService) => ...`: Nest supplies the values, and their types are the
|
|
1482
|
+
* consumer's declaration. A factory written with `...args: unknown[]` is accepted too.
|
|
1479
1483
|
*/
|
|
1480
|
-
useFactory: (...args:
|
|
1484
|
+
useFactory: (...args: never[]) => BymaxAuthModuleOptions | Promise<BymaxAuthModuleOptions>;
|
|
1481
1485
|
/** Injection tokens or providers to inject into `useFactory`. */
|
|
1482
1486
|
inject?: (InjectionToken | OptionalFactoryDependency)[];
|
|
1483
1487
|
/** Additional providers available within the async options scope. */
|
|
@@ -4569,7 +4573,11 @@ declare const WS_TICKET_TTL_SECONDS = 30;
|
|
|
4569
4573
|
interface WsTicketSnapshot {
|
|
4570
4574
|
/** The subject — the internal user id. */
|
|
4571
4575
|
sub: string;
|
|
4572
|
-
/**
|
|
4576
|
+
/**
|
|
4577
|
+
* The tenant scope. Optional because the shared `wst:` record can be written by another
|
|
4578
|
+
* backend without one; this library always sets it, and the WebSocket guard refuses a
|
|
4579
|
+
* snapshot that lacks it.
|
|
4580
|
+
*/
|
|
4573
4581
|
tenantId?: string;
|
|
4574
4582
|
/** The user's role at mint time. */
|
|
4575
4583
|
role: string;
|
|
@@ -5356,7 +5364,15 @@ declare class TokenDeliveryService {
|
|
|
5356
5364
|
private readCookie;
|
|
5357
5365
|
/** Reads the access token from the Authorization Bearer header. */
|
|
5358
5366
|
private readBearerHeader;
|
|
5359
|
-
/**
|
|
5367
|
+
/**
|
|
5368
|
+
* Reads the refresh token from the request body field.
|
|
5369
|
+
*
|
|
5370
|
+
* An omitted field and JSON `null` both mean "no token". Any other value that is not a string
|
|
5371
|
+
* of 1 to {@link REFRESH_TOKEN_MAX_LENGTH} characters is a malformed request, not a missing
|
|
5372
|
+
* token, and is refused before any caller acts on it.
|
|
5373
|
+
*
|
|
5374
|
+
* @throws {@link AuthException} `VALIDATION` when the field is present and malformed.
|
|
5375
|
+
*/
|
|
5360
5376
|
private readBodyRefresh;
|
|
5361
5377
|
}
|
|
5362
5378
|
|
|
@@ -6807,6 +6823,9 @@ declare class ChangePasswordDto {
|
|
|
6807
6823
|
* `whitelist: true`, which STRIPPED the property before the controller's own pipe could refuse
|
|
6808
6824
|
* it — so the suite exercised a request production never sees. Optional, because under cookie
|
|
6809
6825
|
* delivery the credential arrives in the cookie and no body field exists to declare.
|
|
6826
|
+
*
|
|
6827
|
+
* A present value is held to the contract's opaque-token bound (1 to 2048 characters), so an
|
|
6828
|
+
* empty string is refused instead of being read as "no token".
|
|
6810
6829
|
*/
|
|
6811
6830
|
refreshToken?: string;
|
|
6812
6831
|
}
|
|
@@ -7320,6 +7339,15 @@ interface RevokeSessionParams {
|
|
|
7320
7339
|
/** SHA-256 hash of the session being revoked. */
|
|
7321
7340
|
sessionHash: string;
|
|
7322
7341
|
}
|
|
7342
|
+
/** Names the session {@link SessionService.assertLiveSession} checks. See {@link CreateSessionParams}. */
|
|
7343
|
+
interface LiveSessionParams {
|
|
7344
|
+
/** Internal user ID that must own the session. */
|
|
7345
|
+
userId: string;
|
|
7346
|
+
/** Tenant that user belongs to; scopes the session index. */
|
|
7347
|
+
tenantId: string;
|
|
7348
|
+
/** SHA-256 hash of the session that must be live. */
|
|
7349
|
+
sessionHash: string;
|
|
7350
|
+
}
|
|
7323
7351
|
/** Everything {@link SessionService.revokeAllExceptCurrent} needs. See {@link CreateSessionParams}. */
|
|
7324
7352
|
interface RevokeAllExceptCurrentParams {
|
|
7325
7353
|
/** Internal user ID whose other sessions are ending. */
|
|
@@ -7401,18 +7429,29 @@ declare class SessionService {
|
|
|
7401
7429
|
*
|
|
7402
7430
|
* Reads all `rt:`-prefixed members from `sess:{userId}`, fetches the
|
|
7403
7431
|
* corresponding `sd:{hash}` detail records, and marks the caller's own
|
|
7404
|
-
* session via `isCurrent`. A member whose detail record is missing
|
|
7405
|
-
*
|
|
7406
|
-
*
|
|
7407
|
-
*
|
|
7408
|
-
*
|
|
7432
|
+
* session via `isCurrent`. A member whose detail record is missing or malformed
|
|
7433
|
+
* is excluded from the result. A member whose record cannot be read at all is not
|
|
7434
|
+
* left out quietly: the call rejects, because a session missing from the list is
|
|
7435
|
+
* one the caller cannot revoke. Either way the member is offered to a
|
|
7436
|
+
* fire-and-forget prune that removes it from the SET only if its `rt:` key is
|
|
7437
|
+
* also gone — see {@link AuthRedisService.pruneDeadMembers} for why the detail
|
|
7438
|
+
* record alone does not settle it.
|
|
7409
7439
|
*
|
|
7410
7440
|
* Results are sorted by `createdAt` descending (newest session first).
|
|
7411
7441
|
*
|
|
7412
7442
|
* @param params - See {@link ListSessionsParams}.
|
|
7413
7443
|
* @returns Array of {@link SessionInfo} sorted newest-first.
|
|
7444
|
+
* @throws The store's error when a session's detail record cannot be read.
|
|
7414
7445
|
*/
|
|
7415
7446
|
listSessions({ userId, tenantId, currentSessionHash }: ListSessionsParams): Promise<SessionInfo[]>;
|
|
7447
|
+
/**
|
|
7448
|
+
* Reads one index member's session detail and shapes it for the listing.
|
|
7449
|
+
*
|
|
7450
|
+
* @param member - The `rt:{hash}` index member.
|
|
7451
|
+
* @param currentSessionHash - Hash of the caller's own refresh token, when it sent one.
|
|
7452
|
+
* @returns The session, or why this member is not one: a data state or a read fault.
|
|
7453
|
+
*/
|
|
7454
|
+
private readSession;
|
|
7416
7455
|
/**
|
|
7417
7456
|
* Revokes a single session belonging to the specified user.
|
|
7418
7457
|
*
|
|
@@ -7451,12 +7490,25 @@ declare class SessionService {
|
|
|
7451
7490
|
* @throws {@link AuthException} `SESSION_NOT_FOUND` when the session is not owned by the user.
|
|
7452
7491
|
*/
|
|
7453
7492
|
revokeOtherSession({ userId, tenantId, sessionHash }: RevokeSessionParams): Promise<void>;
|
|
7493
|
+
/**
|
|
7494
|
+
* Refuses a session hash that names no live session of this user.
|
|
7495
|
+
*
|
|
7496
|
+
* 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 same one
|
|
7498
|
+
* {@link revokeAllExceptCurrent} applies.
|
|
7499
|
+
*
|
|
7500
|
+
* @param params - See {@link LiveSessionParams}.
|
|
7501
|
+
* @throws {@link AuthException} `SESSION_NOT_FOUND` when the hash is not a live session.
|
|
7502
|
+
*/
|
|
7503
|
+
assertLiveSession({ userId, tenantId, sessionHash }: LiveSessionParams): Promise<void>;
|
|
7454
7504
|
/**
|
|
7455
7505
|
* Revokes all sessions for a user except the caller's current session.
|
|
7456
7506
|
*
|
|
7457
7507
|
* Reads all `rt:`-prefixed members from `sess:{userId}` and calls
|
|
7458
7508
|
* {@link revokeSession} for each session whose hash differs from
|
|
7459
|
-
* `currentSessionHash`. The current session is always preserved
|
|
7509
|
+
* `currentSessionHash`. The current session is always preserved, and it has to exist: a hash
|
|
7510
|
+
* that names no live session of this user is refused before anything is revoked, since keeping
|
|
7511
|
+
* nothing would revoke every session the account has, the caller's own included.
|
|
7460
7512
|
*
|
|
7461
7513
|
* The user's token epoch is advanced as part of this, which is what makes the revocation
|
|
7462
7514
|
* take effect *now* rather than whenever each device's access token happens to expire.
|
|
@@ -7475,6 +7527,8 @@ declare class SessionService {
|
|
|
7475
7527
|
*
|
|
7476
7528
|
* @param userId - Internal user ID whose other sessions are being revoked.
|
|
7477
7529
|
* @param currentSessionHash - SHA-256 hash of the session to preserve.
|
|
7530
|
+
* @throws {@link AuthException} `SESSION_NOT_FOUND` when `currentSessionHash` names no live
|
|
7531
|
+
* session of this user.
|
|
7478
7532
|
* @throws {unknown} Propagates any error thrown by `revokeSession` — including
|
|
7479
7533
|
* {@link AuthException} with various codes, Redis errors, or other runtime errors.
|
|
7480
7534
|
*/
|
|
@@ -7530,6 +7584,12 @@ declare class SessionService {
|
|
|
7530
7584
|
* @throws {@link AuthException} `VALIDATION` when the value is not 64 lowercase hex characters.
|
|
7531
7585
|
*/
|
|
7532
7586
|
private assertValidSessionHash;
|
|
7587
|
+
/**
|
|
7588
|
+
* Throws unless `members` holds a live refresh session with this hash.
|
|
7589
|
+
*
|
|
7590
|
+
* @throws {@link AuthException} `SESSION_NOT_FOUND`.
|
|
7591
|
+
*/
|
|
7592
|
+
private requireLiveMember;
|
|
7533
7593
|
/**
|
|
7534
7594
|
* The Redis key of this user's session index.
|
|
7535
7595
|
*
|
|
@@ -9719,6 +9779,20 @@ declare class PasswordResetService {
|
|
|
9719
9779
|
* the configured breach checker.
|
|
9720
9780
|
*/
|
|
9721
9781
|
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
|
+
/**
|
|
9785
|
+
* Ends every session but the caller's, once the new password is already written.
|
|
9786
|
+
*
|
|
9787
|
+
* With no presented token there is no session to spare and every session ends. A token that was
|
|
9788
|
+
* live when it was checked can rotate away while the new password is hashed, and then there is
|
|
9789
|
+
* no current session left to keep either: every session ends, so the cleanup that makes the
|
|
9790
|
+
* change safe is never aborted by the session it was told to spare. Any other failure of the
|
|
9791
|
+
* sweep propagates.
|
|
9792
|
+
*/
|
|
9793
|
+
private endOtherSessions;
|
|
9794
|
+
/** Ends every session the account has and advances its token epoch. */
|
|
9795
|
+
private endAllSessions;
|
|
9722
9796
|
/**
|
|
9723
9797
|
* Sends the "your password changed" notice, fire-and-forget.
|
|
9724
9798
|
*
|
|
@@ -10965,4 +11039,5 @@ declare class ApiKeyService {
|
|
|
10965
11039
|
private validatedExpiry;
|
|
10966
11040
|
}
|
|
10967
11041
|
|
|
10968
|
-
export { API_KEY_MAX_LABEL_LENGTH, API_KEY_MAX_OVERLAP_SECONDS, AUTH_EMAIL_KINDS, AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_SECURITY_SCHEMES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AccountStatusService, AllowAllBreachChecker,
|
|
11042
|
+
export { API_KEY_MAX_LABEL_LENGTH, API_KEY_MAX_OVERLAP_SECONDS, AUTH_EMAIL_KINDS, AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_SECURITY_SCHEMES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AccountStatusService, AllowAllBreachChecker, ApiKeyGuard, ApiKeyScopes, ApiKeyService, AuthException, AuthExceptionFilter, AuthRateLimit, AuthRateLimitGuard, AuthRevocationService, AuthService, AuthTokenVerifierService, Authenticated, BYMAX_AUTH_API_KEY_CLOCK, BYMAX_AUTH_API_KEY_REPOSITORY, BYMAX_AUTH_BREACH_CHECKER, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, BruteForceService, BymaxAuthModule, ChangePasswordDto, CommonPasswordChecker, CreateInvitationDto, CurrentApiKey, CurrentUser, DefaultAuthEmailProvider, EmailChangeService, ForgotPasswordDto, HibpBreachChecker, IS_PUBLIC_KEY, InvitationService, JwtAuthGuard, JwtPlatformGuard, LoginDto, MfaChallengeDto, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, PlatformAuthService, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, Roles, RolesGuard, SKIP_MFA_KEY, SelfOrAdminGuard, ServiceKey, SessionService, SkipMfa, TokenDeliveryService, TrustedOriginGuard, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WS_TICKET_TTL_SECONDS, WsAuthExceptionFilter, WsJwtGuard, WsTicketService, authDocumentSecurity, createAuthValidationPipe, decrypt, describeChannelStatus, describeError, encrypt, generateSecureToken, hasRole, hmacSha256, redactSecrets, reduceToBaseWord, sanitizeHeaders, sha256, sleep, timingSafeCompare };
|
|
11043
|
+
export type { ApiKeyAccessEvent, ApiKeyClock, ApiKeyDenyReason, ApiKeyPrincipal, AuthApiKey, AuthApiKeySummary, AuthDocumentSecurityParams, AuthEmailCatalogue, AuthEmailContext, AuthEmailKind, AuthEmailMessage, AuthEmailSink, AuthErrorCode, AuthFieldError, AuthGuardFamily, AuthModuleAsyncOptions, AuthPlane, AuthPlatformUser, AuthRateLimitWindow, AuthResult, AuthUser, AuthenticatedRequest, BearerAuthResponse, BeforeRegisterResult, BothAuthResponse, BymaxAuthModuleOptions, BymaxAuthRateLimitOptions, ClientIpSource, CookieAuthResponse, CreateSessionParams, CreateUserData, CreateWithOAuthData, DashboardJwtPayload, DefaultAuthEmailProviderOptions, DeliveryErrorPolicy, DeliveryErrorPolicyMap, FindUserByEmailParams, FindUserByOAuthIdParams, HookContext, IApiKeyRepository, IAuthHooks, IEmailProvider, IPasswordBreachChecker, IPlatformUserRepository, IUserRepository, InviteData, IssueApiKeyInput, IssuedApiKey, LinkOAuthParams, ListSessionsParams, LiveSessionParams, MfaChallengeResult, MfaSetupResult, MfaTempPayload, OAuthLoginResult, OAuthMfaChallengeResult, OAuthProfile, OAuthProviderPlugin, OpenApiSecurityRequirement, PlatformAuthResult, PlatformAuthenticatedRequest, PlatformBearerAuthResponse, PlatformJwtPayload, ResolvedOptions, RevocableTokenPayload, RevokeAllExceptCurrentParams, RevokeAllSessionsParams, RevokeSessionParams, RotateApiKeyInput, RotatedTokenResult, SafeAuthPlatformUser, SafeAuthUser, SessionAlertInfo, SessionInfo, TenantResolverRequest, TenantScopedUserRef, UpdateEmailParams, UpdateEmailVerifiedParams, UpdateMfaData, UpdateMfaParams, UpdatePasswordParams, UpdatePlatformMfaData, UpdateStatusParams, VerifiedAccessToken, VerifyAccessTokenOptions, WsTicketSnapshot };
|