@bymax-one/nest-auth 1.4.3 → 1.4.4
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 +1128 -1
- package/README.md +355 -34
- package/dist/client/index.cjs +85 -34
- package/dist/client/index.d.cts +60 -1
- package/dist/client/index.d.ts +60 -1
- package/dist/client/index.mjs +86 -35
- package/dist/server/index.cjs +1196 -364
- package/dist/server/index.d.cts +945 -130
- package/dist/server/index.d.ts +945 -130
- package/dist/server/index.mjs +1191 -365
- package/dist/shared/index.cjs +41 -0
- package/dist/shared/index.d.cts +17 -1
- package/dist/shared/index.d.ts +17 -1
- package/dist/shared/index.mjs +41 -1
- package/package.json +5 -5
package/dist/server/index.cjs
CHANGED
|
@@ -1260,7 +1260,14 @@ var RegisterDto = class {
|
|
|
1260
1260
|
*
|
|
1261
1261
|
* Maximum 128 characters as a practical
|
|
1262
1262
|
* input bound. The service layer hashes this value immediately after receipt —
|
|
1263
|
-
* it is never logged or persisted in plaintext.
|
|
1263
|
+
* it is never logged or persisted in plaintext BY THIS LIBRARY.
|
|
1264
|
+
*
|
|
1265
|
+
* **Exactly one consumer-supplied component receives it: the breach checker.** Both paths that
|
|
1266
|
+
* create a user hash first and pass only `passwordHash` to `IUserRepository.create`, and that
|
|
1267
|
+
* interface forbids receiving or storing plaintext. Naming the repository here would invite a
|
|
1268
|
+
* consumer to build one that takes it, which is the opposite of what the contract says — so the
|
|
1269
|
+
* only place the plaintext can surface is an error the breach checker raises. See
|
|
1270
|
+
* `PasswordService.assertNotCompromised` for the ceiling and how the library holds its own half.
|
|
1264
1271
|
*/
|
|
1265
1272
|
password;
|
|
1266
1273
|
/**
|
|
@@ -1733,6 +1740,28 @@ var AuthException = class extends common.HttpException {
|
|
|
1733
1740
|
);
|
|
1734
1741
|
}
|
|
1735
1742
|
};
|
|
1743
|
+
|
|
1744
|
+
// src/server/constants/user-subject.ts
|
|
1745
|
+
function userSubject(plane, userId, tenantId) {
|
|
1746
|
+
if (plane === "platform") return `platform:${userId}`;
|
|
1747
|
+
const tenant = String(tenantId);
|
|
1748
|
+
return `dashboard:${Buffer.byteLength(tenant, "utf8")}:${tenant}:${userId}`;
|
|
1749
|
+
}
|
|
1750
|
+
__name(userSubject, "userSubject");
|
|
1751
|
+
|
|
1752
|
+
// src/server/constants/user-keys.ts
|
|
1753
|
+
function sessionIndexKey(plane, userId, hmacKey, tenantId) {
|
|
1754
|
+
const prefix = plane === "platform" ? "psess" : "sess";
|
|
1755
|
+
return `${prefix}:${hmacSha256(userSubject(plane, userId, tenantId), hmacKey)}`;
|
|
1756
|
+
}
|
|
1757
|
+
__name(sessionIndexKey, "sessionIndexKey");
|
|
1758
|
+
function tokenEpochKey(plane, userId, hmacKey, tenantId) {
|
|
1759
|
+
const prefix = plane === "platform" ? "pep" : "ep";
|
|
1760
|
+
return `${prefix}:${hmacSha256(userSubject(plane, userId, tenantId), hmacKey)}`;
|
|
1761
|
+
}
|
|
1762
|
+
__name(tokenEpochKey, "tokenEpochKey");
|
|
1763
|
+
|
|
1764
|
+
// src/server/redis/auth-redis.service.ts
|
|
1736
1765
|
function _ts_decorate5(decorators, target, key, desc) {
|
|
1737
1766
|
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
1738
1767
|
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
|
|
@@ -1919,9 +1948,19 @@ var AuthRedisService = class {
|
|
|
1919
1948
|
* away from any of them.
|
|
1920
1949
|
*/
|
|
1921
1950
|
#redis;
|
|
1951
|
+
/**
|
|
1952
|
+
* The identifier-HMAC key, for the two keyspaces that name an account.
|
|
1953
|
+
*
|
|
1954
|
+
* Also an ECMAScript private field, for the same reason as {@link #redis} and a sharper one:
|
|
1955
|
+
* this is key material. `ResolvedOptions` withholds it from serialization; keeping it
|
|
1956
|
+
* non-enumerable here means the service cannot leak it back through a `JSON.stringify` of
|
|
1957
|
+
* whichever guard or service it was injected into.
|
|
1958
|
+
*/
|
|
1959
|
+
#hmacKey;
|
|
1922
1960
|
constructor(redis, options) {
|
|
1923
1961
|
this.#redis = redis;
|
|
1924
1962
|
this.namespace = options.redisNamespace;
|
|
1963
|
+
this.#hmacKey = options.hmacKey;
|
|
1925
1964
|
}
|
|
1926
1965
|
// ---------------------------------------------------------------------------
|
|
1927
1966
|
// Private helpers
|
|
@@ -2110,7 +2149,7 @@ var AuthRedisService = class {
|
|
|
2110
2149
|
`${p.grace}:${params.oldHash}`,
|
|
2111
2150
|
`${p.consumed}:${params.oldHash}`,
|
|
2112
2151
|
`${p.family}:${params.familyId}`,
|
|
2113
|
-
|
|
2152
|
+
sessionIndexKey(params.kind, params.userId, this.#hmacKey, params.tenantId)
|
|
2114
2153
|
], [
|
|
2115
2154
|
params.newSessionJson,
|
|
2116
2155
|
String(params.refreshTtl),
|
|
@@ -2158,7 +2197,7 @@ var AuthRedisService = class {
|
|
|
2158
2197
|
const p = prefixesFor(params.kind);
|
|
2159
2198
|
await this.eval(CREATE_SESSION_LUA, [
|
|
2160
2199
|
`${p.live}:${params.tokenHash}`,
|
|
2161
|
-
|
|
2200
|
+
sessionIndexKey(params.kind, params.userId, this.#hmacKey, params.tenantId),
|
|
2162
2201
|
// Always passed, even with no family: a Lua script's key list is fixed at the call
|
|
2163
2202
|
// site, and the script skips the key rather than the caller skipping the argument.
|
|
2164
2203
|
`${p.family}:${params.familyId}`
|
|
@@ -2186,7 +2225,7 @@ var AuthRedisService = class {
|
|
|
2186
2225
|
const p = prefixesFor(params.kind);
|
|
2187
2226
|
const written = await this.eval(RECOVER_GRACE_LUA, [
|
|
2188
2227
|
`${p.live}:${params.newHash}`,
|
|
2189
|
-
|
|
2228
|
+
sessionIndexKey(params.kind, params.userId, this.#hmacKey, params.tenantId),
|
|
2190
2229
|
`${p.family}:${params.familyId}`
|
|
2191
2230
|
], [
|
|
2192
2231
|
params.newSessionJson,
|
|
@@ -2234,7 +2273,10 @@ var AuthRedisService = class {
|
|
|
2234
2273
|
* Idempotent: an empty, unknown, or already-cleared family is a no-op.
|
|
2235
2274
|
*
|
|
2236
2275
|
* @param familyId - The family id carried by the consumed-token marker.
|
|
2237
|
-
* @param kind - Which identity plane the family belongs to. Defaults to `'dashboard'`.
|
|
2276
|
+
* @param kind - Which identity plane the family belongs to. Defaults to `'dashboard'`. Unlike
|
|
2277
|
+
* the three methods that lost their default in this change, this one takes no positional
|
|
2278
|
+
* tenant beside it — the owner and its tenant come off the family's own record — so there is
|
|
2279
|
+
* no adjacent same-typed argument for it to be transposed with.
|
|
2238
2280
|
* @returns The number of members removed and the account the family belonged to. The owner
|
|
2239
2281
|
* is reported because the caller cannot obtain it any other way: the presented token's own
|
|
2240
2282
|
* `rt:` key was deleted when it was rotated, so at reuse-detection time the family index is
|
|
@@ -2248,8 +2290,9 @@ var AuthRedisService = class {
|
|
|
2248
2290
|
};
|
|
2249
2291
|
const p = prefixesFor(kind);
|
|
2250
2292
|
const members = await this.smembers(`${p.family}:${familyId}`);
|
|
2251
|
-
const ownerId = await this.readFamilyOwner(members, p.live);
|
|
2252
|
-
const
|
|
2293
|
+
const { userId: ownerId, tenantId } = await this.readFamilyOwner(members, p.live);
|
|
2294
|
+
const nameable = ownerId !== "" && (kind === "platform" || (tenantId ?? "") !== "");
|
|
2295
|
+
const indexKey = nameable ? this.prefix(sessionIndexKey(kind, ownerId, this.#hmacKey, tenantId)) : "";
|
|
2253
2296
|
const removed = await this.eval(REVOKE_FAMILY_LUA, [
|
|
2254
2297
|
`${p.family}:${familyId}`
|
|
2255
2298
|
], [
|
|
@@ -2270,25 +2313,40 @@ var AuthRedisService = class {
|
|
|
2270
2313
|
* names the owner. Reading it here rather than decoding JSON inside the revocation script
|
|
2271
2314
|
* keeps the script free of `cjson` and uses a real parser on the stored record.
|
|
2272
2315
|
*
|
|
2316
|
+
* The TENANT comes off the same record, because the index key the caller then builds is
|
|
2317
|
+
* scoped to it. Reading the two together is what keeps them from disagreeing: an owner
|
|
2318
|
+
* resolved from one member and a tenant guessed from anywhere else would name a key that
|
|
2319
|
+
* belongs to neither.
|
|
2320
|
+
*
|
|
2273
2321
|
* @param members - The family index members (bare session hashes).
|
|
2274
2322
|
* @param livePrefix - The live-session prefix for the plane (`rt` or `prt`).
|
|
2275
|
-
* @returns The owner
|
|
2276
|
-
*
|
|
2323
|
+
* @returns The owner and its tenant; `userId` is `''` when no member NAMES one — every member
|
|
2324
|
+
* record gone, or a record that will not parse, or one carrying no `userId`. The three are
|
|
2325
|
+
* indistinguishable from here, so a caller reporting this must say what was observed rather
|
|
2326
|
+
* than why.
|
|
2277
2327
|
*/
|
|
2278
2328
|
async readFamilyOwner(members, livePrefix) {
|
|
2279
2329
|
for (const hash of members) {
|
|
2280
2330
|
const record = await this.get(`${livePrefix}:${hash}`);
|
|
2281
2331
|
if (record === null) continue;
|
|
2282
|
-
let
|
|
2332
|
+
let parsed;
|
|
2283
2333
|
try {
|
|
2284
|
-
|
|
2334
|
+
parsed = JSON.parse(record);
|
|
2285
2335
|
} catch {
|
|
2286
2336
|
}
|
|
2337
|
+
const userId = parsed?.["userId"];
|
|
2287
2338
|
if (typeof userId === "string" && userId !== "") {
|
|
2288
|
-
|
|
2339
|
+
const tenantId = parsed?.["tenantId"];
|
|
2340
|
+
return {
|
|
2341
|
+
userId,
|
|
2342
|
+
tenantId: typeof tenantId === "string" ? tenantId : void 0
|
|
2343
|
+
};
|
|
2289
2344
|
}
|
|
2290
2345
|
}
|
|
2291
|
-
return
|
|
2346
|
+
return {
|
|
2347
|
+
userId: "",
|
|
2348
|
+
tenantId: void 0
|
|
2349
|
+
};
|
|
2292
2350
|
}
|
|
2293
2351
|
// ---------------------------------------------------------------------------
|
|
2294
2352
|
// Atomic compound operations
|
|
@@ -2471,17 +2529,22 @@ var AuthRedisService = class {
|
|
|
2471
2529
|
* Atomically deletes all refresh sessions for a user on the given identity plane.
|
|
2472
2530
|
*
|
|
2473
2531
|
* Each plane sweeps only its own index — `sess:` for dashboard, `psess:` for platform — so
|
|
2474
|
-
* an admin and a user who happen to share an id never revoke each other's sessions.
|
|
2532
|
+
* an admin and a user who happen to share an id never revoke each other's sessions. The
|
|
2533
|
+
* dashboard index is scoped to the tenant as well, because that plane's ids are only unique
|
|
2534
|
+
* within one: without it a sweep aimed at `t1/u1` also emptied `t2/u1`.
|
|
2475
2535
|
*
|
|
2476
2536
|
* @param userId - Internal user or admin ID whose sessions will be invalidated.
|
|
2477
|
-
* @param
|
|
2537
|
+
* @param tenantId - The tenant the dashboard account belongs to; ignored on the platform plane.
|
|
2538
|
+
* @param kind - Which identity plane to revoke. **Required** — the default was removed because
|
|
2539
|
+
* a positional plane beside a positional tenant is a transposition nobody notices.
|
|
2478
2540
|
*/
|
|
2479
|
-
async invalidateUserSessions(userId, kind
|
|
2541
|
+
async invalidateUserSessions(userId, tenantId, kind) {
|
|
2542
|
+
const key = sessionIndexKey(kind, userId, this.#hmacKey, tenantId);
|
|
2480
2543
|
if (kind === "platform") {
|
|
2481
|
-
await this.sweepSessionIndex(
|
|
2544
|
+
await this.sweepSessionIndex(key, "prt:", "prp:", "psd:");
|
|
2482
2545
|
return;
|
|
2483
2546
|
}
|
|
2484
|
-
await this.sweepSessionIndex(
|
|
2547
|
+
await this.sweepSessionIndex(key, "rt:", "rp:", "sd:");
|
|
2485
2548
|
}
|
|
2486
2549
|
/**
|
|
2487
2550
|
* Atomically increments a counter and sets a fixed TTL on the **first** increment.
|
|
@@ -2525,11 +2588,13 @@ var AuthRedisService = class {
|
|
|
2525
2588
|
* bumped carries one.
|
|
2526
2589
|
*
|
|
2527
2590
|
* @param userId - Internal user or admin ID to look up.
|
|
2528
|
-
* @param
|
|
2591
|
+
* @param tenantId - The tenant the dashboard account belongs to; ignored on the platform plane.
|
|
2592
|
+
* @param kind - Which identity plane to read. **Required** — the default was removed because
|
|
2593
|
+
* a positional plane beside a positional tenant is a transposition nobody notices.
|
|
2529
2594
|
* @returns The stored epoch, or `0` when none is stored or the value is unreadable.
|
|
2530
2595
|
*/
|
|
2531
|
-
async getUserTokenEpoch(userId, kind
|
|
2532
|
-
const raw = await this.get(
|
|
2596
|
+
async getUserTokenEpoch(userId, tenantId, kind) {
|
|
2597
|
+
const raw = await this.get(tokenEpochKey(kind, userId, this.#hmacKey, tenantId));
|
|
2533
2598
|
const parsed = Number(raw);
|
|
2534
2599
|
return Number.isInteger(parsed) ? Math.max(0, parsed) : 0;
|
|
2535
2600
|
}
|
|
@@ -2541,22 +2606,40 @@ var AuthRedisService = class {
|
|
|
2541
2606
|
* cannot serve that purpose when the token is allowed to be absent or expired — and taking
|
|
2542
2607
|
* the owner from an unverified token would let a caller aim the revocation at someone else.
|
|
2543
2608
|
*
|
|
2544
|
-
* A record that is missing, unparseable, or carries no string `userId` answers
|
|
2545
|
-
* is nothing to attribute the logout to, which the caller treats as "no live
|
|
2609
|
+
* A record that is missing, unparseable, or carries no string `userId` answers an empty
|
|
2610
|
+
* `userId`: there is nothing to attribute the logout to, which the caller treats as "no live
|
|
2611
|
+
* session".
|
|
2612
|
+
*
|
|
2613
|
+
* **The tenant comes from the same record, and that is the point.** Revoking the session
|
|
2614
|
+
* needs the owner's index key, which is tenant-scoped on the dashboard plane — and the one
|
|
2615
|
+
* place the tenant can be read without trusting the caller is the record the refresh token
|
|
2616
|
+
* just proved possession of. Taking it from an access token's claims would let a caller aim a
|
|
2617
|
+
* revocation at the colliding id in another tenant, which is the same reasoning that already
|
|
2618
|
+
* kept the OWNER out of those claims.
|
|
2546
2619
|
*
|
|
2547
2620
|
* @param key - The un-namespaced session key (`rt:{hash}` or `prt:{hash}`).
|
|
2548
|
-
* @returns The recorded
|
|
2621
|
+
* @returns The recorded owner and tenant; `userId` is `''` when there is no usable record.
|
|
2549
2622
|
*/
|
|
2550
2623
|
async readSessionOwner(key) {
|
|
2624
|
+
const none = {
|
|
2625
|
+
userId: "",
|
|
2626
|
+
tenantId: void 0
|
|
2627
|
+
};
|
|
2551
2628
|
const raw = await this.get(key);
|
|
2552
|
-
if (raw === null) return
|
|
2629
|
+
if (raw === null) return none;
|
|
2553
2630
|
try {
|
|
2554
2631
|
const parsed = JSON.parse(raw);
|
|
2555
|
-
if (typeof parsed !== "object" || parsed === null) return
|
|
2556
|
-
const
|
|
2557
|
-
|
|
2632
|
+
if (typeof parsed !== "object" || parsed === null) return none;
|
|
2633
|
+
const record = parsed;
|
|
2634
|
+
const userId = record["userId"];
|
|
2635
|
+
if (typeof userId !== "string") return none;
|
|
2636
|
+
const tenantId = record["tenantId"];
|
|
2637
|
+
return {
|
|
2638
|
+
userId,
|
|
2639
|
+
tenantId: typeof tenantId === "string" && tenantId !== "" ? tenantId : void 0
|
|
2640
|
+
};
|
|
2558
2641
|
} catch {
|
|
2559
|
-
return
|
|
2642
|
+
return none;
|
|
2560
2643
|
}
|
|
2561
2644
|
}
|
|
2562
2645
|
/**
|
|
@@ -2569,11 +2652,13 @@ var AuthRedisService = class {
|
|
|
2569
2652
|
* runs from the latest bump: by then every token stamped below it has expired anyway.
|
|
2570
2653
|
*
|
|
2571
2654
|
* @param userId - Internal user or admin ID whose outstanding access tokens are revoked.
|
|
2572
|
-
* @param
|
|
2655
|
+
* @param tenantId - The tenant the dashboard account belongs to; ignored on the platform plane.
|
|
2656
|
+
* @param kind - Which identity plane to bump. **Required** — the default was removed because
|
|
2657
|
+
* a positional plane beside a positional tenant is a transposition nobody notices.
|
|
2573
2658
|
* @returns The epoch after the increment.
|
|
2574
2659
|
*/
|
|
2575
|
-
async bumpUserTokenEpoch(userId, kind
|
|
2576
|
-
const key =
|
|
2660
|
+
async bumpUserTokenEpoch(userId, tenantId, kind) {
|
|
2661
|
+
const key = tokenEpochKey(kind, userId, this.#hmacKey, tenantId);
|
|
2577
2662
|
const result = await this.eval(`local v = redis.call('INCR', KEYS[1])
|
|
2578
2663
|
redis.call('EXPIRE', KEYS[1], ARGV[1])
|
|
2579
2664
|
return v`, [
|
|
@@ -2826,6 +2911,108 @@ function assertNotBlocked(status, blockedStatuses) {
|
|
|
2826
2911
|
}
|
|
2827
2912
|
__name(assertNotBlocked, "assertNotBlocked");
|
|
2828
2913
|
|
|
2914
|
+
// src/server/utils/log-safe.ts
|
|
2915
|
+
var RECORD_BREAKING_CHARACTERS = /[\u0000-\u001F\u007F-\u009F\u2028\u2029]/;
|
|
2916
|
+
function logSafe(value) {
|
|
2917
|
+
return RECORD_BREAKING_CHARACTERS.test(value) ? "<malformed>" : value;
|
|
2918
|
+
}
|
|
2919
|
+
__name(logSafe, "logSafe");
|
|
2920
|
+
|
|
2921
|
+
// src/server/utils/redact-secrets.ts
|
|
2922
|
+
var REDACTED = "<redacted>";
|
|
2923
|
+
function redactSecrets(value, secrets) {
|
|
2924
|
+
const present = secrets.filter((secret) => typeof secret === "string" && secret.length > 0).sort((a, b) => b.length - a.length);
|
|
2925
|
+
if (present.length === 0) return value;
|
|
2926
|
+
const marker = present.some((secret) => REDACTED.includes(secret)) ? "" : REDACTED;
|
|
2927
|
+
let out = "";
|
|
2928
|
+
let index = 0;
|
|
2929
|
+
while (index < value.length) {
|
|
2930
|
+
const matched = longestMatchAt(value, present, index);
|
|
2931
|
+
if (matched === 0) {
|
|
2932
|
+
out += value.charAt(index);
|
|
2933
|
+
index += 1;
|
|
2934
|
+
continue;
|
|
2935
|
+
}
|
|
2936
|
+
let end = index + matched;
|
|
2937
|
+
for (let inner = index; inner < end; inner += 1) {
|
|
2938
|
+
end = Math.max(end, inner + longestMatchAt(value, present, inner));
|
|
2939
|
+
}
|
|
2940
|
+
out += marker;
|
|
2941
|
+
index = end;
|
|
2942
|
+
}
|
|
2943
|
+
if (present.some((secret) => out.includes(secret))) return "";
|
|
2944
|
+
return out;
|
|
2945
|
+
}
|
|
2946
|
+
__name(redactSecrets, "redactSecrets");
|
|
2947
|
+
function longestMatchAt(value, secrets, at) {
|
|
2948
|
+
for (const secret of secrets) {
|
|
2949
|
+
if (value.startsWith(secret, at)) return secret.length;
|
|
2950
|
+
}
|
|
2951
|
+
return 0;
|
|
2952
|
+
}
|
|
2953
|
+
__name(longestMatchAt, "longestMatchAt");
|
|
2954
|
+
|
|
2955
|
+
// src/server/utils/describe-error.ts
|
|
2956
|
+
var ERROR_TEXT_LIMIT = 200;
|
|
2957
|
+
var ERROR_CAUSE_DEPTH = 3;
|
|
2958
|
+
var MALFORMED = "<malformed-error>";
|
|
2959
|
+
var OPAQUE_NAME = "<error>";
|
|
2960
|
+
function isError(value) {
|
|
2961
|
+
try {
|
|
2962
|
+
return value instanceof Error;
|
|
2963
|
+
} catch {
|
|
2964
|
+
return false;
|
|
2965
|
+
}
|
|
2966
|
+
}
|
|
2967
|
+
__name(isError, "isError");
|
|
2968
|
+
function describeOneLink(error, secrets, channelText) {
|
|
2969
|
+
try {
|
|
2970
|
+
const name = nameOf(error, secrets, channelText);
|
|
2971
|
+
const detail = channelText === "drop" ? "" : logSafe(redactSecrets(String(error.message), secrets));
|
|
2972
|
+
const link = detail === "" ? name : `${name}: ${detail}`;
|
|
2973
|
+
return link === "" ? OPAQUE_NAME : link;
|
|
2974
|
+
} catch {
|
|
2975
|
+
return MALFORMED;
|
|
2976
|
+
}
|
|
2977
|
+
}
|
|
2978
|
+
__name(describeOneLink, "describeOneLink");
|
|
2979
|
+
function nameOf(error, secrets, channelText) {
|
|
2980
|
+
if (channelText === "drop") return OPAQUE_NAME;
|
|
2981
|
+
return logSafe(redactSecrets(String(error.name), secrets));
|
|
2982
|
+
}
|
|
2983
|
+
__name(nameOf, "nameOf");
|
|
2984
|
+
function readCause(error) {
|
|
2985
|
+
try {
|
|
2986
|
+
return error.cause;
|
|
2987
|
+
} catch {
|
|
2988
|
+
return void 0;
|
|
2989
|
+
}
|
|
2990
|
+
}
|
|
2991
|
+
__name(readCause, "readCause");
|
|
2992
|
+
function describe(error, secrets, channelText) {
|
|
2993
|
+
const parts = [];
|
|
2994
|
+
let current = error;
|
|
2995
|
+
for (let depth = 0; depth < ERROR_CAUSE_DEPTH && current !== void 0 && current !== null; depth++) {
|
|
2996
|
+
if (!isError(current)) {
|
|
2997
|
+
parts.push(`<non-error: ${typeof current}>`);
|
|
2998
|
+
break;
|
|
2999
|
+
}
|
|
3000
|
+
parts.push(describeOneLink(current, secrets, channelText));
|
|
3001
|
+
current = readCause(current);
|
|
3002
|
+
}
|
|
3003
|
+
const line = parts.length === 0 ? `<non-error: ${typeof error}>` : parts.join(" <- ");
|
|
3004
|
+
return redactSecrets(line, secrets).slice(0, ERROR_TEXT_LIMIT);
|
|
3005
|
+
}
|
|
3006
|
+
__name(describe, "describe");
|
|
3007
|
+
function describeError(error, secrets) {
|
|
3008
|
+
return describe(error, secrets, "redact");
|
|
3009
|
+
}
|
|
3010
|
+
__name(describeError, "describeError");
|
|
3011
|
+
function describeChannelStatus(error) {
|
|
3012
|
+
return describe(error, [], "drop");
|
|
3013
|
+
}
|
|
3014
|
+
__name(describeChannelStatus, "describeChannelStatus");
|
|
3015
|
+
|
|
2829
3016
|
// src/server/utils/stamped-epoch.ts
|
|
2830
3017
|
function readStampedEpoch(payload) {
|
|
2831
3018
|
const { epoch } = payload;
|
|
@@ -2940,7 +3127,10 @@ exports.AuthRevocationService = class AuthRevocationService {
|
|
|
2940
3127
|
if (await this.redis.get(`rv:${payload.jti}`) !== null) {
|
|
2941
3128
|
return true;
|
|
2942
3129
|
}
|
|
2943
|
-
|
|
3130
|
+
if (kind === "dashboard" && (payload.tenantId === void 0 || payload.tenantId === "")) {
|
|
3131
|
+
return true;
|
|
3132
|
+
}
|
|
3133
|
+
const epoch = await this.redis.getUserTokenEpoch(payload.sub, payload.tenantId, kind);
|
|
2944
3134
|
return readStampedEpoch(payload) < epoch;
|
|
2945
3135
|
}
|
|
2946
3136
|
};
|
|
@@ -3549,7 +3739,10 @@ exports.UserStatusGuard = class UserStatusGuard {
|
|
|
3549
3739
|
let status = await this.redis.get(statusKey);
|
|
3550
3740
|
let verified = requireVerified ? await this.redis.get(verifiedKey) : null;
|
|
3551
3741
|
if (status === null || requireVerified && verified === null) {
|
|
3552
|
-
const userRecord = await this.userRepo.findById(
|
|
3742
|
+
const userRecord = await this.userRepo.findById({
|
|
3743
|
+
id: userId,
|
|
3744
|
+
tenantId
|
|
3745
|
+
});
|
|
3553
3746
|
if (!userRecord) {
|
|
3554
3747
|
throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
|
|
3555
3748
|
}
|
|
@@ -4147,7 +4340,12 @@ var PasswordService = class _PasswordService {
|
|
|
4147
4340
|
* documented behaviour, and worst during an incident, when changing the password is the
|
|
4148
4341
|
* urgent thing. A refusal to answer is not evidence against the password.
|
|
4149
4342
|
*
|
|
4150
|
-
* The plaintext is
|
|
4343
|
+
* The plaintext is not passed to the logger, and neither is the checker's ERROR — which is the
|
|
4344
|
+
* part that took a measurement to learn. A breach checker receives the plaintext by contract, so
|
|
4345
|
+
* an error it raises is a place the plaintext can be: an HTTP client that echoes the request it
|
|
4346
|
+
* failed on, a validation error quoting the value it rejected. `logger.error(msg, err)` then
|
|
4347
|
+
* publishes that, plus the stack and whatever properties the client hung on it. Same shape as
|
|
4348
|
+
* the mail-channel leak this library fixed in `DefaultAuthEmailProvider`, one port over.
|
|
4151
4349
|
*
|
|
4152
4350
|
* @param plain - The plaintext password the user is trying to set.
|
|
4153
4351
|
* @throws {@link AuthException} with `PASSWORD_COMPROMISED` when the corpus knows it.
|
|
@@ -4156,8 +4354,8 @@ var PasswordService = class _PasswordService {
|
|
|
4156
4354
|
let breached;
|
|
4157
4355
|
try {
|
|
4158
4356
|
breached = await this.breachChecker.isBreached(plain);
|
|
4159
|
-
} catch
|
|
4160
|
-
this.logger.error("breach check threw; admitting the password (the checker fails open)"
|
|
4357
|
+
} catch {
|
|
4358
|
+
this.logger.error("breach check threw; admitting the password (the checker fails open)");
|
|
4161
4359
|
return;
|
|
4162
4360
|
}
|
|
4163
4361
|
if (breached) {
|
|
@@ -4366,6 +4564,36 @@ exports.SessionService = class _SessionService {
|
|
|
4366
4564
|
// Public API
|
|
4367
4565
|
// ---------------------------------------------------------------------------
|
|
4368
4566
|
/**
|
|
4567
|
+
* Refuses a dashboard tenant that names nothing, at the public boundary.
|
|
4568
|
+
*
|
|
4569
|
+
* Every method on this service takes the tenant as a REQUIRED named field, and all of them are
|
|
4570
|
+
* exported — the object form replaced the positional one precisely so a `string` tenant could
|
|
4571
|
+
* not be transposed with a `string` user id or session hash. Naming it removes the transposition
|
|
4572
|
+
* but not the empty string: a caller can still pass `''`, and that is what this refuses.
|
|
4573
|
+
*
|
|
4574
|
+
* `userSubject` cannot enforce it instead: the rotation scripts must be
|
|
4575
|
+
* called with the empty PLACEHOLDER identity to discover a grace pointer, so the innermost
|
|
4576
|
+
* builder has to stay total, and an empty key in a script's KEYS array is not "no key" — the
|
|
4577
|
+
* `eval` wrapper prefixes it into a real key named `auth:`.
|
|
4578
|
+
*
|
|
4579
|
+
* So the refusal lives here, where a caller can actually be wrong. `''` derived
|
|
4580
|
+
* `dashboard:0::{userId}`, swept and bumped keys nobody writes, and returned normally — a
|
|
4581
|
+
* revocation reported as done while every session and access token it named stayed valid.
|
|
4582
|
+
*
|
|
4583
|
+
* @param tenantId - The tenant supplied by the caller.
|
|
4584
|
+
* @throws {@link AuthException} `VALIDATION` when it is blank.
|
|
4585
|
+
*/
|
|
4586
|
+
assertTenant(tenantId) {
|
|
4587
|
+
if (tenantId === "") {
|
|
4588
|
+
throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
|
|
4589
|
+
{
|
|
4590
|
+
field: "tenantId",
|
|
4591
|
+
message: "tenantId is required to name a session index"
|
|
4592
|
+
}
|
|
4593
|
+
]);
|
|
4594
|
+
}
|
|
4595
|
+
}
|
|
4596
|
+
/**
|
|
4369
4597
|
* Records a new session in Redis and enforces the concurrent session limit.
|
|
4370
4598
|
*
|
|
4371
4599
|
* Stores device and activity metadata under `sd:{hash}` with the same TTL
|
|
@@ -4382,13 +4610,11 @@ exports.SessionService = class _SessionService {
|
|
|
4382
4610
|
* before the SET member is committed, the limit check will see one fewer
|
|
4383
4611
|
* session than actually exists, allowing a permanent extra session.
|
|
4384
4612
|
*
|
|
4385
|
-
* @param
|
|
4386
|
-
* @param rawRefreshToken - The raw opaque refresh token (hashed before storage).
|
|
4387
|
-
* @param ip - Client IP address for the new session.
|
|
4388
|
-
* @param userAgent - Raw `User-Agent` header value for device detection.
|
|
4613
|
+
* @param params - See {@link CreateSessionParams}.
|
|
4389
4614
|
* @returns The SHA-256 hash of `rawRefreshToken` used as the session key.
|
|
4390
4615
|
*/
|
|
4391
|
-
async createSession(userId, rawRefreshToken, ip, userAgent) {
|
|
4616
|
+
async createSession({ userId, tenantId, rawRefreshToken, ip, userAgent }) {
|
|
4617
|
+
this.assertTenant(tenantId);
|
|
4392
4618
|
const hash = sha256(rawRefreshToken);
|
|
4393
4619
|
const device = parseUserAgent(userAgent);
|
|
4394
4620
|
const now = Date.now();
|
|
@@ -4402,7 +4628,7 @@ exports.SessionService = class _SessionService {
|
|
|
4402
4628
|
lastActivityAt: now
|
|
4403
4629
|
};
|
|
4404
4630
|
await this.redis.set(`sd:${hash}`, JSON.stringify(detail), ttl);
|
|
4405
|
-
await this.enforceSessionLimit(userId, hash, ip, userAgent);
|
|
4631
|
+
await this.enforceSessionLimit(userId, tenantId, hash, ip, userAgent);
|
|
4406
4632
|
if (this.hooks?.onNewSession) {
|
|
4407
4633
|
const { onNewSession } = this.hooks;
|
|
4408
4634
|
const minimalSessionInfo = {
|
|
@@ -4415,13 +4641,16 @@ exports.SessionService = class _SessionService {
|
|
|
4415
4641
|
userAgent,
|
|
4416
4642
|
sanitizedHeaders: {}
|
|
4417
4643
|
};
|
|
4418
|
-
void this.userRepo.findById(
|
|
4644
|
+
void this.userRepo.findById({
|
|
4645
|
+
id: userId,
|
|
4646
|
+
tenantId
|
|
4647
|
+
}).then((user) => {
|
|
4419
4648
|
if (!user) return;
|
|
4420
4649
|
void Promise.resolve(onNewSession(toSafeUser(user), minimalSessionInfo, context)).catch((err) => {
|
|
4421
|
-
this.logger.error(
|
|
4650
|
+
this.logger.error(`onNewSession hook threw: ${describeChannelStatus(err)}`);
|
|
4422
4651
|
});
|
|
4423
4652
|
}).catch((err) => {
|
|
4424
|
-
this.logger.error(
|
|
4653
|
+
this.logger.error(`onNewSession hook \u2014 findById failed: ${describeChannelStatus(err)}`);
|
|
4425
4654
|
});
|
|
4426
4655
|
}
|
|
4427
4656
|
return hash;
|
|
@@ -4439,16 +4668,15 @@ exports.SessionService = class _SessionService {
|
|
|
4439
4668
|
*
|
|
4440
4669
|
* Results are sorted by `createdAt` descending (newest session first).
|
|
4441
4670
|
*
|
|
4442
|
-
* @param
|
|
4443
|
-
* @param currentSessionHash - Optional SHA-256 hash of the caller's active session;
|
|
4444
|
-
* matched session will have `isCurrent: true`.
|
|
4671
|
+
* @param params - See {@link ListSessionsParams}.
|
|
4445
4672
|
* @returns Array of {@link SessionInfo} sorted newest-first.
|
|
4446
4673
|
*/
|
|
4447
|
-
async listSessions(userId, currentSessionHash) {
|
|
4448
|
-
|
|
4449
|
-
|
|
4674
|
+
async listSessions({ userId, tenantId, currentSessionHash }) {
|
|
4675
|
+
this.assertTenant(tenantId);
|
|
4676
|
+
void this.redis.pruneExpiredGraceMembers(this.indexKey(userId, tenantId), "rp:").catch((err) => {
|
|
4677
|
+
this.logger.warn(`listSessions: grace-pointer prune failed: ${describeChannelStatus(err)}`);
|
|
4450
4678
|
});
|
|
4451
|
-
const members = await this.redis.smembers(
|
|
4679
|
+
const members = await this.redis.smembers(this.indexKey(userId, tenantId));
|
|
4452
4680
|
const rtMembers = members.filter((m) => m.startsWith("rt:"));
|
|
4453
4681
|
const results = [];
|
|
4454
4682
|
const staleKeys = [];
|
|
@@ -4498,8 +4726,8 @@ exports.SessionService = class _SessionService {
|
|
|
4498
4726
|
lastActivityAt: detail.lastActivityAt
|
|
4499
4727
|
});
|
|
4500
4728
|
}));
|
|
4501
|
-
void this.redis.pruneDeadMembers(
|
|
4502
|
-
this.logger.error(`listSessions: failed to prune ${staleKeys.length} dead member(s)
|
|
4729
|
+
void this.redis.pruneDeadMembers(this.indexKey(userId, tenantId), staleKeys).catch((err) => {
|
|
4730
|
+
this.logger.error(`listSessions: failed to prune ${staleKeys.length} dead member(s): ${describeChannelStatus(err)}`);
|
|
4503
4731
|
});
|
|
4504
4732
|
results.sort((a, b) => b.createdAt - a.createdAt);
|
|
4505
4733
|
return results;
|
|
@@ -4516,10 +4744,11 @@ exports.SessionService = class _SessionService {
|
|
|
4516
4744
|
* @param sessionHash - SHA-256 hash of the refresh token identifying the session.
|
|
4517
4745
|
* @throws {@link AuthException} `SESSION_NOT_FOUND` when the session is not owned by the user.
|
|
4518
4746
|
*/
|
|
4519
|
-
async revokeSession(userId, sessionHash) {
|
|
4747
|
+
async revokeSession({ userId, tenantId, sessionHash }) {
|
|
4748
|
+
this.assertTenant(tenantId);
|
|
4520
4749
|
this.assertValidSessionHash(sessionHash);
|
|
4521
4750
|
const result = await this.redis.eval(REVOKE_SESSION_LUA, [
|
|
4522
|
-
|
|
4751
|
+
this.indexKey(userId, tenantId),
|
|
4523
4752
|
`rt:${sessionHash}`,
|
|
4524
4753
|
`sd:${sessionHash}`
|
|
4525
4754
|
], [
|
|
@@ -4554,9 +4783,13 @@ exports.SessionService = class _SessionService {
|
|
|
4554
4783
|
* @param sessionHash - SHA-256 hash of the refresh token identifying the session.
|
|
4555
4784
|
* @throws {@link AuthException} `SESSION_NOT_FOUND` when the session is not owned by the user.
|
|
4556
4785
|
*/
|
|
4557
|
-
async revokeOtherSession(userId, sessionHash) {
|
|
4558
|
-
await this.revokeSession(
|
|
4559
|
-
|
|
4786
|
+
async revokeOtherSession({ userId, tenantId, sessionHash }) {
|
|
4787
|
+
await this.revokeSession({
|
|
4788
|
+
userId,
|
|
4789
|
+
tenantId,
|
|
4790
|
+
sessionHash
|
|
4791
|
+
});
|
|
4792
|
+
await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
|
|
4560
4793
|
}
|
|
4561
4794
|
/**
|
|
4562
4795
|
* Revokes all sessions for a user except the caller's current session.
|
|
@@ -4585,15 +4818,20 @@ exports.SessionService = class _SessionService {
|
|
|
4585
4818
|
* @throws {unknown} Propagates any error thrown by `revokeSession` — including
|
|
4586
4819
|
* {@link AuthException} with various codes, Redis errors, or other runtime errors.
|
|
4587
4820
|
*/
|
|
4588
|
-
async revokeAllExceptCurrent(userId, currentSessionHash) {
|
|
4589
|
-
this.
|
|
4590
|
-
|
|
4821
|
+
async revokeAllExceptCurrent({ userId, tenantId, currentSessionHash }) {
|
|
4822
|
+
this.assertTenant(tenantId);
|
|
4823
|
+
this.assertValidSessionHash(currentSessionHash, "currentSessionHash");
|
|
4824
|
+
const members = await this.redis.smembers(this.indexKey(userId, tenantId));
|
|
4591
4825
|
const rtMembers = members.filter((m) => m.startsWith("rt:"));
|
|
4592
4826
|
for (const member of rtMembers) {
|
|
4593
4827
|
const hash = member.slice(3);
|
|
4594
4828
|
if (timingSafeCompare(hash, currentSessionHash)) continue;
|
|
4595
4829
|
try {
|
|
4596
|
-
await this.revokeSession(
|
|
4830
|
+
await this.revokeSession({
|
|
4831
|
+
userId,
|
|
4832
|
+
tenantId,
|
|
4833
|
+
sessionHash: hash
|
|
4834
|
+
});
|
|
4597
4835
|
} catch (err) {
|
|
4598
4836
|
if (err instanceof AuthException) {
|
|
4599
4837
|
const body = err.getResponse();
|
|
@@ -4605,9 +4843,9 @@ exports.SessionService = class _SessionService {
|
|
|
4605
4843
|
const gracePointers = members.filter((m) => m.startsWith("rp:"));
|
|
4606
4844
|
for (const member of gracePointers) {
|
|
4607
4845
|
await this.redis.del(member);
|
|
4608
|
-
await this.redis.srem(
|
|
4846
|
+
await this.redis.srem(this.indexKey(userId, tenantId), member);
|
|
4609
4847
|
}
|
|
4610
|
-
await this.redis.bumpUserTokenEpoch(userId);
|
|
4848
|
+
await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
|
|
4611
4849
|
}
|
|
4612
4850
|
/**
|
|
4613
4851
|
* Rotates the session detail record from the old token hash to the new one.
|
|
@@ -4630,12 +4868,13 @@ exports.SessionService = class _SessionService {
|
|
|
4630
4868
|
* @param newHash - SHA-256 hex hash of the newly issued refresh token.
|
|
4631
4869
|
* @param ip - Client IP address from the current request.
|
|
4632
4870
|
* @param userAgent - Raw `User-Agent` header value from the current request.
|
|
4633
|
-
* @throws {@link AuthException} `
|
|
4634
|
-
*
|
|
4871
|
+
* @throws {@link AuthException} `VALIDATION` when either hash is not a valid 64-character
|
|
4872
|
+
* lowercase hex string. The `details` name which one — `oldHash` or `newHash` — because a
|
|
4873
|
+
* caller told only that "a hash" was malformed cannot act on it.
|
|
4635
4874
|
*/
|
|
4636
4875
|
async rotateSession(oldHash, newHash, ip, userAgent) {
|
|
4637
|
-
this.assertValidSessionHash(oldHash);
|
|
4638
|
-
this.assertValidSessionHash(newHash);
|
|
4876
|
+
this.assertValidSessionHash(oldHash, "oldHash");
|
|
4877
|
+
this.assertValidSessionHash(newHash, "newHash");
|
|
4639
4878
|
if (timingSafeCompare(oldHash, newHash)) {
|
|
4640
4879
|
return;
|
|
4641
4880
|
}
|
|
@@ -4680,19 +4919,48 @@ exports.SessionService = class _SessionService {
|
|
|
4680
4919
|
* attacker-controlled key names.
|
|
4681
4920
|
*
|
|
4682
4921
|
* @remarks
|
|
4683
|
-
* `SESSION_NOT_FOUND
|
|
4684
|
-
* callers
|
|
4685
|
-
*
|
|
4922
|
+
* **This used to answer `SESSION_NOT_FOUND`, and that was wrong.** The stated reason was to stop
|
|
4923
|
+
* callers enumerating valid hash formats — but the format is not a secret. It is 64 hex
|
|
4924
|
+
* characters, `SessionInfo.sessionHash` publishes it on every listed session, and the route's
|
|
4925
|
+
* own documentation describes it. Nothing is protected by hiding it, and the pairing had a real
|
|
4926
|
+
* cost: a consumer sending a malformed hash got the same answer as one sending a hash that had
|
|
4927
|
+
* already been revoked, so a UI bug read as a race between the session list and the click. That
|
|
4928
|
+
* is measured, not hypothetical — it cost a consumer session twenty minutes chasing a race that
|
|
4929
|
+
* cannot happen.
|
|
4930
|
+
*
|
|
4931
|
+
* A malformed hash is a caller error and now says so. A well-formed hash that names nothing
|
|
4932
|
+
* still answers `SESSION_NOT_FOUND`, which is where the no-enumeration argument does apply:
|
|
4933
|
+
* that one really would tell the caller whether a session exists.
|
|
4686
4934
|
*
|
|
4687
4935
|
* @param sessionHash - The session hash to validate.
|
|
4688
|
-
* @throws {@link AuthException} `
|
|
4936
|
+
* @throws {@link AuthException} `VALIDATION` when the value is not 64 lowercase hex characters.
|
|
4689
4937
|
*/
|
|
4690
|
-
assertValidSessionHash(sessionHash) {
|
|
4938
|
+
assertValidSessionHash(sessionHash, field = "sessionHash") {
|
|
4691
4939
|
if (!SESSION_HASH_RE.test(sessionHash)) {
|
|
4692
|
-
throw new AuthException(AUTH_ERROR_CODES.
|
|
4940
|
+
throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
|
|
4941
|
+
{
|
|
4942
|
+
field,
|
|
4943
|
+
message: `${field} must be 64 lowercase hexadecimal characters`
|
|
4944
|
+
}
|
|
4945
|
+
]);
|
|
4693
4946
|
}
|
|
4694
4947
|
}
|
|
4695
4948
|
/**
|
|
4949
|
+
* The Redis key of this user's session index.
|
|
4950
|
+
*
|
|
4951
|
+
* Derived rather than interpolated, and tenant-scoped: `IUserRepository.findById` takes a
|
|
4952
|
+
* tenant because ids may only be unique within one, so a bare-id index let a revoke aimed at
|
|
4953
|
+
* one tenant's user empty another's. The derivation lives in `user-keys.ts` because rust-auth
|
|
4954
|
+
* reads the same key from the same contract.
|
|
4955
|
+
*
|
|
4956
|
+
* @param userId - The account whose sessions the index tracks.
|
|
4957
|
+
* @param tenantId - The tenant that account belongs to.
|
|
4958
|
+
* @returns The un-namespaced index key.
|
|
4959
|
+
*/
|
|
4960
|
+
indexKey(userId, tenantId) {
|
|
4961
|
+
return sessionIndexKey("dashboard", userId, this.options.hmacKey, tenantId);
|
|
4962
|
+
}
|
|
4963
|
+
/**
|
|
4696
4964
|
* Enforces the concurrent session limit for a user by evicting the oldest
|
|
4697
4965
|
* sessions (FIFO) when the limit has been exceeded.
|
|
4698
4966
|
*
|
|
@@ -4709,15 +4977,16 @@ exports.SessionService = class _SessionService {
|
|
|
4709
4977
|
* risk is low for most `defaultMaxSessions` values (≥ 2).
|
|
4710
4978
|
*
|
|
4711
4979
|
* @param userId - Internal user ID whose session count is being checked.
|
|
4980
|
+
* @param tenantId - The tenant that user belongs to; part of the index key.
|
|
4712
4981
|
* @param newHash - SHA-256 hash of the newly issued refresh token (excluded from eviction).
|
|
4713
4982
|
* @param ip - Client IP address (forwarded to the `onSessionEvicted` hook context).
|
|
4714
4983
|
* @param userAgent - User-Agent string (forwarded to the `onSessionEvicted` hook context).
|
|
4715
4984
|
*/
|
|
4716
|
-
async enforceSessionLimit(userId, newHash, ip, userAgent) {
|
|
4717
|
-
await this.redis.pruneExpiredGraceMembers(
|
|
4718
|
-
const members = await this.redis.smembers(
|
|
4985
|
+
async enforceSessionLimit(userId, tenantId, newHash, ip, userAgent) {
|
|
4986
|
+
await this.redis.pruneExpiredGraceMembers(this.indexKey(userId, tenantId), "rp:");
|
|
4987
|
+
const members = await this.redis.smembers(this.indexKey(userId, tenantId));
|
|
4719
4988
|
const rtMembers = members.filter((m) => m.startsWith("rt:"));
|
|
4720
|
-
const limit = await this.resolveSessionLimit(userId);
|
|
4989
|
+
const limit = await this.resolveSessionLimit(userId, tenantId);
|
|
4721
4990
|
if (rtMembers.length <= limit) return;
|
|
4722
4991
|
const withTimestamps = await Promise.all(rtMembers.map(async (member) => {
|
|
4723
4992
|
const memberHash = member.slice(3);
|
|
@@ -4752,15 +5021,15 @@ exports.SessionService = class _SessionService {
|
|
|
4752
5021
|
for (const entry of toEvict) {
|
|
4753
5022
|
try {
|
|
4754
5023
|
await this.redis.del(`rt:${entry.memberHash}`);
|
|
4755
|
-
await this.redis.srem(
|
|
5024
|
+
await this.redis.srem(this.indexKey(userId, tenantId), entry.member);
|
|
4756
5025
|
await this.redis.del(`sd:${entry.memberHash}`);
|
|
4757
5026
|
} catch (err) {
|
|
4758
|
-
this.logger.error(`enforceSessionLimit: failed to evict session ${entry.memberHash} for user ${userId}
|
|
5027
|
+
this.logger.error(`enforceSessionLimit: failed to evict session ${entry.memberHash} for user ${logSafe(userId)}: ${describeChannelStatus(err)}`);
|
|
4759
5028
|
continue;
|
|
4760
5029
|
}
|
|
4761
5030
|
if (this.hooks?.onSessionEvicted) {
|
|
4762
5031
|
void Promise.resolve(this.hooks.onSessionEvicted(userId, entry.memberHash, context)).catch((err) => {
|
|
4763
|
-
this.logger.error(
|
|
5032
|
+
this.logger.error(`onSessionEvicted hook threw: ${describeChannelStatus(err)}`);
|
|
4764
5033
|
});
|
|
4765
5034
|
}
|
|
4766
5035
|
}
|
|
@@ -4782,24 +5051,28 @@ exports.SessionService = class _SessionService {
|
|
|
4782
5051
|
* *thrown* resolver was ever caught.
|
|
4783
5052
|
*
|
|
4784
5053
|
* @param userId - Internal user ID to resolve the limit for.
|
|
5054
|
+
* @param tenantId - Tenant that user belongs to; scopes the lookup behind the resolver.
|
|
4785
5055
|
* @returns Maximum allowed concurrent sessions for the given user.
|
|
4786
5056
|
*/
|
|
4787
|
-
async resolveSessionLimit(userId) {
|
|
5057
|
+
async resolveSessionLimit(userId, tenantId) {
|
|
4788
5058
|
const { maxSessionsResolver, defaultMaxSessions } = this.options.sessions;
|
|
4789
5059
|
if (!maxSessionsResolver) {
|
|
4790
5060
|
return defaultMaxSessions;
|
|
4791
5061
|
}
|
|
4792
5062
|
try {
|
|
4793
|
-
const user = await this.userRepo.findById(
|
|
5063
|
+
const user = await this.userRepo.findById({
|
|
5064
|
+
id: userId,
|
|
5065
|
+
tenantId
|
|
5066
|
+
});
|
|
4794
5067
|
if (!user) return defaultMaxSessions;
|
|
4795
5068
|
const resolved = await maxSessionsResolver(user);
|
|
4796
5069
|
if (!Number.isInteger(resolved) || resolved < 1) {
|
|
4797
|
-
this.logger.error(`maxSessionsResolver returned ${String(resolved)}, which is not a positive whole number of sessions \u2014 falling back to defaultMaxSessions. A cap that silently stops applying is worse than one that is merely wrong.`);
|
|
5070
|
+
this.logger.error(`maxSessionsResolver returned ${logSafe(String(resolved))}, which is not a positive whole number of sessions \u2014 falling back to defaultMaxSessions. A cap that silently stops applying is worse than one that is merely wrong.`);
|
|
4798
5071
|
return defaultMaxSessions;
|
|
4799
5072
|
}
|
|
4800
5073
|
return resolved;
|
|
4801
5074
|
} catch (err) {
|
|
4802
|
-
this.logger.error(
|
|
5075
|
+
this.logger.error(`maxSessionsResolver threw \u2014 falling back to defaultMaxSessions: ${describeChannelStatus(err)}`);
|
|
4803
5076
|
return defaultMaxSessions;
|
|
4804
5077
|
}
|
|
4805
5078
|
}
|
|
@@ -4820,25 +5093,19 @@ exports.SessionService = _ts_decorate16([
|
|
|
4820
5093
|
])
|
|
4821
5094
|
], exports.SessionService);
|
|
4822
5095
|
|
|
4823
|
-
// src/server/constants/mfa-subject.ts
|
|
4824
|
-
function mfaSubject(plane, userId, tenantId) {
|
|
4825
|
-
return plane === "platform" ? `platform:${userId}` : `dashboard:${tenantId}:${userId}`;
|
|
4826
|
-
}
|
|
4827
|
-
__name(mfaSubject, "mfaSubject");
|
|
4828
|
-
|
|
4829
5096
|
// src/server/constants/recent-auth.ts
|
|
4830
5097
|
var RECENT_AUTH_TTL_SECONDS = 300;
|
|
4831
5098
|
function recentAuthKey(plane, userId, hmacKey, tenantId) {
|
|
4832
|
-
return `ra:${hmacSha256(
|
|
5099
|
+
return `ra:${hmacSha256(userSubject(plane, userId, tenantId), hmacKey)}`;
|
|
4833
5100
|
}
|
|
4834
5101
|
__name(recentAuthKey, "recentAuthKey");
|
|
4835
5102
|
|
|
4836
|
-
// src/server/utils/
|
|
4837
|
-
var
|
|
4838
|
-
function
|
|
4839
|
-
return
|
|
5103
|
+
// src/server/utils/owner-fragment.ts
|
|
5104
|
+
var UNKNOWN_OWNER = "userId=<unknown: no live session remains in this family to name it>";
|
|
5105
|
+
function ownerFragment(ownerId) {
|
|
5106
|
+
return ownerId === "" ? UNKNOWN_OWNER : `userId=${logSafe(ownerId)}`;
|
|
4840
5107
|
}
|
|
4841
|
-
__name(
|
|
5108
|
+
__name(ownerFragment, "ownerFragment");
|
|
4842
5109
|
|
|
4843
5110
|
// src/server/services/token-manager.service.ts
|
|
4844
5111
|
function _ts_decorate17(decorators, target, key, desc) {
|
|
@@ -4971,7 +5238,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
4971
5238
|
* @returns Full auth result containing access token, raw refresh token, and user.
|
|
4972
5239
|
*/
|
|
4973
5240
|
async issueTokens(user, ip, userAgent, overrides) {
|
|
4974
|
-
const epoch = await this.redis.getUserTokenEpoch(user.id);
|
|
5241
|
+
const epoch = await this.redis.getUserTokenEpoch(user.id, user.tenantId, "dashboard");
|
|
4975
5242
|
const accessToken = this.issueAccess({
|
|
4976
5243
|
sub: user.id,
|
|
4977
5244
|
tenantId: user.tenantId,
|
|
@@ -4989,6 +5256,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
4989
5256
|
const ttl = this.options.jwt.refreshExpiresInDays * 86400;
|
|
4990
5257
|
await this.redis.writeNewSession({
|
|
4991
5258
|
kind: "dashboard",
|
|
5259
|
+
tenantId: user.tenantId,
|
|
4992
5260
|
tokenHash,
|
|
4993
5261
|
sessionJson: this.serializeSession(session),
|
|
4994
5262
|
familyId,
|
|
@@ -5018,7 +5286,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5018
5286
|
* @returns Platform auth result.
|
|
5019
5287
|
*/
|
|
5020
5288
|
async issuePlatformTokens(admin, ip, userAgent, overrides) {
|
|
5021
|
-
const epoch = await this.redis.getUserTokenEpoch(admin.id, "platform");
|
|
5289
|
+
const epoch = await this.redis.getUserTokenEpoch(admin.id, void 0, "platform");
|
|
5022
5290
|
const accessToken = this.issuePlatformAccess({
|
|
5023
5291
|
sub: admin.id,
|
|
5024
5292
|
role: admin.role,
|
|
@@ -5034,6 +5302,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5034
5302
|
const ttl = this.options.jwt.refreshExpiresInDays * 86400;
|
|
5035
5303
|
await this.redis.writeNewSession({
|
|
5036
5304
|
kind: "platform",
|
|
5305
|
+
tenantId: void 0,
|
|
5037
5306
|
tokenHash,
|
|
5038
5307
|
sessionJson: this.serializeSession(session),
|
|
5039
5308
|
familyId,
|
|
@@ -5112,9 +5381,11 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5112
5381
|
const graceTtl = this.options.jwt.refreshGraceWindowSeconds;
|
|
5113
5382
|
const seed = await this.readSeedSession(`rt:${oldHash}`, ip, userAgent);
|
|
5114
5383
|
this.assertWithinAbsoluteLifetime(seed);
|
|
5384
|
+
this.assertRotatableTenant(seed);
|
|
5115
5385
|
const newSession = this.buildSession(seed.userId, seed.tenantId, seed.role, ip, userAgent, seed.mfaEnabled, seed.familyId, seed.familyCreatedAt);
|
|
5116
5386
|
const outcome = await this.redis.rotateRefreshSession({
|
|
5117
5387
|
kind: "dashboard",
|
|
5388
|
+
tenantId: seed.tenantId,
|
|
5118
5389
|
oldHash,
|
|
5119
5390
|
newHash,
|
|
5120
5391
|
newSessionJson: this.serializeSession(newSession),
|
|
@@ -5132,8 +5403,8 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5132
5403
|
if (outcome.kind === "reused") {
|
|
5133
5404
|
this.logger.warn(`reissueTokens: reuse of a consumed refresh token detected \u2014 revoking the token family familyId=${logSafe(outcome.familyId)}`);
|
|
5134
5405
|
const { ownerId } = await this.redis.revokeFamily(outcome.familyId);
|
|
5135
|
-
this.logger.warn(`reissueTokens: token family revoked after reuse detection
|
|
5136
|
-
this.emitReuseDetected(ownerId, outcome.familyId);
|
|
5406
|
+
this.logger.warn(`reissueTokens: token family revoked after reuse detection ${ownerFragment(ownerId)} familyId=${logSafe(outcome.familyId)}`);
|
|
5407
|
+
this.emitReuseDetected(ownerId, outcome.familyId, ip, userAgent);
|
|
5137
5408
|
throw new AuthException(AUTH_ERROR_CODES.REFRESH_TOKEN_INVALID);
|
|
5138
5409
|
}
|
|
5139
5410
|
this.logger.warn("reissueTokens: no valid session or grace window found \u2014 REFRESH_TOKEN_INVALID");
|
|
@@ -5145,18 +5416,64 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5145
5416
|
* The owner is read from the stored session where it can be — a replay of a token whose live
|
|
5146
5417
|
* key is already gone leaves nothing to read, and the hook is skipped rather than fired with
|
|
5147
5418
|
* an empty identity that a consumer would have to guess about.
|
|
5419
|
+
*
|
|
5420
|
+
* **The context describes WHO PRESENTED the replayed token**, which is the whole reason a
|
|
5421
|
+
* consumer subscribes to this hook. `userId` says whose account the family belongs to; `ip` and
|
|
5422
|
+
* `userAgent` are the only description of the party holding the token that should not exist, so
|
|
5423
|
+
* a report carrying the first and not the second says a compromise happened and gives nothing
|
|
5424
|
+
* to act on. Both were previously dropped: the emit built an EMPTY context while
|
|
5425
|
+
* `reissueTokens` had both values in scope as its own parameters.
|
|
5426
|
+
*
|
|
5427
|
+
* `sanitizedHeaders` stays empty and that is honest — the rotation path receives the address
|
|
5428
|
+
* and the agent, never the header map, so there is nothing to sanitize. Inventing one would be
|
|
5429
|
+
* worse than an empty object a consumer can see is empty.
|
|
5430
|
+
*
|
|
5431
|
+
* @param userId - The account the revoked family belonged to.
|
|
5432
|
+
* @param familyId - The revoked family.
|
|
5433
|
+
* @param ip - Address the replayed token was presented from.
|
|
5434
|
+
* @param userAgent - Raw `User-Agent` of the presenting client.
|
|
5148
5435
|
*/
|
|
5149
|
-
emitReuseDetected(userId, familyId) {
|
|
5436
|
+
emitReuseDetected(userId, familyId, ip, userAgent) {
|
|
5150
5437
|
if (!this.hooks?.onRefreshTokenReuseDetected || userId === "") return;
|
|
5151
5438
|
try {
|
|
5152
5439
|
void Promise.resolve(this.hooks.onRefreshTokenReuseDetected({
|
|
5153
5440
|
userId,
|
|
5154
5441
|
familyId
|
|
5155
|
-
},
|
|
5156
|
-
|
|
5442
|
+
}, {
|
|
5443
|
+
...createEmptyHookContext(),
|
|
5444
|
+
ip,
|
|
5445
|
+
userAgent
|
|
5446
|
+
})).catch((err) => {
|
|
5447
|
+
this.logger.error(`onRefreshTokenReuseDetected hook threw: ${describeChannelStatus(err)}`);
|
|
5157
5448
|
});
|
|
5158
5449
|
} catch (err) {
|
|
5159
|
-
this.logger.error(
|
|
5450
|
+
this.logger.error(`onRefreshTokenReuseDetected hook threw synchronously: ${describeChannelStatus(err)}`);
|
|
5451
|
+
}
|
|
5452
|
+
}
|
|
5453
|
+
/**
|
|
5454
|
+
* Refuses to rotate a dashboard session whose record names no tenant.
|
|
5455
|
+
*
|
|
5456
|
+
* `parseSession` validates `userId`, `role` and `mfaEnabled` but not `tenantId`, so a record
|
|
5457
|
+
* written before the index carried one reaches here with the field absent. Rotating it would do
|
|
5458
|
+
* two wrong things at once: write the new session under `dashboard:9:undefined:{userId}`, an
|
|
5459
|
+
* index belonging to no tenant and swept by no revoke-all, and mint an access token with no
|
|
5460
|
+
* tenant claim — which every dashboard guard then refuses, so the caller gets a session that
|
|
5461
|
+
* cannot be used and cannot be revoked.
|
|
5462
|
+
*
|
|
5463
|
+
* Refusing is the same answer the migration note gives: a pre-upgrade session dies and the user
|
|
5464
|
+
* signs in again. That is a cost; rotating into a keyspace nobody sweeps is a hole.
|
|
5465
|
+
*
|
|
5466
|
+
* The platform plane is exempt — its subject carries no tenant segment by design.
|
|
5467
|
+
*
|
|
5468
|
+
* @param session - The seed session read from the presented token.
|
|
5469
|
+
* @throws {@link AuthException} with `REFRESH_TOKEN_INVALID`, indistinguishable from any other
|
|
5470
|
+
* invalid refresh: the remedy is the same and the difference would only tell a token holder
|
|
5471
|
+
* how old the record is.
|
|
5472
|
+
*/
|
|
5473
|
+
assertRotatableTenant(session) {
|
|
5474
|
+
if (session.userId === "") return;
|
|
5475
|
+
if (session.tenantId === void 0 || session.tenantId === "") {
|
|
5476
|
+
throw new AuthException(AUTH_ERROR_CODES.REFRESH_TOKEN_INVALID);
|
|
5160
5477
|
}
|
|
5161
5478
|
}
|
|
5162
5479
|
/**
|
|
@@ -5240,11 +5557,13 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5240
5557
|
async rotateFromGrace(graceSessionJson, ip, userAgent, refreshTtl) {
|
|
5241
5558
|
const graceSession = this.parseSession(graceSessionJson);
|
|
5242
5559
|
this.assertWithinAbsoluteLifetime(graceSession);
|
|
5560
|
+
this.assertRotatableTenant(graceSession);
|
|
5243
5561
|
const anotherNewRefresh = generateSecureToken();
|
|
5244
5562
|
const anotherNewHash = sha256(anotherNewRefresh);
|
|
5245
5563
|
const anotherSession = this.buildSession(graceSession.userId, graceSession.tenantId, graceSession.role, ip, userAgent, graceSession.mfaEnabled, graceSession.familyId, graceSession.familyCreatedAt);
|
|
5246
5564
|
const written = await this.redis.writeRecoveredSession({
|
|
5247
5565
|
kind: "dashboard",
|
|
5566
|
+
tenantId: graceSession.tenantId,
|
|
5248
5567
|
newHash: anotherNewHash,
|
|
5249
5568
|
newSessionJson: this.serializeSession(anotherSession),
|
|
5250
5569
|
familyId: graceSession.familyId,
|
|
@@ -5361,7 +5680,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5361
5680
|
* of this behaviour and direct users through the MFA challenge flow to re-acquire it.
|
|
5362
5681
|
*/
|
|
5363
5682
|
async buildRotatedResult(session, rawRefreshToken) {
|
|
5364
|
-
const epoch = await this.redis.getUserTokenEpoch(session.userId);
|
|
5683
|
+
const epoch = await this.redis.getUserTokenEpoch(session.userId, session.tenantId, "dashboard");
|
|
5365
5684
|
const accessToken = this.issueAccess({
|
|
5366
5685
|
sub: session.userId,
|
|
5367
5686
|
tenantId: session.tenantId,
|
|
@@ -5407,6 +5726,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5407
5726
|
const newSession = this.buildSession(seed.userId, "", seed.role, ip, userAgent, seed.mfaEnabled, seed.familyId, seed.familyCreatedAt);
|
|
5408
5727
|
const outcome = await this.redis.rotateRefreshSession({
|
|
5409
5728
|
kind: "platform",
|
|
5729
|
+
tenantId: void 0,
|
|
5410
5730
|
oldHash,
|
|
5411
5731
|
newHash,
|
|
5412
5732
|
newSessionJson: this.serializeSession(newSession),
|
|
@@ -5424,8 +5744,8 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5424
5744
|
if (outcome.kind === "reused") {
|
|
5425
5745
|
this.logger.warn(`reissuePlatformTokens: reuse of a consumed refresh token detected \u2014 revoking the token family familyId=${logSafe(outcome.familyId)}`);
|
|
5426
5746
|
const { ownerId } = await this.redis.revokeFamily(outcome.familyId, "platform");
|
|
5427
|
-
this.logger.warn(`reissuePlatformTokens: token family revoked after reuse detection
|
|
5428
|
-
this.emitReuseDetected(ownerId, outcome.familyId);
|
|
5747
|
+
this.logger.warn(`reissuePlatformTokens: token family revoked after reuse detection ${ownerFragment(ownerId)} familyId=${logSafe(outcome.familyId)}`);
|
|
5748
|
+
this.emitReuseDetected(ownerId, outcome.familyId, ip, userAgent);
|
|
5429
5749
|
throw new AuthException(AUTH_ERROR_CODES.REFRESH_TOKEN_INVALID);
|
|
5430
5750
|
}
|
|
5431
5751
|
this.logger.warn("reissuePlatformTokens: no valid session or grace window found \u2014 REFRESH_TOKEN_INVALID");
|
|
@@ -5460,6 +5780,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5460
5780
|
const anotherSession = this.buildSession(graceSession.userId, "", graceSession.role, ip, userAgent, graceSession.mfaEnabled, graceSession.familyId, graceSession.familyCreatedAt);
|
|
5461
5781
|
const written = await this.redis.writeRecoveredSession({
|
|
5462
5782
|
kind: "platform",
|
|
5783
|
+
tenantId: void 0,
|
|
5463
5784
|
newHash: anotherNewHash,
|
|
5464
5785
|
newSessionJson: this.serializeSession(anotherSession),
|
|
5465
5786
|
familyId: graceSession.familyId,
|
|
@@ -5469,7 +5790,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5469
5790
|
if (!written) {
|
|
5470
5791
|
throw new AuthException(AUTH_ERROR_CODES.REFRESH_TOKEN_INVALID);
|
|
5471
5792
|
}
|
|
5472
|
-
await this.redis.srem(
|
|
5793
|
+
await this.redis.srem(sessionIndexKey("platform", graceSession.userId, this.options.hmacKey, void 0), `prp:${oldHash}`);
|
|
5473
5794
|
await this.redis.del(`psd:${oldHash}`);
|
|
5474
5795
|
await this.writePlatformSessionDetail(anotherNewHash, ip, userAgent, refreshTtl);
|
|
5475
5796
|
return await this.buildPlatformRotatedResult(anotherSession, anotherNewRefresh);
|
|
@@ -5482,7 +5803,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5482
5803
|
* Platform admins must re-complete the MFA challenge flow to re-acquire a verified token.
|
|
5483
5804
|
*/
|
|
5484
5805
|
async buildPlatformRotatedResult(session, rawRefreshToken) {
|
|
5485
|
-
const epoch = await this.redis.getUserTokenEpoch(session.userId, "platform");
|
|
5806
|
+
const epoch = await this.redis.getUserTokenEpoch(session.userId, void 0, "platform");
|
|
5486
5807
|
const accessToken = this.issuePlatformAccess({
|
|
5487
5808
|
sub: session.userId,
|
|
5488
5809
|
role: session.role,
|
|
@@ -5529,7 +5850,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5529
5850
|
type: "platform",
|
|
5530
5851
|
mfaEnabled,
|
|
5531
5852
|
mfaVerified: claims.mfaVerified,
|
|
5532
|
-
epoch: await this.redis.getUserTokenEpoch(claims.sub, "platform")
|
|
5853
|
+
epoch: await this.redis.getUserTokenEpoch(claims.sub, void 0, "platform")
|
|
5533
5854
|
});
|
|
5534
5855
|
}
|
|
5535
5856
|
// ---------------------------------------------------------------------------
|
|
@@ -5604,7 +5925,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5604
5925
|
} : {},
|
|
5605
5926
|
// Stamped so the challenge token dies with the rest of the account's credentials. See
|
|
5606
5927
|
// the claim's own documentation for what it was surviving.
|
|
5607
|
-
epoch: await this.redis.getUserTokenEpoch(userId, context)
|
|
5928
|
+
epoch: await this.redis.getUserTokenEpoch(userId, tenantId, context)
|
|
5608
5929
|
};
|
|
5609
5930
|
const token = this.jwtService.sign(payload, {
|
|
5610
5931
|
expiresIn: `${MFA_TEMP_TOKEN_TTL_SECONDS}s`,
|
|
@@ -5656,7 +5977,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5656
5977
|
} catch {
|
|
5657
5978
|
throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
|
|
5658
5979
|
}
|
|
5659
|
-
if (payload.context === "dashboard" && payload.tenantId ===
|
|
5980
|
+
if (payload.context === "dashboard" && (payload.tenantId ?? "") === "" || payload.context === "platform" && payload.tenantId !== void 0) {
|
|
5660
5981
|
throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
|
|
5661
5982
|
}
|
|
5662
5983
|
const storedUserId = await this.redis.get(`mfa:${sha256(payload.jti)}`);
|
|
@@ -5666,7 +5987,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5666
5987
|
if (storedUserId !== payload.sub) {
|
|
5667
5988
|
throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
|
|
5668
5989
|
}
|
|
5669
|
-
if (readStampedEpoch(payload) < await this.redis.getUserTokenEpoch(payload.sub, payload.context)) {
|
|
5990
|
+
if (readStampedEpoch(payload) < await this.redis.getUserTokenEpoch(payload.sub, payload.tenantId, payload.context)) {
|
|
5670
5991
|
throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
|
|
5671
5992
|
}
|
|
5672
5993
|
return {
|
|
@@ -5716,7 +6037,7 @@ TokenManagerService = _ts_decorate17([
|
|
|
5716
6037
|
function maskEmail(email) {
|
|
5717
6038
|
const atIndex = email.indexOf("@");
|
|
5718
6039
|
if (atIndex <= 0) return "***";
|
|
5719
|
-
return email[0] + "***@" + email.slice(atIndex + 1);
|
|
6040
|
+
return logSafe(email[0] + "***@" + email.slice(atIndex + 1));
|
|
5720
6041
|
}
|
|
5721
6042
|
__name(maskEmail, "maskEmail");
|
|
5722
6043
|
|
|
@@ -5751,6 +6072,19 @@ async function resolveTenantId(dtoTenantId, req, resolver) {
|
|
|
5751
6072
|
}
|
|
5752
6073
|
__name(resolveTenantId, "resolveTenantId");
|
|
5753
6074
|
|
|
6075
|
+
// src/server/utils/safe-log-line.ts
|
|
6076
|
+
var WITHHELD = "delivery details withheld: the composed line matched a value that must not be logged";
|
|
6077
|
+
function survives(line, secret) {
|
|
6078
|
+
if (secret.length === 0) return false;
|
|
6079
|
+
return line.includes(secret) || line.replace(/\D/g, "").includes(secret);
|
|
6080
|
+
}
|
|
6081
|
+
__name(survives, "survives");
|
|
6082
|
+
function safeLogLine(line, secrets) {
|
|
6083
|
+
if (!secrets.some((secret) => survives(line, secret))) return line;
|
|
6084
|
+
return redactSecrets(WITHHELD, secrets);
|
|
6085
|
+
}
|
|
6086
|
+
__name(safeLogLine, "safeLogLine");
|
|
6087
|
+
|
|
5754
6088
|
// src/server/utils/tenant-scoped.ts
|
|
5755
6089
|
function tenantScoped(user, tenantId) {
|
|
5756
6090
|
if (user === null) return null;
|
|
@@ -5856,14 +6190,21 @@ exports.AuthService = class _AuthService {
|
|
|
5856
6190
|
async rehashPassword(userId, tenantId, plain, verifiedHash) {
|
|
5857
6191
|
try {
|
|
5858
6192
|
const upgraded = await this.passwordService.hash(plain);
|
|
5859
|
-
const current = await this.userRepo.findById(
|
|
6193
|
+
const current = await this.userRepo.findById({
|
|
6194
|
+
id: userId,
|
|
6195
|
+
tenantId
|
|
6196
|
+
});
|
|
5860
6197
|
if (current?.passwordHash !== verifiedHash) {
|
|
5861
|
-
this.logger.log(`rehash on verify skipped \u2014 the stored hash changed userId=${userId}`);
|
|
6198
|
+
this.logger.log(`rehash on verify skipped \u2014 the stored hash changed userId=${logSafe(userId)}`);
|
|
5862
6199
|
return;
|
|
5863
6200
|
}
|
|
5864
|
-
await this.userRepo.updatePassword(
|
|
6201
|
+
await this.userRepo.updatePassword({
|
|
6202
|
+
id: userId,
|
|
6203
|
+
tenantId,
|
|
6204
|
+
passwordHash: upgraded
|
|
6205
|
+
});
|
|
5865
6206
|
} catch (err) {
|
|
5866
|
-
this.logger.error(
|
|
6207
|
+
this.logger.error(`rehash on verify failed \u2014 the stored hash is unchanged: ${describeChannelStatus(err)}`);
|
|
5867
6208
|
}
|
|
5868
6209
|
}
|
|
5869
6210
|
// ---------------------------------------------------------------------------
|
|
@@ -5908,7 +6249,10 @@ exports.AuthService = class _AuthService {
|
|
|
5908
6249
|
hookOverrides = hookResult.modifiedData;
|
|
5909
6250
|
}
|
|
5910
6251
|
}
|
|
5911
|
-
const existing = await this.userRepo.findByEmail(
|
|
6252
|
+
const existing = await this.userRepo.findByEmail({
|
|
6253
|
+
email: dto.email,
|
|
6254
|
+
tenantId
|
|
6255
|
+
});
|
|
5912
6256
|
if (existing) {
|
|
5913
6257
|
await this.passwordService.compareDummy(dto.password);
|
|
5914
6258
|
throw new AuthException(AUTH_ERROR_CODES.EMAIL_ALREADY_EXISTS);
|
|
@@ -5938,12 +6282,18 @@ exports.AuthService = class _AuthService {
|
|
|
5938
6282
|
const safeUser = toSafeUser2(newUser);
|
|
5939
6283
|
const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
|
|
5940
6284
|
if (this.options.sessions.enabled) {
|
|
5941
|
-
await this.sessionService.createSession(
|
|
6285
|
+
await this.sessionService.createSession({
|
|
6286
|
+
userId: safeUser.id,
|
|
6287
|
+
tenantId: safeUser.tenantId,
|
|
6288
|
+
rawRefreshToken: result.rawRefreshToken,
|
|
6289
|
+
ip,
|
|
6290
|
+
userAgent
|
|
6291
|
+
});
|
|
5942
6292
|
}
|
|
5943
|
-
this.logger.log(`register: user registered userId=${newUser.id} tenantId=${logSafe(tenantId)}`);
|
|
6293
|
+
this.logger.log(`register: user registered userId=${logSafe(newUser.id)} tenantId=${logSafe(tenantId)}`);
|
|
5944
6294
|
if (this.hooks?.afterRegister) {
|
|
5945
6295
|
void Promise.resolve(this.hooks.afterRegister(safeUser, context)).catch((err) => {
|
|
5946
|
-
this.logger.error(
|
|
6296
|
+
this.logger.error(`afterRegister hook threw: ${describeChannelStatus(err)}`);
|
|
5947
6297
|
});
|
|
5948
6298
|
}
|
|
5949
6299
|
return result;
|
|
@@ -5995,7 +6345,10 @@ exports.AuthService = class _AuthService {
|
|
|
5995
6345
|
if (this.hooks?.beforeLogin) {
|
|
5996
6346
|
await this.hooks.beforeLogin(dto.email, tenantId, context);
|
|
5997
6347
|
}
|
|
5998
|
-
const user = await this.userRepo.findByEmail(
|
|
6348
|
+
const user = await this.userRepo.findByEmail({
|
|
6349
|
+
email: dto.email,
|
|
6350
|
+
tenantId
|
|
6351
|
+
});
|
|
5999
6352
|
const tenantMismatch = user !== null && user.tenantId !== tenantId;
|
|
6000
6353
|
if (tenantMismatch && !this.warnedTenantMismatch) {
|
|
6001
6354
|
this.warnedTenantMismatch = true;
|
|
@@ -6045,7 +6398,7 @@ exports.AuthService = class _AuthService {
|
|
|
6045
6398
|
}
|
|
6046
6399
|
if (user.mfaEnabled) {
|
|
6047
6400
|
const mfaTempToken = await this.tokenManager.issueMfaTempToken(user.id, "dashboard", user.tenantId);
|
|
6048
|
-
this.logger.log(`login: MFA challenge issued userId=${user.id} tenantId=${logSafe(tenantId)}`);
|
|
6401
|
+
this.logger.log(`login: MFA challenge issued userId=${logSafe(user.id)} tenantId=${logSafe(tenantId)}`);
|
|
6049
6402
|
return {
|
|
6050
6403
|
mfaRequired: true,
|
|
6051
6404
|
mfaTempToken
|
|
@@ -6054,15 +6407,26 @@ exports.AuthService = class _AuthService {
|
|
|
6054
6407
|
const safeUser = toSafeUser2(user);
|
|
6055
6408
|
const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
|
|
6056
6409
|
if (this.options.sessions.enabled) {
|
|
6057
|
-
await this.sessionService.createSession(
|
|
6410
|
+
await this.sessionService.createSession({
|
|
6411
|
+
userId: safeUser.id,
|
|
6412
|
+
tenantId: safeUser.tenantId,
|
|
6413
|
+
rawRefreshToken: result.rawRefreshToken,
|
|
6414
|
+
ip,
|
|
6415
|
+
userAgent
|
|
6416
|
+
});
|
|
6058
6417
|
}
|
|
6059
|
-
this.logger.log(`login: success userId=${safeUser.id} tenantId=${logSafe(tenantId)}`);
|
|
6060
|
-
void this.userRepo.updateLastLogin(
|
|
6061
|
-
|
|
6418
|
+
this.logger.log(`login: success userId=${logSafe(safeUser.id)} tenantId=${logSafe(tenantId)}`);
|
|
6419
|
+
void this.userRepo.updateLastLogin({
|
|
6420
|
+
id: user.id,
|
|
6421
|
+
tenantId
|
|
6422
|
+
}).catch((err) => {
|
|
6423
|
+
this.logger.error(`updateLastLogin failed: ${describeError(err, [
|
|
6424
|
+
user.id
|
|
6425
|
+
])}`);
|
|
6062
6426
|
});
|
|
6063
6427
|
if (this.hooks?.afterLogin) {
|
|
6064
6428
|
void Promise.resolve(this.hooks.afterLogin(safeUser, context)).catch((err) => {
|
|
6065
|
-
this.logger.error(
|
|
6429
|
+
this.logger.error(`afterLogin hook threw: ${describeChannelStatus(err)}`);
|
|
6066
6430
|
});
|
|
6067
6431
|
}
|
|
6068
6432
|
return result;
|
|
@@ -6094,8 +6458,8 @@ exports.AuthService = class _AuthService {
|
|
|
6094
6458
|
*/
|
|
6095
6459
|
async logout(accessToken, rawRefreshToken) {
|
|
6096
6460
|
const sessionHash = sha256(rawRefreshToken);
|
|
6097
|
-
const userId = await this.redis.readSessionOwner(`rt:${sessionHash}`);
|
|
6098
|
-
this.logger.log(`logout: userId=${userId || "(no live session)"}`);
|
|
6461
|
+
const { userId, tenantId } = await this.redis.readSessionOwner(`rt:${sessionHash}`);
|
|
6462
|
+
this.logger.log(`logout: userId=${logSafe(userId || "(no live session)")}`);
|
|
6099
6463
|
try {
|
|
6100
6464
|
const payload = this.tokenManager.verifyIgnoringExpiry(accessToken);
|
|
6101
6465
|
const now = Math.floor(Date.now() / 1e3);
|
|
@@ -6107,17 +6471,23 @@ exports.AuthService = class _AuthService {
|
|
|
6107
6471
|
}
|
|
6108
6472
|
await this.redis.del(`rt:${sessionHash}`);
|
|
6109
6473
|
await this.redis.del(`rp:${sessionHash}`);
|
|
6110
|
-
if (this.options.sessions.enabled && userId) {
|
|
6111
|
-
await this.sessionService.revokeSession(
|
|
6474
|
+
if (this.options.sessions.enabled && userId && tenantId !== void 0) {
|
|
6475
|
+
await this.sessionService.revokeSession({
|
|
6476
|
+
userId,
|
|
6477
|
+
tenantId,
|
|
6478
|
+
sessionHash
|
|
6479
|
+
}).catch((err) => {
|
|
6112
6480
|
const errCode = err instanceof AuthException ? err.getResponse().error.code : void 0;
|
|
6113
6481
|
if (errCode !== AUTH_ERROR_CODES.SESSION_NOT_FOUND) {
|
|
6114
|
-
this.logger.warn(`logout: session cleanup failed \u2014 ${
|
|
6482
|
+
this.logger.warn(`logout: session cleanup failed \u2014 ${describeChannelStatus(err)}`);
|
|
6115
6483
|
}
|
|
6116
6484
|
});
|
|
6117
6485
|
}
|
|
6118
6486
|
if (this.hooks?.afterLogout && userId) {
|
|
6119
6487
|
void Promise.resolve(this.hooks.afterLogout(userId, createEmptyHookContext())).catch((err) => {
|
|
6120
|
-
this.logger.error(
|
|
6488
|
+
this.logger.error(`afterLogout hook threw: ${describeError(err, [
|
|
6489
|
+
userId
|
|
6490
|
+
])}`);
|
|
6121
6491
|
});
|
|
6122
6492
|
}
|
|
6123
6493
|
return userId;
|
|
@@ -6139,15 +6509,24 @@ exports.AuthService = class _AuthService {
|
|
|
6139
6509
|
*/
|
|
6140
6510
|
async refresh(oldRefreshToken, ip, userAgent) {
|
|
6141
6511
|
const result = await this.tokenManager.reissueTokens(oldRefreshToken, ip, userAgent);
|
|
6142
|
-
const user = await this.userRepo.findById(
|
|
6512
|
+
const user = await this.userRepo.findById({
|
|
6513
|
+
id: result.session.userId,
|
|
6514
|
+
tenantId: result.session.tenantId
|
|
6515
|
+
});
|
|
6143
6516
|
if (!user) {
|
|
6144
|
-
await this.revokeAllSessions(
|
|
6517
|
+
await this.revokeAllSessions({
|
|
6518
|
+
userId: result.session.userId,
|
|
6519
|
+
tenantId: result.session.tenantId
|
|
6520
|
+
});
|
|
6145
6521
|
throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
|
|
6146
6522
|
}
|
|
6147
6523
|
try {
|
|
6148
6524
|
this.assertUserNotBlocked(user);
|
|
6149
6525
|
} catch (err) {
|
|
6150
|
-
await this.revokeAllSessions(
|
|
6526
|
+
await this.revokeAllSessions({
|
|
6527
|
+
userId: result.session.userId,
|
|
6528
|
+
tenantId: result.session.tenantId
|
|
6529
|
+
});
|
|
6151
6530
|
throw err;
|
|
6152
6531
|
}
|
|
6153
6532
|
if (this.options.emailVerification.required && !user.emailVerified) {
|
|
@@ -6167,12 +6546,12 @@ exports.AuthService = class _AuthService {
|
|
|
6167
6546
|
// cleared on this session stays cleared, and re-stamping the authority must not
|
|
6168
6547
|
// silently demand it again.
|
|
6169
6548
|
mfaVerified: rotated.mfaVerified,
|
|
6170
|
-
epoch: await this.redis.getUserTokenEpoch(user.id)
|
|
6549
|
+
epoch: await this.redis.getUserTokenEpoch(user.id, user.tenantId, "dashboard")
|
|
6171
6550
|
});
|
|
6172
6551
|
}
|
|
6173
6552
|
if (this.options.sessions.enabled) {
|
|
6174
6553
|
void this.sessionService.rotateSession(sha256(oldRefreshToken), sha256(result.rawRefreshToken), ip, userAgent).catch((err) => {
|
|
6175
|
-
this.logger.warn(`refresh: session detail rotation failed \u2014 ${
|
|
6554
|
+
this.logger.warn(`refresh: session detail rotation failed \u2014 ${describeChannelStatus(err)}`);
|
|
6176
6555
|
});
|
|
6177
6556
|
}
|
|
6178
6557
|
return {
|
|
@@ -6201,11 +6580,21 @@ exports.AuthService = class _AuthService {
|
|
|
6201
6580
|
* The epoch is bumped after the sweep, not before: a failure in the sweep then leaves the
|
|
6202
6581
|
* operation visibly incomplete rather than reading as done while the sessions live on.
|
|
6203
6582
|
*
|
|
6204
|
-
* @param
|
|
6583
|
+
* @param params - See {@link RevokeAllSessionsParams}. Both keyspaces are scoped to the tenant,
|
|
6584
|
+
* so naming the wrong one revokes the colliding id in another tenant instead.
|
|
6585
|
+
* @throws {@link AuthException} `VALIDATION` when the tenant is blank.
|
|
6205
6586
|
*/
|
|
6206
|
-
async revokeAllSessions(userId) {
|
|
6207
|
-
|
|
6208
|
-
|
|
6587
|
+
async revokeAllSessions({ userId, tenantId }) {
|
|
6588
|
+
if (tenantId === "") {
|
|
6589
|
+
throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
|
|
6590
|
+
{
|
|
6591
|
+
field: "tenantId",
|
|
6592
|
+
message: "tenantId is required to revoke a user's sessions"
|
|
6593
|
+
}
|
|
6594
|
+
]);
|
|
6595
|
+
}
|
|
6596
|
+
await this.redis.invalidateUserSessions(userId, tenantId, "dashboard");
|
|
6597
|
+
await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
|
|
6209
6598
|
}
|
|
6210
6599
|
// ---------------------------------------------------------------------------
|
|
6211
6600
|
// GetMe
|
|
@@ -6214,11 +6603,16 @@ exports.AuthService = class _AuthService {
|
|
|
6214
6603
|
* Retrieves the full safe user record for the currently authenticated user.
|
|
6215
6604
|
*
|
|
6216
6605
|
* @param userId - Subject claim from the verified JWT.
|
|
6606
|
+
* @param tenantId - Tenant claim from the same token; scopes the lookup, because a repository
|
|
6607
|
+
* id is unique only within a tenant.
|
|
6217
6608
|
* @returns Safe user object (credential fields excluded).
|
|
6218
6609
|
* @throws {@link AuthException} with `TOKEN_INVALID` if the user no longer exists.
|
|
6219
6610
|
*/
|
|
6220
|
-
async getMe(userId) {
|
|
6221
|
-
const user = await this.userRepo.findById(
|
|
6611
|
+
async getMe(userId, tenantId) {
|
|
6612
|
+
const user = await this.userRepo.findById({
|
|
6613
|
+
id: userId,
|
|
6614
|
+
tenantId
|
|
6615
|
+
});
|
|
6222
6616
|
if (!user) {
|
|
6223
6617
|
throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
|
|
6224
6618
|
}
|
|
@@ -6271,8 +6665,11 @@ exports.AuthService = class _AuthService {
|
|
|
6271
6665
|
* @throws `MFA_REQUIRED` when the target user has MFA enabled — the
|
|
6272
6666
|
* consumer must route through the MFA challenge flow for that user.
|
|
6273
6667
|
*/
|
|
6274
|
-
async issueTokensForUserId(userId, ip, userAgent) {
|
|
6275
|
-
const user = await this.userRepo.findById(
|
|
6668
|
+
async issueTokensForUserId(userId, tenantId, ip, userAgent) {
|
|
6669
|
+
const user = await this.userRepo.findById({
|
|
6670
|
+
id: userId,
|
|
6671
|
+
tenantId
|
|
6672
|
+
});
|
|
6276
6673
|
if (!user) {
|
|
6277
6674
|
throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
|
|
6278
6675
|
}
|
|
@@ -6286,11 +6683,22 @@ exports.AuthService = class _AuthService {
|
|
|
6286
6683
|
const safeUser = toSafeUser2(user);
|
|
6287
6684
|
const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
|
|
6288
6685
|
if (this.options.sessions.enabled) {
|
|
6289
|
-
await this.sessionService.createSession(
|
|
6686
|
+
await this.sessionService.createSession({
|
|
6687
|
+
userId: safeUser.id,
|
|
6688
|
+
tenantId: safeUser.tenantId,
|
|
6689
|
+
rawRefreshToken: result.rawRefreshToken,
|
|
6690
|
+
ip,
|
|
6691
|
+
userAgent
|
|
6692
|
+
});
|
|
6290
6693
|
}
|
|
6291
|
-
this.logger.log(`issueTokensForUserId: success userId=${safeUser.id} tenantId=${logSafe(safeUser.tenantId)}`);
|
|
6292
|
-
void this.userRepo.updateLastLogin(
|
|
6293
|
-
|
|
6694
|
+
this.logger.log(`issueTokensForUserId: success userId=${logSafe(safeUser.id)} tenantId=${logSafe(safeUser.tenantId)}`);
|
|
6695
|
+
void this.userRepo.updateLastLogin({
|
|
6696
|
+
id: user.id,
|
|
6697
|
+
tenantId: safeUser.tenantId
|
|
6698
|
+
}).catch((err) => {
|
|
6699
|
+
this.logger.error(`updateLastLogin failed: ${describeError(err, [
|
|
6700
|
+
user.id
|
|
6701
|
+
])}`);
|
|
6294
6702
|
});
|
|
6295
6703
|
if (this.hooks?.afterLogin) {
|
|
6296
6704
|
void Promise.resolve(this.hooks.afterLogin(safeUser, {
|
|
@@ -6299,7 +6707,7 @@ exports.AuthService = class _AuthService {
|
|
|
6299
6707
|
userAgent,
|
|
6300
6708
|
sanitizedHeaders: {}
|
|
6301
6709
|
})).catch((err) => {
|
|
6302
|
-
this.logger.error(
|
|
6710
|
+
this.logger.error(`afterLogin hook threw: ${describeChannelStatus(err)}`);
|
|
6303
6711
|
});
|
|
6304
6712
|
}
|
|
6305
6713
|
return result;
|
|
@@ -6327,16 +6735,23 @@ exports.AuthService = class _AuthService {
|
|
|
6327
6735
|
tenantId = await this.resolveTenantId(tenantId, req);
|
|
6328
6736
|
email = normalizeEmail(email);
|
|
6329
6737
|
await this.otpService.verify("email_verification", this.otpIdentifier(tenantId, email), otp);
|
|
6330
|
-
const user = tenantScoped(await this.userRepo.findByEmail(
|
|
6738
|
+
const user = tenantScoped(await this.userRepo.findByEmail({
|
|
6739
|
+
email,
|
|
6740
|
+
tenantId
|
|
6741
|
+
}), tenantId);
|
|
6331
6742
|
if (!user) {
|
|
6332
6743
|
throw new AuthException(AUTH_ERROR_CODES.OTP_INVALID);
|
|
6333
6744
|
}
|
|
6334
|
-
await this.userRepo.updateEmailVerified(
|
|
6745
|
+
await this.userRepo.updateEmailVerified({
|
|
6746
|
+
id: user.id,
|
|
6747
|
+
tenantId,
|
|
6748
|
+
verified: true
|
|
6749
|
+
});
|
|
6335
6750
|
await this.redis.del(`uev:${encodeURIComponent(tenantId)}:${encodeURIComponent(user.id)}`);
|
|
6336
|
-
this.logger.log(`verifyEmail: email verified userId=${user.id} tenantId=${logSafe(tenantId)}`);
|
|
6751
|
+
this.logger.log(`verifyEmail: email verified userId=${logSafe(user.id)} tenantId=${logSafe(tenantId)}`);
|
|
6337
6752
|
if (this.hooks?.afterEmailVerified) {
|
|
6338
6753
|
void Promise.resolve(this.hooks.afterEmailVerified(toSafeUser2(user), createEmptyHookContext())).catch((err) => {
|
|
6339
|
-
this.logger.error(
|
|
6754
|
+
this.logger.error(`afterEmailVerified hook threw: ${describeChannelStatus(err)}`);
|
|
6340
6755
|
});
|
|
6341
6756
|
}
|
|
6342
6757
|
}
|
|
@@ -6360,7 +6775,10 @@ exports.AuthService = class _AuthService {
|
|
|
6360
6775
|
await sleep(Math.max(0, ANTI_ENUM_MIN_MS - (Date.now() - start)));
|
|
6361
6776
|
return;
|
|
6362
6777
|
}
|
|
6363
|
-
const user = tenantScoped(await this.userRepo.findByEmail(
|
|
6778
|
+
const user = tenantScoped(await this.userRepo.findByEmail({
|
|
6779
|
+
email,
|
|
6780
|
+
tenantId
|
|
6781
|
+
}), tenantId);
|
|
6364
6782
|
if (user && !user.emailVerified) {
|
|
6365
6783
|
await this.sendVerificationOtp(tenantId, email, user.id);
|
|
6366
6784
|
}
|
|
@@ -6396,6 +6814,67 @@ exports.AuthService = class _AuthService {
|
|
|
6396
6814
|
await this.bruteForce.resetFailures(identifier);
|
|
6397
6815
|
this.logger.log(`unlockAccount: lockout cleared email=${maskEmail(normalizeEmail(email))} tenantId=${logSafe(tenantId)}`);
|
|
6398
6816
|
}
|
|
6817
|
+
/**
|
|
6818
|
+
* Reports whether an account is currently locked out by brute-force protection.
|
|
6819
|
+
*
|
|
6820
|
+
* The counterpart to {@link unlockAccount}, and the reason it exists: the write side was
|
|
6821
|
+
* public while the read side was not, so a host could offer an Unlock control and could not
|
|
6822
|
+
* tell anyone whether it had anything to do.
|
|
6823
|
+
*
|
|
6824
|
+
* A consumer cannot derive this themselves even with the source in hand. The counter is keyed
|
|
6825
|
+
* by an HMAC of `dashboard:{tenantId}:{email}` under the library's own `hmacKey`, which is
|
|
6826
|
+
* derived rather than supplied — and reproducing the preimage is precisely what keeping the
|
|
6827
|
+
* derivation in one place prevents. A third copy in a consumer repository is a third chance to
|
|
6828
|
+
* drift, and the failure is silent: a key that never exists reads as "not locked out" for every
|
|
6829
|
+
* account, including locked ones. A false negative on a security indicator, reported
|
|
6830
|
+
* confidently.
|
|
6831
|
+
*
|
|
6832
|
+
* **Cheap enough to put on every row of a list, with one caveat that is the host's.** Issuing
|
|
6833
|
+
* these concurrently overlaps the waits, so twenty of them cost close to what one costs; issuing
|
|
6834
|
+
* them with `await` inside a loop serialises the round trips and cost sixteen times as much when
|
|
6835
|
+
* the reporter measured it against a local Redis. That ratio is a property of concurrency, not a
|
|
6836
|
+
* guarantee this library makes: each call is its own Redis command, the ioredis client is
|
|
6837
|
+
* supplied by the host, and whether those commands are also BATCHED into one write depends on
|
|
6838
|
+
* `enableAutoPipelining`, which ioredis leaves off by default. Use `Promise.all`; do not treat
|
|
6839
|
+
* any absolute number here as a contract.
|
|
6840
|
+
*
|
|
6841
|
+
* Like {@link unlockAccount}, this ships **no route**. Whether a caller may ask about an account
|
|
6842
|
+
* they do not own is a decision only the host can make, and a lockout flag reachable without
|
|
6843
|
+
* authorisation is an oracle about other people's accounts.
|
|
6844
|
+
*
|
|
6845
|
+
* @param email - The account's address. Normalized here exactly as login normalizes it, or the
|
|
6846
|
+
* derived key misses the counter the lockout actually wrote.
|
|
6847
|
+
* @param tenantId - The tenant the account belongs to.
|
|
6848
|
+
* @returns `true` while the account is locked out.
|
|
6849
|
+
*/
|
|
6850
|
+
async isAccountLockedOut(email, tenantId) {
|
|
6851
|
+
return await this.bruteForce.isLockedOut(this.lockoutIdentifier(tenantId, normalizeEmail(email)));
|
|
6852
|
+
}
|
|
6853
|
+
/**
|
|
6854
|
+
* Reports how many seconds remain on an account's lockout.
|
|
6855
|
+
*
|
|
6856
|
+
* Separate from {@link isAccountLockedOut} because a bare flag with no horizon is the interface
|
|
6857
|
+
* that invites the support call the indicator was meant to prevent: it says an account is
|
|
6858
|
+
* locked and cannot say for how long, so the only honest advice is "try again later".
|
|
6859
|
+
*
|
|
6860
|
+
* **Gated on the lockout, not merely on the key.** `BruteForceService.getRemainingLockoutSeconds`
|
|
6861
|
+
* returns the TTL of the failure counter, and `recordFailure` creates that counter on the FIRST
|
|
6862
|
+
* failure — so the raw TTL is positive from one failed attempt onward, long before the threshold
|
|
6863
|
+
* is reached. Returned unchecked it would tell a console "locked for 14 minutes" about an
|
|
6864
|
+
* account that is not locked and whose next attempt would succeed. The threshold is therefore
|
|
6865
|
+
* read first, which costs a second Redis command only on the accounts that are actually locked.
|
|
6866
|
+
*
|
|
6867
|
+
* Ships no route, for the reason given on {@link isAccountLockedOut}.
|
|
6868
|
+
*
|
|
6869
|
+
* @param email - The account's address, normalized here as login normalizes it.
|
|
6870
|
+
* @param tenantId - The tenant the account belongs to.
|
|
6871
|
+
* @returns Seconds until the lockout expires, or `0` when the account is not locked out.
|
|
6872
|
+
*/
|
|
6873
|
+
async getAccountLockoutSeconds(email, tenantId) {
|
|
6874
|
+
const identifier = this.lockoutIdentifier(tenantId, normalizeEmail(email));
|
|
6875
|
+
if (!await this.bruteForce.isLockedOut(identifier)) return 0;
|
|
6876
|
+
return await this.bruteForce.getRemainingLockoutSeconds(identifier);
|
|
6877
|
+
}
|
|
6399
6878
|
// ---------------------------------------------------------------------------
|
|
6400
6879
|
// Private helpers
|
|
6401
6880
|
// ---------------------------------------------------------------------------
|
|
@@ -6495,10 +6974,10 @@ exports.AuthService = class _AuthService {
|
|
|
6495
6974
|
fireAndForget(run, name) {
|
|
6496
6975
|
try {
|
|
6497
6976
|
void Promise.resolve(run()).catch((err) => {
|
|
6498
|
-
this.logger.error(`${name} hook threw
|
|
6977
|
+
this.logger.error(`${name} hook threw: ${describeChannelStatus(err)}`);
|
|
6499
6978
|
});
|
|
6500
6979
|
} catch (err) {
|
|
6501
|
-
this.logger.error(`${name} hook threw synchronously
|
|
6980
|
+
this.logger.error(`${name} hook threw synchronously: ${describeChannelStatus(err)}`);
|
|
6502
6981
|
}
|
|
6503
6982
|
}
|
|
6504
6983
|
assertUserNotBlocked(user) {
|
|
@@ -6514,9 +6993,18 @@ exports.AuthService = class _AuthService {
|
|
|
6514
6993
|
const ttl = this.options.emailVerification.otpTtlSeconds;
|
|
6515
6994
|
const otp = this.otpService.generate(length);
|
|
6516
6995
|
await this.otpService.store("email_verification", identifier, otp, ttl);
|
|
6517
|
-
|
|
6518
|
-
|
|
6519
|
-
|
|
6996
|
+
const provider = this.emailProvider;
|
|
6997
|
+
void (async () => {
|
|
6998
|
+
try {
|
|
6999
|
+
await provider.sendEmailVerificationOtp(tenantId, email, otp);
|
|
7000
|
+
} catch (err) {
|
|
7001
|
+
const withheld = [
|
|
7002
|
+
otp,
|
|
7003
|
+
email
|
|
7004
|
+
];
|
|
7005
|
+
this.logger.error(safeLogLine(`sendEmailVerificationOtp failed for user ${logSafe(redactSecrets(userId, withheld))}: ` + describeChannelStatus(err), withheld));
|
|
7006
|
+
}
|
|
7007
|
+
})();
|
|
6520
7008
|
}
|
|
6521
7009
|
};
|
|
6522
7010
|
exports.AuthService = _ts_decorate18([
|
|
@@ -6612,10 +7100,13 @@ exports.WsTicketService = class _WsTicketService {
|
|
|
6612
7100
|
throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
|
|
6613
7101
|
}
|
|
6614
7102
|
if (payload.mfaEnabled && payload.mfaVerified !== true) {
|
|
6615
|
-
this.logger.warn(`ws-ticket: refused, MFA not satisfied userId=${payload.sub}`);
|
|
7103
|
+
this.logger.warn(`ws-ticket: refused, MFA not satisfied userId=${logSafe(payload.sub)}`);
|
|
6616
7104
|
throw new AuthException(AUTH_ERROR_CODES.MFA_REQUIRED);
|
|
6617
7105
|
}
|
|
6618
|
-
const user = await this.userRepo.findById(
|
|
7106
|
+
const user = await this.userRepo.findById({
|
|
7107
|
+
id: payload.sub,
|
|
7108
|
+
tenantId: payload.tenantId
|
|
7109
|
+
});
|
|
6619
7110
|
if (!user) throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
|
|
6620
7111
|
assertNotBlocked(user.status, this.options.blockedStatuses);
|
|
6621
7112
|
const snapshot = {
|
|
@@ -6627,7 +7118,7 @@ exports.WsTicketService = class _WsTicketService {
|
|
|
6627
7118
|
mfaVerified: payload.mfaVerified
|
|
6628
7119
|
};
|
|
6629
7120
|
const ticket = await this.redis.mintWsTicket(snapshot, WS_TICKET_TTL_SECONDS);
|
|
6630
|
-
this.logger.log(`ws-ticket: issued userId=${payload.sub} tenantId=${payload.tenantId}`);
|
|
7121
|
+
this.logger.log(`ws-ticket: issued userId=${logSafe(payload.sub)} tenantId=${logSafe(payload.tenantId)}`);
|
|
6631
7122
|
return {
|
|
6632
7123
|
ticket,
|
|
6633
7124
|
expiresIn: WS_TICKET_TTL_SECONDS
|
|
@@ -6791,10 +7282,11 @@ var AuthController = class {
|
|
|
6791
7282
|
* and so refuses an unverified or blocked account. The account's own `status` and
|
|
6792
7283
|
* `emailVerified` fields are in the returned record for the client to branch on.
|
|
6793
7284
|
*
|
|
6794
|
-
* @param user - JWT payload from the verified access token.
|
|
7285
|
+
* @param user - JWT payload from the verified access token. Both the subject and the tenant
|
|
7286
|
+
* are read from it: an account is named by the pair, never by the id alone.
|
|
6795
7287
|
*/
|
|
6796
7288
|
async me(user) {
|
|
6797
|
-
return this.authService.getMe(user.sub);
|
|
7289
|
+
return this.authService.getMe(user.sub, user.tenantId);
|
|
6798
7290
|
}
|
|
6799
7291
|
/**
|
|
6800
7292
|
* Mints a single-use ticket for authenticating a WebSocket upgrade.
|
|
@@ -7147,6 +7639,8 @@ exports.EmailChangeService = class _EmailChangeService {
|
|
|
7147
7639
|
* new address. Nothing about the account changes until that token comes back.
|
|
7148
7640
|
*
|
|
7149
7641
|
* @param userId - The authenticated caller, from their own claims — never the body.
|
|
7642
|
+
* @param tenantId - The tenant that caller belongs to, from the same claims; scopes the
|
|
7643
|
+
* account read, because a repository id is unique only within a tenant.
|
|
7150
7644
|
* @param dto - The new address and the current password.
|
|
7151
7645
|
* @throws {@link AuthException} `INVALID_CREDENTIALS` when the account has no local password
|
|
7152
7646
|
* or the submitted one is wrong — the same code a failed login returns, so a thief holding
|
|
@@ -7154,21 +7648,24 @@ exports.EmailChangeService = class _EmailChangeService {
|
|
|
7154
7648
|
* @throws {@link AuthException} `EMAIL_ALREADY_EXISTS` when the address is the account's own
|
|
7155
7649
|
* or belongs to another account in the tenant.
|
|
7156
7650
|
*/
|
|
7157
|
-
async requestChange(userId, dto) {
|
|
7651
|
+
async requestChange(userId, tenantId, dto) {
|
|
7158
7652
|
const newEmail = normalizeEmail(dto.newEmail);
|
|
7159
|
-
const user = await this.userRepo.findById(
|
|
7653
|
+
const user = await this.userRepo.findById({
|
|
7654
|
+
id: userId,
|
|
7655
|
+
tenantId
|
|
7656
|
+
});
|
|
7160
7657
|
if (!user?.passwordHash) {
|
|
7161
7658
|
throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
|
|
7162
7659
|
}
|
|
7163
|
-
const bfIdentifier = hmacSha256(`reauth:email-change:${userId}`, this.options.hmacKey);
|
|
7660
|
+
const bfIdentifier = hmacSha256(`reauth:email-change:${userSubject("dashboard", userId, tenantId)}`, this.options.hmacKey);
|
|
7164
7661
|
if (await this.bruteForce.isLockedOut(bfIdentifier)) {
|
|
7165
|
-
this.logger.warn(`requestChange: account locked userId=${userId}`);
|
|
7662
|
+
this.logger.warn(`requestChange: account locked userId=${logSafe(userId)}`);
|
|
7166
7663
|
throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
|
|
7167
7664
|
}
|
|
7168
7665
|
const matches = await this.passwordService.compare(dto.currentPassword, user.passwordHash);
|
|
7169
7666
|
if (!matches) {
|
|
7170
7667
|
await this.bruteForce.recordFailure(bfIdentifier);
|
|
7171
|
-
this.logger.warn(`requestChange: current password rejected userId=${userId}`);
|
|
7668
|
+
this.logger.warn(`requestChange: current password rejected userId=${logSafe(userId)}`);
|
|
7172
7669
|
throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
|
|
7173
7670
|
}
|
|
7174
7671
|
await this.bruteForce.resetFailures(bfIdentifier);
|
|
@@ -7184,8 +7681,12 @@ exports.EmailChangeService = class _EmailChangeService {
|
|
|
7184
7681
|
passwordFingerprint: sha256(user.passwordHash)
|
|
7185
7682
|
};
|
|
7186
7683
|
await this.redis.set(`ec:${sha256(rawToken)}`, JSON.stringify(context), this.options.emailChange.tokenTtlSeconds);
|
|
7187
|
-
|
|
7188
|
-
|
|
7684
|
+
try {
|
|
7685
|
+
await this.emailProvider.sendEmailChangeVerification?.(user.tenantId, newEmail, rawToken);
|
|
7686
|
+
} catch (err) {
|
|
7687
|
+
throw new Error(describeChannelStatus(err));
|
|
7688
|
+
}
|
|
7689
|
+
this.logger.log(`requestChange: verification sent userId=${logSafe(userId)} newEmail=${maskEmail(newEmail)}`);
|
|
7189
7690
|
}
|
|
7190
7691
|
// ---------------------------------------------------------------------------
|
|
7191
7692
|
// confirmChange()
|
|
@@ -7208,7 +7709,10 @@ exports.EmailChangeService = class _EmailChangeService {
|
|
|
7208
7709
|
if (context === null) {
|
|
7209
7710
|
throw new AuthException(AUTH_ERROR_CODES.EMAIL_CHANGE_TOKEN_INVALID);
|
|
7210
7711
|
}
|
|
7211
|
-
const user = await this.userRepo.findById(
|
|
7712
|
+
const user = await this.userRepo.findById({
|
|
7713
|
+
id: context.userId,
|
|
7714
|
+
tenantId: context.tenantId
|
|
7715
|
+
});
|
|
7212
7716
|
if (!user) {
|
|
7213
7717
|
throw new AuthException(AUTH_ERROR_CODES.EMAIL_CHANGE_TOKEN_INVALID);
|
|
7214
7718
|
}
|
|
@@ -7216,8 +7720,12 @@ exports.EmailChangeService = class _EmailChangeService {
|
|
|
7216
7720
|
assertNotBlocked(user.status, this.options.blockedStatuses);
|
|
7217
7721
|
await this.assertAddressIsFree(user, context.newEmail);
|
|
7218
7722
|
const oldEmail = user.email;
|
|
7219
|
-
await this.userRepo.updateEmail(
|
|
7220
|
-
|
|
7723
|
+
await this.userRepo.updateEmail({
|
|
7724
|
+
id: context.userId,
|
|
7725
|
+
tenantId: context.tenantId,
|
|
7726
|
+
email: context.newEmail
|
|
7727
|
+
});
|
|
7728
|
+
this.logger.log(`confirmChange: address changed userId=${logSafe(context.userId)} from=${maskEmail(oldEmail)} to=${maskEmail(context.newEmail)}`);
|
|
7221
7729
|
await this.notifyOldAddress(user.tenantId, oldEmail, context.newEmail);
|
|
7222
7730
|
}
|
|
7223
7731
|
// ---------------------------------------------------------------------------
|
|
@@ -7242,7 +7750,10 @@ exports.EmailChangeService = class _EmailChangeService {
|
|
|
7242
7750
|
if (normalizeEmail(user.email) === newEmail) {
|
|
7243
7751
|
throw new AuthException(AUTH_ERROR_CODES.EMAIL_ALREADY_EXISTS);
|
|
7244
7752
|
}
|
|
7245
|
-
const existing = await this.userRepo.findByEmail(
|
|
7753
|
+
const existing = await this.userRepo.findByEmail({
|
|
7754
|
+
email: newEmail,
|
|
7755
|
+
tenantId: user.tenantId
|
|
7756
|
+
});
|
|
7246
7757
|
if (existing) {
|
|
7247
7758
|
throw new AuthException(AUTH_ERROR_CODES.EMAIL_ALREADY_EXISTS);
|
|
7248
7759
|
}
|
|
@@ -7270,7 +7781,7 @@ exports.EmailChangeService = class _EmailChangeService {
|
|
|
7270
7781
|
if (stored === void 0 || stored === "") return;
|
|
7271
7782
|
const current = user.passwordHash === null ? null : sha256(user.passwordHash);
|
|
7272
7783
|
if (current === null || stored !== current) {
|
|
7273
|
-
this.logger.warn(`confirmChange: token no longer bound to the account password userId=${context.userId}`);
|
|
7784
|
+
this.logger.warn(`confirmChange: token no longer bound to the account password userId=${logSafe(context.userId)}`);
|
|
7274
7785
|
throw new AuthException(AUTH_ERROR_CODES.EMAIL_CHANGE_TOKEN_INVALID);
|
|
7275
7786
|
}
|
|
7276
7787
|
}
|
|
@@ -7303,7 +7814,7 @@ exports.EmailChangeService = class _EmailChangeService {
|
|
|
7303
7814
|
try {
|
|
7304
7815
|
await this.emailProvider.sendEmailChangedNotification(tenantId, oldEmail, newEmail);
|
|
7305
7816
|
} catch (err) {
|
|
7306
|
-
this.logger.error(
|
|
7817
|
+
this.logger.error(`confirmChange: notification to the previous address failed: ` + describeChannelStatus(err));
|
|
7307
7818
|
}
|
|
7308
7819
|
}
|
|
7309
7820
|
};
|
|
@@ -7382,7 +7893,7 @@ var EmailChangeController = class {
|
|
|
7382
7893
|
// carries it: a suspended account holding a live access token must not be able to move the
|
|
7383
7894
|
// credential its recovery depends on.
|
|
7384
7895
|
async requestChange(dto, user) {
|
|
7385
|
-
await this.emailChangeService.requestChange(user.sub, dto);
|
|
7896
|
+
await this.emailChangeService.requestChange(user.sub, user.tenantId, dto);
|
|
7386
7897
|
}
|
|
7387
7898
|
// ---------------------------------------------------------------------------
|
|
7388
7899
|
// POST /email/change/confirm
|
|
@@ -7490,8 +8001,9 @@ var AcceptInvitationDto = class {
|
|
|
7490
8001
|
*
|
|
7491
8002
|
* Maximum 128 characters as a practical
|
|
7492
8003
|
* input bound to prevent DoS via pathological scrypt inputs.
|
|
7493
|
-
* The service layer hashes this value immediately — it is never logged or
|
|
7494
|
-
*
|
|
8004
|
+
* The service layer hashes this value immediately — it is never logged or persisted in plaintext
|
|
8005
|
+
* BY THIS LIBRARY. A breach checker you supply receives it by contract, and an error it raises
|
|
8006
|
+
* is a place it can be; see `PasswordService.assertNotCompromised` for the ceiling.
|
|
7495
8007
|
*/
|
|
7496
8008
|
password;
|
|
7497
8009
|
};
|
|
@@ -7708,7 +8220,10 @@ exports.InvitationService = class _InvitationService {
|
|
|
7708
8220
|
if (!Object.hasOwn(hierarchy, role)) {
|
|
7709
8221
|
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
|
|
7710
8222
|
}
|
|
7711
|
-
const inviter = await this.userRepo.findById(
|
|
8223
|
+
const inviter = await this.userRepo.findById({
|
|
8224
|
+
id: inviterUserId,
|
|
8225
|
+
tenantId
|
|
8226
|
+
});
|
|
7712
8227
|
if (!inviter) {
|
|
7713
8228
|
throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
|
|
7714
8229
|
}
|
|
@@ -7736,13 +8251,17 @@ exports.InvitationService = class _InvitationService {
|
|
|
7736
8251
|
await this.redis.set(tokenKey, JSON.stringify(stored), ttl);
|
|
7737
8252
|
const displayTenantName = tenantName ?? tenantId;
|
|
7738
8253
|
const expiresAt = new Date(Date.now() + ttl * 1e3);
|
|
7739
|
-
|
|
7740
|
-
|
|
7741
|
-
|
|
7742
|
-
|
|
7743
|
-
|
|
7744
|
-
|
|
7745
|
-
|
|
8254
|
+
try {
|
|
8255
|
+
await this.emailProvider.sendInvitation(tenantId, normalizedEmail, {
|
|
8256
|
+
inviterName: inviter.name,
|
|
8257
|
+
tenantName: displayTenantName,
|
|
8258
|
+
inviteToken: rawToken,
|
|
8259
|
+
expiresAt
|
|
8260
|
+
});
|
|
8261
|
+
} catch (err) {
|
|
8262
|
+
throw new Error(describeChannelStatus(err));
|
|
8263
|
+
}
|
|
8264
|
+
this.logger.log(`invite: invitation created email=${maskEmail(normalizedEmail)} role=${logSafe(role)} tenantId=${logSafe(tenantId)} inviterUserId=${logSafe(inviterUserId)}`);
|
|
7746
8265
|
}
|
|
7747
8266
|
// ---------------------------------------------------------------------------
|
|
7748
8267
|
// acceptInvitation()
|
|
@@ -7942,7 +8461,10 @@ exports.InvitationService = class _InvitationService {
|
|
|
7942
8461
|
*/
|
|
7943
8462
|
async revokeInvitation(revokerUserId, email, tenantId) {
|
|
7944
8463
|
const normalizedEmail = normalizeEmail(email);
|
|
7945
|
-
const revoker = await this.userRepo.findById(
|
|
8464
|
+
const revoker = await this.userRepo.findById({
|
|
8465
|
+
id: revokerUserId,
|
|
8466
|
+
tenantId
|
|
8467
|
+
});
|
|
7946
8468
|
if (!revoker) {
|
|
7947
8469
|
throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
|
|
7948
8470
|
}
|
|
@@ -7958,12 +8480,12 @@ exports.InvitationService = class _InvitationService {
|
|
|
7958
8480
|
const raw = await this.redis.get(`inv:${tokenHash}`);
|
|
7959
8481
|
const invitation = raw === null ? null : this.parseInvitation(raw);
|
|
7960
8482
|
if (invitation !== null && !this.mayWithdraw(revoker, invitation)) {
|
|
7961
|
-
this.logger.warn(`revokeInvitation: refused email=${maskEmail(normalizedEmail)} tenantId=${logSafe(tenantId)} revokerUserId=${revokerUserId} \u2014 outranked by the invitation`);
|
|
8483
|
+
this.logger.warn(`revokeInvitation: refused email=${maskEmail(normalizedEmail)} tenantId=${logSafe(tenantId)} revokerUserId=${logSafe(revokerUserId)} \u2014 outranked by the invitation`);
|
|
7962
8484
|
return false;
|
|
7963
8485
|
}
|
|
7964
8486
|
await this.redis.del(indexKey);
|
|
7965
8487
|
const removed = await this.redis.del(`inv:${tokenHash}`);
|
|
7966
|
-
this.logger.log(`revokeInvitation: invitation withdrawn email=${maskEmail(normalizedEmail)} tenantId=${logSafe(tenantId)} revokerUserId=${revokerUserId}`);
|
|
8488
|
+
this.logger.log(`revokeInvitation: invitation withdrawn email=${maskEmail(normalizedEmail)} tenantId=${logSafe(tenantId)} revokerUserId=${logSafe(revokerUserId)}`);
|
|
7967
8489
|
return removed;
|
|
7968
8490
|
}
|
|
7969
8491
|
/**
|
|
@@ -8010,10 +8532,13 @@ exports.InvitationService = class _InvitationService {
|
|
|
8010
8532
|
* grant what the invitation grants.
|
|
8011
8533
|
*/
|
|
8012
8534
|
async assertInviterStillAuthorised(invitation) {
|
|
8013
|
-
const inviter = await this.userRepo.findById(
|
|
8535
|
+
const inviter = await this.userRepo.findById({
|
|
8536
|
+
id: invitation.inviterUserId,
|
|
8537
|
+
tenantId: invitation.tenantId
|
|
8538
|
+
});
|
|
8014
8539
|
const stillAuthorised = inviter !== null && this.inGoodStanding(inviter) && inviter.tenantId === invitation.tenantId && hasRole(inviter.role, invitation.role, this.options.roles.hierarchy);
|
|
8015
8540
|
if (!stillAuthorised) {
|
|
8016
|
-
this.logger.warn(`acceptInvitation: the inviter can no longer grant this invitation inviterUserId=${invitation.inviterUserId} role=${invitation.role}`);
|
|
8541
|
+
this.logger.warn(`acceptInvitation: the inviter can no longer grant this invitation inviterUserId=${logSafe(invitation.inviterUserId)} role=${logSafe(invitation.role)}`);
|
|
8017
8542
|
throw new AuthException(AUTH_ERROR_CODES.INVALID_INVITATION_TOKEN);
|
|
8018
8543
|
}
|
|
8019
8544
|
}
|
|
@@ -8040,7 +8565,10 @@ exports.InvitationService = class _InvitationService {
|
|
|
8040
8565
|
throw new AuthException(AUTH_ERROR_CODES.INVALID_INVITATION_TOKEN);
|
|
8041
8566
|
}
|
|
8042
8567
|
await this.assertInviterStillAuthorised(invitation);
|
|
8043
|
-
const existing = await this.userRepo.findByEmail(
|
|
8568
|
+
const existing = await this.userRepo.findByEmail({
|
|
8569
|
+
email: invitation.email,
|
|
8570
|
+
tenantId: invitation.tenantId
|
|
8571
|
+
});
|
|
8044
8572
|
if (existing) {
|
|
8045
8573
|
throw new AuthException(AUTH_ERROR_CODES.EMAIL_ALREADY_EXISTS);
|
|
8046
8574
|
}
|
|
@@ -8057,16 +8585,22 @@ exports.InvitationService = class _InvitationService {
|
|
|
8057
8585
|
const { passwordHash: _ph, mfaSecret: _ms, mfaRecoveryCodes: _mrc, ...safeUser } = authUser;
|
|
8058
8586
|
const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
|
|
8059
8587
|
if (this.options.sessions.enabled) {
|
|
8060
|
-
await this.sessionService.createSession(
|
|
8588
|
+
await this.sessionService.createSession({
|
|
8589
|
+
userId: safeUser.id,
|
|
8590
|
+
tenantId: safeUser.tenantId,
|
|
8591
|
+
rawRefreshToken: result.rawRefreshToken,
|
|
8592
|
+
ip,
|
|
8593
|
+
userAgent
|
|
8594
|
+
});
|
|
8061
8595
|
}
|
|
8062
|
-
this.logger.log(`acceptInvitation: invitation accepted userId=${safeUser.id} tenantId=${invitation.tenantId} role=${invitation.role}`);
|
|
8596
|
+
this.logger.log(`acceptInvitation: invitation accepted userId=${logSafe(safeUser.id)} tenantId=${logSafe(invitation.tenantId)} role=${logSafe(invitation.role)}`);
|
|
8063
8597
|
if (this.hooks?.afterInvitationAccepted) {
|
|
8064
8598
|
void Promise.resolve(this.hooks.afterInvitationAccepted(safeUser, {
|
|
8065
8599
|
ip,
|
|
8066
8600
|
userAgent,
|
|
8067
8601
|
sanitizedHeaders: sanitizeHeaders(headers)
|
|
8068
8602
|
})).catch((err) => {
|
|
8069
|
-
this.logger.error(
|
|
8603
|
+
this.logger.error(`afterInvitationAccepted hook threw: ${describeChannelStatus(err)}`);
|
|
8070
8604
|
});
|
|
8071
8605
|
}
|
|
8072
8606
|
return result;
|
|
@@ -8612,6 +9146,7 @@ function isMfaSetupData(value) {
|
|
|
8612
9146
|
return typeof v["encryptedSecret"] === "string" && typeof v["encryptedPlainCodes"] === "string" && Array.isArray(v["hashedCodes"]) && v["hashedCodes"].every((code) => typeof code === "string");
|
|
8613
9147
|
}
|
|
8614
9148
|
__name(isMfaSetupData, "isMfaSetupData");
|
|
9149
|
+
var PLANE_TENANT_MESSAGE = "tenantId must be a non-empty value on the dashboard plane and absent on the platform plane";
|
|
8615
9150
|
exports.MfaService = class _MfaService {
|
|
8616
9151
|
static {
|
|
8617
9152
|
__name(this, "MfaService");
|
|
@@ -8677,10 +9212,15 @@ exports.MfaService = class _MfaService {
|
|
|
8677
9212
|
if (context === "platform" && this.platformUserRepo) {
|
|
8678
9213
|
await this.platformUserRepo.updateMfa(userId, update);
|
|
8679
9214
|
} else {
|
|
8680
|
-
|
|
9215
|
+
this.assertDashboardTenant(tenantId);
|
|
9216
|
+
await this.userRepo.updateMfa({
|
|
9217
|
+
id: userId,
|
|
9218
|
+
tenantId,
|
|
9219
|
+
data: update
|
|
9220
|
+
});
|
|
8681
9221
|
}
|
|
8682
9222
|
} catch (err) {
|
|
8683
|
-
this.logger.error(
|
|
9223
|
+
this.logger.error(`re-encryption under the current MFA key failed: ${describeChannelStatus(err)}`);
|
|
8684
9224
|
}
|
|
8685
9225
|
}
|
|
8686
9226
|
/**
|
|
@@ -8721,7 +9261,7 @@ exports.MfaService = class _MfaService {
|
|
|
8721
9261
|
* @throws {@link AuthException} `MFA_STATE_CONFLICT` when another transition holds the lock.
|
|
8722
9262
|
*/
|
|
8723
9263
|
async transitionMfaRecord(context, userId, tenantId, mutate) {
|
|
8724
|
-
const scopedLockKey = `mfalock:${hmacSha256(
|
|
9264
|
+
const scopedLockKey = `mfalock:${hmacSha256(userSubject(context, userId, tenantId), this.options.hmacKey)}`;
|
|
8725
9265
|
const legacyLockKey = `mfalock:${hmacSha256(`${context}:${userId}`, this.options.hmacKey)}`;
|
|
8726
9266
|
const acquireLegacy = legacyLockKey !== scopedLockKey;
|
|
8727
9267
|
const lockToken = crypto.randomBytes(16).toString("hex");
|
|
@@ -8748,7 +9288,12 @@ exports.MfaService = class _MfaService {
|
|
|
8748
9288
|
if (context === "platform" && this.platformUserRepo) {
|
|
8749
9289
|
await this.platformUserRepo.updateMfa(userId, write);
|
|
8750
9290
|
} else {
|
|
8751
|
-
|
|
9291
|
+
this.assertDashboardTenant(tenantId);
|
|
9292
|
+
await this.userRepo.updateMfa({
|
|
9293
|
+
id: userId,
|
|
9294
|
+
tenantId,
|
|
9295
|
+
data: write
|
|
9296
|
+
});
|
|
8752
9297
|
}
|
|
8753
9298
|
return true;
|
|
8754
9299
|
} finally {
|
|
@@ -8828,7 +9373,7 @@ exports.MfaService = class _MfaService {
|
|
|
8828
9373
|
try {
|
|
8829
9374
|
parsed = JSON.parse(raw);
|
|
8830
9375
|
} catch {
|
|
8831
|
-
this.logger.warn(`parseSetupData: pending-setup payload is not valid JSON userId=${userId}`);
|
|
9376
|
+
this.logger.warn(`parseSetupData: pending-setup payload is not valid JSON userId=${logSafe(userId)}`);
|
|
8832
9377
|
throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
|
|
8833
9378
|
}
|
|
8834
9379
|
if (!isMfaSetupData(parsed)) {
|
|
@@ -8850,7 +9395,7 @@ exports.MfaService = class _MfaService {
|
|
|
8850
9395
|
try {
|
|
8851
9396
|
parsed = JSON.parse(raw);
|
|
8852
9397
|
} catch {
|
|
8853
|
-
this.logger.warn(`parsePlainRecoveryCodes: decrypted payload is not valid JSON userId=${userId}`);
|
|
9398
|
+
this.logger.warn(`parsePlainRecoveryCodes: decrypted payload is not valid JSON userId=${logSafe(userId)}`);
|
|
8854
9399
|
throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
|
|
8855
9400
|
}
|
|
8856
9401
|
if (!Array.isArray(parsed) || parsed.some((code) => typeof code !== "string")) {
|
|
@@ -8953,7 +9498,7 @@ exports.MfaService = class _MfaService {
|
|
|
8953
9498
|
* @returns `true` when this challenge is the one that claimed it.
|
|
8954
9499
|
*/
|
|
8955
9500
|
async claimRecoveryCode(context, userId, code, tenantId) {
|
|
8956
|
-
const claimKey = `rcu:${hmacSha256(`${
|
|
9501
|
+
const claimKey = `rcu:${hmacSha256(`${userSubject(context, userId, tenantId)}:${code}`, this.options.hmacKey)}`;
|
|
8957
9502
|
return await this.redis.setnx(claimKey, RECOVERY_CODE_CLAIM_TTL_SECONDS);
|
|
8958
9503
|
}
|
|
8959
9504
|
/**
|
|
@@ -9019,7 +9564,7 @@ exports.MfaService = class _MfaService {
|
|
|
9019
9564
|
const user = await this.fetchUserForContext(context, userId, tenantId);
|
|
9020
9565
|
if (user.mfaEnabled) throw new AuthException(AUTH_ERROR_CODES.MFA_ALREADY_ENABLED);
|
|
9021
9566
|
await this.assertReauthenticated(context, userId, user.passwordHash, password, tenantId);
|
|
9022
|
-
const setupKey = `mfa_setup:${hmacSha256(
|
|
9567
|
+
const setupKey = `mfa_setup:${hmacSha256(userSubject(context, userId, tenantId), this.options.hmacKey)}`;
|
|
9023
9568
|
const existingFast = await this.redis.get(setupKey);
|
|
9024
9569
|
if (existingFast !== null) {
|
|
9025
9570
|
const data = this.parseSetupData(existingFast, userId);
|
|
@@ -9062,7 +9607,7 @@ exports.MfaService = class _MfaService {
|
|
|
9062
9607
|
await this.redis.set(setupKey, payload, MFA_SETUP_TTL_SECONDS);
|
|
9063
9608
|
}
|
|
9064
9609
|
const qrCodeUri = buildTotpUri(secretBase32, user.email, this.mfaOptions.issuer);
|
|
9065
|
-
this.logger.log(`setup: MFA setup initiated userId=${userId} context=${context}`);
|
|
9610
|
+
this.logger.log(`setup: MFA setup initiated userId=${logSafe(userId)} context=${context}`);
|
|
9066
9611
|
return {
|
|
9067
9612
|
secret: secretBase32,
|
|
9068
9613
|
qrCodeUri,
|
|
@@ -9099,7 +9644,7 @@ exports.MfaService = class _MfaService {
|
|
|
9099
9644
|
}
|
|
9100
9645
|
const user = await this.fetchUserForContext(context, userId, tenantId);
|
|
9101
9646
|
if (user.mfaEnabled) throw new AuthException(AUTH_ERROR_CODES.MFA_ALREADY_ENABLED);
|
|
9102
|
-
const setupKey = `mfa_setup:${hmacSha256(
|
|
9647
|
+
const setupKey = `mfa_setup:${hmacSha256(userSubject(context, userId, tenantId), this.options.hmacKey)}`;
|
|
9103
9648
|
const raw = await this.redis.get(setupKey);
|
|
9104
9649
|
if (raw === null) throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
|
|
9105
9650
|
const data = this.parseSetupData(raw, userId);
|
|
@@ -9107,12 +9652,12 @@ exports.MfaService = class _MfaService {
|
|
|
9107
9652
|
const totpWindow = this.mfaOptions.totpWindow;
|
|
9108
9653
|
const codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, code, totpWindow, tenantId);
|
|
9109
9654
|
if (!codeValid) {
|
|
9110
|
-
this.logger.warn(`verifyAndEnable: invalid TOTP code userId=${userId}`);
|
|
9655
|
+
this.logger.warn(`verifyAndEnable: invalid TOTP code userId=${logSafe(userId)}`);
|
|
9111
9656
|
throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
|
|
9112
9657
|
}
|
|
9113
9658
|
const consumed = await this.redis.getdel(setupKey);
|
|
9114
9659
|
if (consumed === null) {
|
|
9115
|
-
this.logger.warn(`verifyAndEnable: setup key consumed by concurrent request userId=${userId}`);
|
|
9660
|
+
this.logger.warn(`verifyAndEnable: setup key consumed by concurrent request userId=${logSafe(userId)}`);
|
|
9116
9661
|
throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
|
|
9117
9662
|
}
|
|
9118
9663
|
await this.transitionMfaRecord(context, userId, tenantId, () => ({
|
|
@@ -9120,10 +9665,10 @@ exports.MfaService = class _MfaService {
|
|
|
9120
9665
|
mfaSecret: data.encryptedSecret,
|
|
9121
9666
|
mfaRecoveryCodes: data.hashedCodes
|
|
9122
9667
|
}));
|
|
9123
|
-
await this.redis.invalidateUserSessions(userId, context);
|
|
9124
|
-
await this.redis.bumpUserTokenEpoch(userId, context);
|
|
9125
|
-
this.logger.log(`verifyAndEnable: MFA enabled userId=${userId} context=${context}`);
|
|
9126
|
-
|
|
9668
|
+
await this.redis.invalidateUserSessions(userId, tenantId, context);
|
|
9669
|
+
await this.redis.bumpUserTokenEpoch(userId, tenantId, context);
|
|
9670
|
+
this.logger.log(`verifyAndEnable: MFA enabled userId=${logSafe(userId)} context=${context}`);
|
|
9671
|
+
this.notify("verifyAndEnable", userId, user, (provider, tenant, email) => provider.sendMfaEnabledNotification(tenant, email));
|
|
9127
9672
|
if (this.hooks.afterMfaEnabled) {
|
|
9128
9673
|
const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
|
|
9129
9674
|
void Promise.resolve(this.hooks.afterMfaEnabled(safeUser, {
|
|
@@ -9157,7 +9702,7 @@ exports.MfaService = class _MfaService {
|
|
|
9157
9702
|
async challenge(mfaTempToken, code, ip, userAgent) {
|
|
9158
9703
|
const { userId, context, tenantId, jti: tempTokenJti } = await this.tokenManager.verifyMfaTempToken(mfaTempToken);
|
|
9159
9704
|
if (await this.isMfaFlowLockedOut("challenge", context, userId, tenantId)) {
|
|
9160
|
-
this.logger.warn(`challenge: account locked userId=${userId}`);
|
|
9705
|
+
this.logger.warn(`challenge: account locked userId=${logSafe(userId)}`);
|
|
9161
9706
|
throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
|
|
9162
9707
|
}
|
|
9163
9708
|
const user = await this.fetchUserForContext(context, userId, tenantId);
|
|
@@ -9178,7 +9723,7 @@ exports.MfaService = class _MfaService {
|
|
|
9178
9723
|
}
|
|
9179
9724
|
if (!codeValid) {
|
|
9180
9725
|
await this.recordMfaFlowFailure("challenge", context, userId, tenantId);
|
|
9181
|
-
this.logger.warn(`challenge: invalid MFA code userId=${userId} context=${context}`);
|
|
9726
|
+
this.logger.warn(`challenge: invalid MFA code userId=${logSafe(userId)} context=${context}`);
|
|
9182
9727
|
throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
|
|
9183
9728
|
}
|
|
9184
9729
|
await this.resetMfaFlowFailures("challenge", context, userId, tenantId);
|
|
@@ -9211,14 +9756,20 @@ exports.MfaService = class _MfaService {
|
|
|
9211
9756
|
} else if (encryptedUnderRetiredKey) {
|
|
9212
9757
|
void this.reencryptSecret(userId, context, secretBase32, user.mfaRecoveryCodes ?? [], tenantId);
|
|
9213
9758
|
}
|
|
9214
|
-
this.logger.log(`challenge: MFA challenge passed userId=${userId} context=${context}`);
|
|
9759
|
+
this.logger.log(`challenge: MFA challenge passed userId=${logSafe(userId)} context=${context}`);
|
|
9215
9760
|
if (context === "dashboard") {
|
|
9216
9761
|
const safeUser = this.toSafeUser(user);
|
|
9217
9762
|
const result2 = await this.tokenManager.issueTokens(safeUser, ip, userAgent, {
|
|
9218
9763
|
mfaVerified: true
|
|
9219
9764
|
});
|
|
9220
9765
|
if (this.options.sessions.enabled) {
|
|
9221
|
-
await this.sessionService.createSession(
|
|
9766
|
+
await this.sessionService.createSession({
|
|
9767
|
+
userId: safeUser.id,
|
|
9768
|
+
tenantId: safeUser.tenantId,
|
|
9769
|
+
rawRefreshToken: result2.rawRefreshToken,
|
|
9770
|
+
ip,
|
|
9771
|
+
userAgent
|
|
9772
|
+
});
|
|
9222
9773
|
}
|
|
9223
9774
|
if (this.hooks.afterLogin) {
|
|
9224
9775
|
void Promise.resolve(this.hooks.afterLogin(safeUser, {
|
|
@@ -9276,7 +9827,7 @@ exports.MfaService = class _MfaService {
|
|
|
9276
9827
|
const user = await this.fetchUserForContext(context, userId, tenantId);
|
|
9277
9828
|
if (!user.mfaEnabled) throw new AuthException(AUTH_ERROR_CODES.MFA_NOT_ENABLED);
|
|
9278
9829
|
if (await this.isMfaFlowLockedOut("disable", context, userId, tenantId)) {
|
|
9279
|
-
this.logger.warn(`disable: account locked userId=${userId} context=${context}`);
|
|
9830
|
+
this.logger.warn(`disable: account locked userId=${logSafe(userId)} context=${context}`);
|
|
9280
9831
|
throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
|
|
9281
9832
|
}
|
|
9282
9833
|
if (!user.mfaSecret) {
|
|
@@ -9287,7 +9838,7 @@ exports.MfaService = class _MfaService {
|
|
|
9287
9838
|
const codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, code, totpWindow, tenantId);
|
|
9288
9839
|
if (!codeValid) {
|
|
9289
9840
|
await this.recordMfaFlowFailure("disable", context, userId, tenantId);
|
|
9290
|
-
this.logger.warn(`disable: invalid MFA code userId=${userId} context=${context}`);
|
|
9841
|
+
this.logger.warn(`disable: invalid MFA code userId=${logSafe(userId)} context=${context}`);
|
|
9291
9842
|
throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
|
|
9292
9843
|
}
|
|
9293
9844
|
await this.resetMfaFlowFailures("disable", context, userId, tenantId);
|
|
@@ -9296,10 +9847,10 @@ exports.MfaService = class _MfaService {
|
|
|
9296
9847
|
mfaSecret: null,
|
|
9297
9848
|
mfaRecoveryCodes: null
|
|
9298
9849
|
}));
|
|
9299
|
-
await this.redis.invalidateUserSessions(userId, context);
|
|
9300
|
-
await this.redis.bumpUserTokenEpoch(userId, context);
|
|
9301
|
-
this.logger.log(`disable: MFA disabled userId=${userId} context=${context}`);
|
|
9302
|
-
|
|
9850
|
+
await this.redis.invalidateUserSessions(userId, tenantId, context);
|
|
9851
|
+
await this.redis.bumpUserTokenEpoch(userId, tenantId, context);
|
|
9852
|
+
this.logger.log(`disable: MFA disabled userId=${logSafe(userId)} context=${context}`);
|
|
9853
|
+
this.notify("disable", userId, user, (provider, tenant, email) => provider.sendMfaDisabledNotification(tenant, email));
|
|
9303
9854
|
const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
|
|
9304
9855
|
if (this.hooks.afterMfaDisabled) {
|
|
9305
9856
|
void Promise.resolve(this.hooks.afterMfaDisabled(safeUser, {
|
|
@@ -9355,7 +9906,7 @@ exports.MfaService = class _MfaService {
|
|
|
9355
9906
|
this.assertPlaneTenant(context, tenantId);
|
|
9356
9907
|
const user = await this.fetchUserForContext(context, userId, tenantId);
|
|
9357
9908
|
if (!user.mfaEnabled) {
|
|
9358
|
-
this.logger.log(`resetMfa: no second factor to remove userId=${userId} context=${context}`);
|
|
9909
|
+
this.logger.log(`resetMfa: no second factor to remove userId=${logSafe(userId)} context=${context}`);
|
|
9359
9910
|
return;
|
|
9360
9911
|
}
|
|
9361
9912
|
await this.transitionMfaRecord(context, userId, tenantId, () => ({
|
|
@@ -9363,10 +9914,10 @@ exports.MfaService = class _MfaService {
|
|
|
9363
9914
|
mfaSecret: null,
|
|
9364
9915
|
mfaRecoveryCodes: null
|
|
9365
9916
|
}));
|
|
9366
|
-
await this.redis.invalidateUserSessions(userId, context);
|
|
9367
|
-
await this.redis.bumpUserTokenEpoch(userId, context);
|
|
9368
|
-
this.logger.warn(`resetMfa: MFA removed administratively userId=${userId} context=${context}`);
|
|
9369
|
-
|
|
9917
|
+
await this.redis.invalidateUserSessions(userId, tenantId, context);
|
|
9918
|
+
await this.redis.bumpUserTokenEpoch(userId, tenantId, context);
|
|
9919
|
+
this.logger.warn(`resetMfa: MFA removed administratively userId=${logSafe(userId)} context=${context}`);
|
|
9920
|
+
this.notify("resetMfa", userId, user, (provider, tenant, email) => provider.sendMfaDisabledNotification(tenant, email));
|
|
9370
9921
|
const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
|
|
9371
9922
|
if (this.hooks.afterMfaDisabled) {
|
|
9372
9923
|
void Promise.resolve(this.hooks.afterMfaDisabled(safeUser, {
|
|
@@ -9427,7 +9978,7 @@ exports.MfaService = class _MfaService {
|
|
|
9427
9978
|
const user = await this.fetchUserForContext(context, userId, tenantId);
|
|
9428
9979
|
if (!user.mfaEnabled) throw new AuthException(AUTH_ERROR_CODES.MFA_NOT_ENABLED);
|
|
9429
9980
|
if (await this.isMfaFlowLockedOut("disable", context, userId, tenantId)) {
|
|
9430
|
-
this.logger.warn(`regenerateRecoveryCodes: account locked userId=${userId} context=${context}`);
|
|
9981
|
+
this.logger.warn(`regenerateRecoveryCodes: account locked userId=${logSafe(userId)} context=${context}`);
|
|
9431
9982
|
throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
|
|
9432
9983
|
}
|
|
9433
9984
|
if (!user.mfaSecret) {
|
|
@@ -9438,7 +9989,7 @@ exports.MfaService = class _MfaService {
|
|
|
9438
9989
|
const codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, totpCode, totpWindow, tenantId);
|
|
9439
9990
|
if (!codeValid) {
|
|
9440
9991
|
await this.recordMfaFlowFailure("disable", context, userId, tenantId);
|
|
9441
|
-
this.logger.warn(`regenerateRecoveryCodes: invalid MFA code userId=${userId} context=${context}`);
|
|
9992
|
+
this.logger.warn(`regenerateRecoveryCodes: invalid MFA code userId=${logSafe(userId)} context=${context}`);
|
|
9442
9993
|
throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
|
|
9443
9994
|
}
|
|
9444
9995
|
await this.resetMfaFlowFailures("disable", context, userId, tenantId);
|
|
@@ -9453,7 +10004,7 @@ exports.MfaService = class _MfaService {
|
|
|
9453
10004
|
};
|
|
9454
10005
|
});
|
|
9455
10006
|
if (!replaced) throw new AuthException(AUTH_ERROR_CODES.MFA_NOT_ENABLED);
|
|
9456
|
-
this.logger.log(`regenerateRecoveryCodes: recovery codes regenerated userId=${userId} context=${context}`);
|
|
10007
|
+
this.logger.log(`regenerateRecoveryCodes: recovery codes regenerated userId=${logSafe(userId)} context=${context}`);
|
|
9457
10008
|
if (this.hooks.afterMfaRecoveryCodesRegenerated) {
|
|
9458
10009
|
const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
|
|
9459
10010
|
void Promise.resolve(this.hooks.afterMfaRecoveryCodesRegenerated(safeUser, {
|
|
@@ -9473,17 +10024,21 @@ exports.MfaService = class _MfaService {
|
|
|
9473
10024
|
/**
|
|
9474
10025
|
* Verifies a TOTP code and enforces anti-replay within the validation window.
|
|
9475
10026
|
*
|
|
9476
|
-
* Stores a Redis key `tu:{hmac}` where `hmac = hmacSha256("{
|
|
9477
|
-
*
|
|
9478
|
-
* rejected as a replay.
|
|
9479
|
-
*
|
|
10027
|
+
* Stores a Redis key `tu:{hmac}` where `hmac = hmacSha256("{userSubject}:{code}", hmacKey)` —
|
|
10028
|
+
* so the marker is scoped to the plane and, on the dashboard plane, to the tenant. A second
|
|
10029
|
+
* submission of the same code within the TTL is rejected as a replay. Binding the marker to
|
|
10030
|
+
* both the subject and the code value prevents code disclosure in Redis and cross-user,
|
|
10031
|
+
* cross-tenant and cross-plane replay alike.
|
|
10032
|
+
*
|
|
10033
|
+
* A second marker under the pre-scoping preimage `{context}:{userId}:{code}` is written and
|
|
10034
|
+
* required alongside it; see the call site for why both must be fresh during a rolling upgrade.
|
|
9480
10035
|
*
|
|
9481
10036
|
* @returns `true` if the code is valid and has not been replayed, `false` otherwise.
|
|
9482
10037
|
*/
|
|
9483
10038
|
async verifyTotpWithAntiReplay(context, userId, secretBase32, code, window, tenantId) {
|
|
9484
10039
|
if (!verifyTotp(secretBase32, code, window)) return false;
|
|
9485
10040
|
const ttl = totpAntiReplayTtlSeconds(window);
|
|
9486
|
-
const scopedReplayKey = `tu:${hmacSha256(`${
|
|
10041
|
+
const scopedReplayKey = `tu:${hmacSha256(`${userSubject(context, userId, tenantId)}:${code}`, this.options.hmacKey)}`;
|
|
9487
10042
|
const legacyReplayKey = `tu:${hmacSha256(`${context}:${userId}:${code}`, this.options.hmacKey)}`;
|
|
9488
10043
|
const scopedIsNew = await this.redis.setnx(scopedReplayKey, ttl);
|
|
9489
10044
|
if (scopedReplayKey === legacyReplayKey) return scopedIsNew;
|
|
@@ -9518,13 +10073,13 @@ exports.MfaService = class _MfaService {
|
|
|
9518
10073
|
if (passwordHash === null) {
|
|
9519
10074
|
const recent = await this.redis.get(recentAuthKey(context, userId, this.options.hmacKey, tenantId));
|
|
9520
10075
|
if (recent === null) {
|
|
9521
|
-
this.logger.warn(`reauthenticate: no recent authentication userId=${userId} context=${context}`);
|
|
10076
|
+
this.logger.warn(`reauthenticate: no recent authentication userId=${logSafe(userId)} context=${context}`);
|
|
9522
10077
|
throw new AuthException(AUTH_ERROR_CODES.REAUTHENTICATION_REQUIRED);
|
|
9523
10078
|
}
|
|
9524
10079
|
return;
|
|
9525
10080
|
}
|
|
9526
10081
|
if (await this.isMfaFlowLockedOut("reauth", context, userId, tenantId)) {
|
|
9527
|
-
this.logger.warn(`reauthenticate: account locked userId=${userId} context=${context}`);
|
|
10082
|
+
this.logger.warn(`reauthenticate: account locked userId=${logSafe(userId)} context=${context}`);
|
|
9528
10083
|
throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
|
|
9529
10084
|
}
|
|
9530
10085
|
const supplied = password ?? "";
|
|
@@ -9536,31 +10091,28 @@ exports.MfaService = class _MfaService {
|
|
|
9536
10091
|
await this.resetMfaFlowFailures("reauth", context, userId, tenantId);
|
|
9537
10092
|
}
|
|
9538
10093
|
/**
|
|
9539
|
-
*
|
|
9540
|
-
* account is blocked.
|
|
10094
|
+
* Asserts a dashboard-plane call carries a tenant, narrowing it to `string` for the caller.
|
|
9541
10095
|
*
|
|
9542
|
-
*
|
|
9543
|
-
*
|
|
9544
|
-
*
|
|
9545
|
-
*
|
|
9546
|
-
*
|
|
9547
|
-
*
|
|
9548
|
-
* own authenticator over it — for the token's remaining lifetime. Nothing else covers that
|
|
9549
|
-
* window: no status change bumps the token epoch, so the per-request check is the only
|
|
9550
|
-
* defence, and neither MFA controller composes `UserStatusGuard` (the platform plane has no
|
|
9551
|
-
* status guard at all). Every other authority-bearing route in the library does gate on
|
|
9552
|
-
* status; changing an authentication factor is at least as privileged as minting an
|
|
9553
|
-
* invitation.
|
|
10096
|
+
* This is the dashboard half of {@link assertPlaneTenant}, split out for one reason: an
|
|
10097
|
+
* assertion signature is the only way to state "past this point the tenant is present" to the
|
|
10098
|
+
* type system. `IUserRepository.findById` requires the tenant, and the account read behind the
|
|
10099
|
+
* MFA flows sits under a `context === 'dashboard'` branch where a `void` guard run earlier in
|
|
10100
|
+
* the caller has narrowed nothing. Without this the branch had to pass `string | undefined`
|
|
10101
|
+
* into a `string` parameter, which is precisely the tenant-blind read the guard exists to stop.
|
|
9554
10102
|
*
|
|
9555
|
-
*
|
|
9556
|
-
*
|
|
9557
|
-
*
|
|
9558
|
-
* @param context - Which identity plane the caller is acting on.
|
|
9559
|
-
* @param userId - The subject taken from the verified token.
|
|
9560
|
-
* @returns The account record, guaranteed to be in good standing.
|
|
9561
|
-
* @throws `TOKEN_INVALID` if the user is not found.
|
|
9562
|
-
* @throws {@link AuthException} the status error when the account is blocked.
|
|
10103
|
+
* @param tenantId - The tenant supplied by the caller, if any.
|
|
10104
|
+
* @throws {@link AuthException} `VALIDATION` (400) when it is missing or blank.
|
|
9563
10105
|
*/
|
|
10106
|
+
assertDashboardTenant(tenantId) {
|
|
10107
|
+
if (tenantId === void 0 || tenantId === "") {
|
|
10108
|
+
throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
|
|
10109
|
+
{
|
|
10110
|
+
field: "tenantId",
|
|
10111
|
+
message: PLANE_TENANT_MESSAGE
|
|
10112
|
+
}
|
|
10113
|
+
]);
|
|
10114
|
+
}
|
|
10115
|
+
}
|
|
9564
10116
|
/**
|
|
9565
10117
|
* A dashboard MFA flow MUST carry the tenant it was authenticated in; a platform flow MUST NOT.
|
|
9566
10118
|
*
|
|
@@ -9577,11 +10129,15 @@ exports.MfaService = class _MfaService {
|
|
|
9577
10129
|
* platform call supplies one.
|
|
9578
10130
|
*/
|
|
9579
10131
|
assertPlaneTenant(context, tenantId) {
|
|
9580
|
-
if (context === "dashboard"
|
|
10132
|
+
if (context === "dashboard") {
|
|
10133
|
+
this.assertDashboardTenant(tenantId);
|
|
10134
|
+
return;
|
|
10135
|
+
}
|
|
10136
|
+
if (tenantId !== void 0) {
|
|
9581
10137
|
throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
|
|
9582
10138
|
{
|
|
9583
10139
|
field: "tenantId",
|
|
9584
|
-
message:
|
|
10140
|
+
message: PLANE_TENANT_MESSAGE
|
|
9585
10141
|
}
|
|
9586
10142
|
]);
|
|
9587
10143
|
}
|
|
@@ -9593,7 +10149,7 @@ exports.MfaService = class _MfaService {
|
|
|
9593
10149
|
*
|
|
9594
10150
|
* A rolling upgrade runs old and new code against one Redis at once: on the dashboard plane an
|
|
9595
10151
|
* old pod counts a failure under `{flow}:{plane}:{userId}` while a new pod counts it under
|
|
9596
|
-
* `{flow}:{
|
|
10152
|
+
* `{flow}:{userSubject}`, and either alone leaves a hole — a lockout an old pod filled would not
|
|
9597
10153
|
* stop a new pod, and a success on one would not clear the other. For one release every read
|
|
9598
10154
|
* consults both and every write touches both, so the two move as one; a later release drops the
|
|
9599
10155
|
* legacy arm. On the platform plane the two ids are identical (no tenant ever entered the
|
|
@@ -9604,7 +10160,7 @@ exports.MfaService = class _MfaService {
|
|
|
9604
10160
|
mfaFlowCounterIds(flow, context, userId, tenantId) {
|
|
9605
10161
|
return {
|
|
9606
10162
|
legacy: hmacSha256(`${flow}:${context}:${userId}`, this.options.hmacKey),
|
|
9607
|
-
scoped: hmacSha256(`${flow}:${
|
|
10163
|
+
scoped: hmacSha256(`${flow}:${userSubject(context, userId, tenantId)}`, this.options.hmacKey)
|
|
9608
10164
|
};
|
|
9609
10165
|
}
|
|
9610
10166
|
/**
|
|
@@ -9634,9 +10190,79 @@ exports.MfaService = class _MfaService {
|
|
|
9634
10190
|
await this.bruteForce.resetFailures(scoped);
|
|
9635
10191
|
if (legacy !== scoped) await this.bruteForce.resetFailures(legacy);
|
|
9636
10192
|
}
|
|
10193
|
+
/**
|
|
10194
|
+
* Sends an MFA state-change notice, fire-and-forget, with the recipient kept out of the log.
|
|
10195
|
+
*
|
|
10196
|
+
* **Not awaited, and that is the fix, not a shortcut.** These three sends used to be awaited
|
|
10197
|
+
* with no `catch`, so a rejected delivery travelled out of the service to `AuthExceptionFilter`
|
|
10198
|
+
* — which answered the caller with an error for an operation that had ALREADY completed. By
|
|
10199
|
+
* that point the secret is written, the sessions are invalidated and the token epoch is bumped;
|
|
10200
|
+
* the user's second factor is on, and telling them it failed is how they end up locked out of
|
|
10201
|
+
* an account they just secured. `PasswordResetService.notifyPasswordChanged` had reached the
|
|
10202
|
+
* same conclusion for the same reason.
|
|
10203
|
+
*
|
|
10204
|
+
* **And the address does not reach the log.** The filter logged that error raw, and an SMTP
|
|
10205
|
+
* rejection routinely NAMES the recipient it refused (`550 user@example.com: recipient
|
|
10206
|
+
* rejected`) — no quoted body required, which makes it the likeliest exposure of the set.
|
|
10207
|
+
* `describeChannelStatus` publishes nothing the channel wrote, and nothing parsed off it either,
|
|
10208
|
+
* so no part of that name comes through. `withheld` covers the fields this line composes rather than the error, and
|
|
10209
|
+
* `safeLogLine` checks the seam the template opens between them.
|
|
10210
|
+
*
|
|
10211
|
+
* @param origin - The calling flow, for the log line.
|
|
10212
|
+
* @param userId - Whose account changed.
|
|
10213
|
+
* @param user - The account, read for its tenant and address.
|
|
10214
|
+
* @param send - Which notice to dispatch.
|
|
10215
|
+
*/
|
|
10216
|
+
notify(origin, userId, user, send) {
|
|
10217
|
+
const provider = this.emailProvider;
|
|
10218
|
+
const tenantId = emailTenantOf(user);
|
|
10219
|
+
const email = user.email;
|
|
10220
|
+
const withheld = [
|
|
10221
|
+
email
|
|
10222
|
+
];
|
|
10223
|
+
void (async () => {
|
|
10224
|
+
try {
|
|
10225
|
+
await send(provider, tenantId, email);
|
|
10226
|
+
} catch (err) {
|
|
10227
|
+
this.logger.error(safeLogLine(`${origin}: MFA notice delivery failed for user ${logSafe(userId)}: ` + describeChannelStatus(err), withheld));
|
|
10228
|
+
}
|
|
10229
|
+
})();
|
|
10230
|
+
}
|
|
10231
|
+
/**
|
|
10232
|
+
* Fetches a user from the correct repository based on the MFA context, and refuses one whose
|
|
10233
|
+
* account is blocked.
|
|
10234
|
+
*
|
|
10235
|
+
* The status gate lives here rather than in each caller because every entry point that
|
|
10236
|
+
* reaches this method changes or spends an authentication factor, and every one of them
|
|
10237
|
+
* must refuse a suspended or banned account. It used to live in `challenge` alone, so
|
|
10238
|
+
* `setup`, `verifyAndEnable`, `disable` and `regenerateRecoveryCodes` had no gate at all:
|
|
10239
|
+
* an operator who suspended a compromised account bought nothing against an attacker still
|
|
10240
|
+
* holding an unexpired access token, who could turn the second factor off — or enrol their
|
|
10241
|
+
* own authenticator over it — for the token's remaining lifetime. Nothing else covers that
|
|
10242
|
+
* window: no status change bumps the token epoch, so the per-request check is the only
|
|
10243
|
+
* defence, and neither MFA controller composes `UserStatusGuard` (the platform plane has no
|
|
10244
|
+
* status guard at all). Every other authority-bearing route in the library does gate on
|
|
10245
|
+
* status; changing an authentication factor is at least as privileged as minting an
|
|
10246
|
+
* invitation.
|
|
10247
|
+
*
|
|
10248
|
+
* Gating the fetch rather than the callers is deliberate: a method added later inherits the
|
|
10249
|
+
* check instead of having to remember it.
|
|
10250
|
+
*
|
|
10251
|
+
* @param context - Which identity plane the caller is acting on.
|
|
10252
|
+
* @param userId - The subject taken from the verified token.
|
|
10253
|
+
* @param tenantId - The tenant the caller was authenticated in, on the dashboard plane;
|
|
10254
|
+
* absent on the platform plane, whose admins belong to none.
|
|
10255
|
+
* @returns The account record, guaranteed to be in good standing.
|
|
10256
|
+
* @throws `TOKEN_INVALID` if the user is not found.
|
|
10257
|
+
* @throws {@link AuthException} the status error when the account is blocked.
|
|
10258
|
+
*/
|
|
9637
10259
|
async fetchUserForContext(context, userId, tenantId) {
|
|
9638
10260
|
if (context === "dashboard") {
|
|
9639
|
-
|
|
10261
|
+
this.assertDashboardTenant(tenantId);
|
|
10262
|
+
const user = await this.userRepo.findById({
|
|
10263
|
+
id: userId,
|
|
10264
|
+
tenantId
|
|
10265
|
+
});
|
|
9640
10266
|
if (!user) throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
|
|
9641
10267
|
assertNotBlocked(user.status, this.options.blockedStatuses);
|
|
9642
10268
|
return user;
|
|
@@ -10446,7 +11072,10 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10446
11072
|
return;
|
|
10447
11073
|
}
|
|
10448
11074
|
try {
|
|
10449
|
-
const user = tenantScoped(await this.userRepo.findByEmail(
|
|
11075
|
+
const user = tenantScoped(await this.userRepo.findByEmail({
|
|
11076
|
+
email: dto.email,
|
|
11077
|
+
tenantId
|
|
11078
|
+
}), tenantId);
|
|
10450
11079
|
if (user && !this.isBlocked(user.status)) {
|
|
10451
11080
|
const { method } = this.options.passwordReset;
|
|
10452
11081
|
if (method === "otp") {
|
|
@@ -10456,7 +11085,7 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10456
11085
|
}
|
|
10457
11086
|
}
|
|
10458
11087
|
} catch (err) {
|
|
10459
|
-
this.logger.error(
|
|
11088
|
+
this.logger.error(`initiateReset: unexpected error: ${describeChannelStatus(err)}`);
|
|
10460
11089
|
} finally {
|
|
10461
11090
|
await sleep(Math.max(0, ANTI_ENUM_MIN_MS2 - (Date.now() - start)));
|
|
10462
11091
|
}
|
|
@@ -10544,7 +11173,10 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10544
11173
|
};
|
|
10545
11174
|
const identifier = this.otpIdentifier(tenantId, dto.email);
|
|
10546
11175
|
await this.otpService.verify(PASSWORD_RESET_PURPOSE, identifier, dto.otp);
|
|
10547
|
-
const user = tenantScoped(await this.userRepo.findByEmail(
|
|
11176
|
+
const user = tenantScoped(await this.userRepo.findByEmail({
|
|
11177
|
+
email: dto.email,
|
|
11178
|
+
tenantId
|
|
11179
|
+
}), tenantId);
|
|
10548
11180
|
if (!user) {
|
|
10549
11181
|
throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
|
|
10550
11182
|
}
|
|
@@ -10553,7 +11185,7 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10553
11185
|
userId: user.id,
|
|
10554
11186
|
email: dto.email,
|
|
10555
11187
|
tenantId,
|
|
10556
|
-
passwordFingerprint: await this.passwordFingerprintOf(user.id)
|
|
11188
|
+
passwordFingerprint: await this.passwordFingerprintOf(user.id, user.tenantId)
|
|
10557
11189
|
};
|
|
10558
11190
|
await this.redis.set(`pw_vtok:${sha256(rawVerifiedToken)}`, JSON.stringify(context), VERIFIED_TOKEN_TTL_SECONDS);
|
|
10559
11191
|
return rawVerifiedToken;
|
|
@@ -10585,12 +11217,15 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10585
11217
|
return;
|
|
10586
11218
|
}
|
|
10587
11219
|
try {
|
|
10588
|
-
const user = tenantScoped(await this.userRepo.findByEmail(
|
|
11220
|
+
const user = tenantScoped(await this.userRepo.findByEmail({
|
|
11221
|
+
email: dto.email,
|
|
11222
|
+
tenantId
|
|
11223
|
+
}), tenantId);
|
|
10589
11224
|
if (user && !this.isBlocked(user.status)) {
|
|
10590
11225
|
await this.sendOtp(dto.email, tenantId, user.id);
|
|
10591
11226
|
}
|
|
10592
11227
|
} catch (err) {
|
|
10593
|
-
this.logger.error(
|
|
11228
|
+
this.logger.error(`resendOtp: unexpected error: ${describeChannelStatus(err)}`);
|
|
10594
11229
|
} finally {
|
|
10595
11230
|
await sleep(Math.max(0, ANTI_ENUM_MIN_MS2 - (Date.now() - start)));
|
|
10596
11231
|
}
|
|
@@ -10616,7 +11251,7 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10616
11251
|
throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
|
|
10617
11252
|
}
|
|
10618
11253
|
await this.assertResetTokenStillBound(context);
|
|
10619
|
-
await this.applyPasswordReset(context.userId, newPassword);
|
|
11254
|
+
await this.applyPasswordReset(context.userId, context.tenantId, newPassword);
|
|
10620
11255
|
}
|
|
10621
11256
|
/**
|
|
10622
11257
|
* Direct OTP reset path: verifies and consumes the OTP, then updates the password.
|
|
@@ -10624,11 +11259,14 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10624
11259
|
async resetWithOtp(email, tenantId, otp, newPassword) {
|
|
10625
11260
|
const identifier = this.otpIdentifier(tenantId, email);
|
|
10626
11261
|
await this.otpService.verify(PASSWORD_RESET_PURPOSE, identifier, otp);
|
|
10627
|
-
const user = tenantScoped(await this.userRepo.findByEmail(
|
|
11262
|
+
const user = tenantScoped(await this.userRepo.findByEmail({
|
|
11263
|
+
email,
|
|
11264
|
+
tenantId
|
|
11265
|
+
}), tenantId);
|
|
10628
11266
|
if (!user) {
|
|
10629
11267
|
throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
|
|
10630
11268
|
}
|
|
10631
|
-
await this.applyPasswordReset(user.id, newPassword);
|
|
11269
|
+
await this.applyPasswordReset(user.id, user.tenantId, newPassword);
|
|
10632
11270
|
}
|
|
10633
11271
|
/**
|
|
10634
11272
|
* VerifiedToken reset path: atomically consumes the verifiedToken from Redis
|
|
@@ -10644,7 +11282,7 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10644
11282
|
throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
|
|
10645
11283
|
}
|
|
10646
11284
|
await this.assertResetTokenStillBound(context);
|
|
10647
|
-
await this.applyPasswordReset(context.userId, newPassword);
|
|
11285
|
+
await this.applyPasswordReset(context.userId, context.tenantId, newPassword);
|
|
10648
11286
|
}
|
|
10649
11287
|
/**
|
|
10650
11288
|
* Hashes the new password and updates it in the user repository.
|
|
@@ -10698,31 +11336,42 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10698
11336
|
* @throws {@link AuthException} `PASSWORD_COMPROMISED` when the new password is refused by
|
|
10699
11337
|
* the configured breach checker.
|
|
10700
11338
|
*/
|
|
10701
|
-
async changePassword(userId, dto, currentRefreshToken) {
|
|
10702
|
-
const user = await this.userRepo.findById(
|
|
11339
|
+
async changePassword(userId, tenantId, dto, currentRefreshToken) {
|
|
11340
|
+
const user = await this.userRepo.findById({
|
|
11341
|
+
id: userId,
|
|
11342
|
+
tenantId
|
|
11343
|
+
});
|
|
10703
11344
|
if (!user?.passwordHash) {
|
|
10704
11345
|
throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
|
|
10705
11346
|
}
|
|
10706
|
-
const bfIdentifier = hmacSha256(`reauth:change-password:${userId}`, this.options.hmacKey);
|
|
11347
|
+
const bfIdentifier = hmacSha256(`reauth:change-password:${userSubject("dashboard", userId, tenantId)}`, this.options.hmacKey);
|
|
10707
11348
|
if (await this.bruteForce.isLockedOut(bfIdentifier)) {
|
|
10708
|
-
this.logger.warn(`changePassword: account locked userId=${userId}`);
|
|
11349
|
+
this.logger.warn(`changePassword: account locked userId=${logSafe(userId)}`);
|
|
10709
11350
|
throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
|
|
10710
11351
|
}
|
|
10711
11352
|
const matches = await this.passwordService.compare(dto.currentPassword, user.passwordHash);
|
|
10712
11353
|
if (!matches) {
|
|
10713
11354
|
await this.bruteForce.recordFailure(bfIdentifier);
|
|
10714
|
-
this.logger.warn(`changePassword: current password rejected userId=${userId}`);
|
|
11355
|
+
this.logger.warn(`changePassword: current password rejected userId=${logSafe(userId)}`);
|
|
10715
11356
|
throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
|
|
10716
11357
|
}
|
|
10717
11358
|
await this.bruteForce.resetFailures(bfIdentifier);
|
|
10718
11359
|
await this.passwordService.assertAcceptable(dto.newPassword, "newPassword");
|
|
10719
11360
|
const passwordHash = await this.passwordService.hash(dto.newPassword);
|
|
10720
|
-
await this.userRepo.updatePassword(
|
|
11361
|
+
await this.userRepo.updatePassword({
|
|
11362
|
+
id: userId,
|
|
11363
|
+
tenantId,
|
|
11364
|
+
passwordHash
|
|
11365
|
+
});
|
|
10721
11366
|
if (currentRefreshToken !== void 0 && currentRefreshToken.length > 0) {
|
|
10722
|
-
await this.sessionService.revokeAllExceptCurrent(
|
|
11367
|
+
await this.sessionService.revokeAllExceptCurrent({
|
|
11368
|
+
userId,
|
|
11369
|
+
tenantId: user.tenantId,
|
|
11370
|
+
currentSessionHash: sha256(currentRefreshToken)
|
|
11371
|
+
});
|
|
10723
11372
|
} else {
|
|
10724
|
-
await this.redis.invalidateUserSessions(userId);
|
|
10725
|
-
await this.redis.bumpUserTokenEpoch(userId);
|
|
11373
|
+
await this.redis.invalidateUserSessions(userId, user.tenantId, "dashboard");
|
|
11374
|
+
await this.redis.bumpUserTokenEpoch(userId, user.tenantId, "dashboard");
|
|
10726
11375
|
}
|
|
10727
11376
|
await this.notifyPasswordChanged(user);
|
|
10728
11377
|
}
|
|
@@ -10740,9 +11389,17 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10740
11389
|
async notifyPasswordChanged(user) {
|
|
10741
11390
|
const send = this.emailProvider?.sendPasswordChangedNotification;
|
|
10742
11391
|
if (send === void 0) return;
|
|
10743
|
-
|
|
10744
|
-
|
|
10745
|
-
|
|
11392
|
+
const provider = this.emailProvider;
|
|
11393
|
+
const withheld = [
|
|
11394
|
+
user.email
|
|
11395
|
+
];
|
|
11396
|
+
void (async () => {
|
|
11397
|
+
try {
|
|
11398
|
+
await send.call(provider, user.tenantId, user.email);
|
|
11399
|
+
} catch (err) {
|
|
11400
|
+
this.logger.error(safeLogLine(`notifyPasswordChanged: delivery failed for user ${logSafe(user.id)}: ` + describeChannelStatus(err), withheld));
|
|
11401
|
+
}
|
|
11402
|
+
})();
|
|
10746
11403
|
}
|
|
10747
11404
|
/**
|
|
10748
11405
|
* A digest of the account's current password hash, used to bind a reset token to it.
|
|
@@ -10752,8 +11409,11 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10752
11409
|
* local password yields the empty string, which is a value like any other: a token minted
|
|
10753
11410
|
* then is invalidated as soon as one is set.
|
|
10754
11411
|
*/
|
|
10755
|
-
async passwordFingerprintOf(userId) {
|
|
10756
|
-
const user = await this.userRepo.findById(
|
|
11412
|
+
async passwordFingerprintOf(userId, tenantId) {
|
|
11413
|
+
const user = await this.userRepo.findById({
|
|
11414
|
+
id: userId,
|
|
11415
|
+
tenantId
|
|
11416
|
+
});
|
|
10757
11417
|
return user?.passwordHash ? sha256(user.passwordHash) : "";
|
|
10758
11418
|
}
|
|
10759
11419
|
/**
|
|
@@ -10771,21 +11431,28 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10771
11431
|
*/
|
|
10772
11432
|
async assertResetTokenStillBound(context) {
|
|
10773
11433
|
if (context.passwordFingerprint === "") return;
|
|
10774
|
-
if (context.passwordFingerprint === await this.passwordFingerprintOf(context.userId)) return;
|
|
10775
|
-
this.logger.warn(`reset: refusing a token issued against a password that has since changed userId=${context.userId}`);
|
|
11434
|
+
if (context.passwordFingerprint === await this.passwordFingerprintOf(context.userId, context.tenantId)) return;
|
|
11435
|
+
this.logger.warn(`reset: refusing a token issued against a password that has since changed userId=${logSafe(context.userId)}`);
|
|
10776
11436
|
throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
|
|
10777
11437
|
}
|
|
10778
|
-
async applyPasswordReset(userId, newPassword) {
|
|
11438
|
+
async applyPasswordReset(userId, tenantId, newPassword) {
|
|
10779
11439
|
const passwordHash = await this.passwordService.hash(newPassword);
|
|
10780
|
-
await this.userRepo.updatePassword(
|
|
10781
|
-
|
|
10782
|
-
|
|
10783
|
-
|
|
11440
|
+
await this.userRepo.updatePassword({
|
|
11441
|
+
id: userId,
|
|
11442
|
+
tenantId,
|
|
11443
|
+
passwordHash
|
|
11444
|
+
});
|
|
11445
|
+
await this.redis.invalidateUserSessions(userId, tenantId, "dashboard");
|
|
11446
|
+
await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
|
|
11447
|
+
const user = await this.userRepo.findById({
|
|
11448
|
+
id: userId,
|
|
11449
|
+
tenantId
|
|
11450
|
+
});
|
|
10784
11451
|
if (user) {
|
|
10785
11452
|
await this.notifyPasswordChanged(user);
|
|
10786
11453
|
if (this.hooks?.afterPasswordReset) {
|
|
10787
11454
|
void Promise.resolve(this.hooks.afterPasswordReset(toSafeUser3(user), createEmptyHookContext())).catch((err) => {
|
|
10788
|
-
this.logger.error(
|
|
11455
|
+
this.logger.error(`afterPasswordReset hook threw: ${describeChannelStatus(err)}`);
|
|
10789
11456
|
});
|
|
10790
11457
|
}
|
|
10791
11458
|
}
|
|
@@ -10808,15 +11475,24 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10808
11475
|
userId,
|
|
10809
11476
|
email,
|
|
10810
11477
|
tenantId,
|
|
10811
|
-
passwordFingerprint: await this.passwordFingerprintOf(userId)
|
|
11478
|
+
passwordFingerprint: await this.passwordFingerprintOf(userId, tenantId)
|
|
10812
11479
|
};
|
|
10813
11480
|
await this.redis.set(tokenKey, JSON.stringify(context), this.options.passwordReset.tokenTtlSeconds);
|
|
10814
|
-
|
|
10815
|
-
|
|
10816
|
-
|
|
10817
|
-
|
|
10818
|
-
})
|
|
10819
|
-
|
|
11481
|
+
const provider = this.emailProvider;
|
|
11482
|
+
void (async () => {
|
|
11483
|
+
try {
|
|
11484
|
+
await provider.sendPasswordResetToken(tenantId, email, rawToken);
|
|
11485
|
+
} catch (err) {
|
|
11486
|
+
const withheld = [
|
|
11487
|
+
rawToken,
|
|
11488
|
+
email
|
|
11489
|
+
];
|
|
11490
|
+
this.logger.error(safeLogLine(`sendPasswordResetToken failed for user ${logSafe(userId)}: ` + describeChannelStatus(err), withheld));
|
|
11491
|
+
void this.redis.del(tokenKey).catch((delErr) => {
|
|
11492
|
+
this.logger.error(`pw_reset rollback delete failed for user ${logSafe(userId)}: ${describeChannelStatus(delErr)}`);
|
|
11493
|
+
});
|
|
11494
|
+
}
|
|
11495
|
+
})();
|
|
10820
11496
|
}
|
|
10821
11497
|
/**
|
|
10822
11498
|
* Generates and stores a password-reset OTP, then sends it to the user's email.
|
|
@@ -10831,9 +11507,18 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10831
11507
|
const identifier = this.otpIdentifier(tenantId, email);
|
|
10832
11508
|
const otp = this.otpService.generate(otpLength);
|
|
10833
11509
|
await this.otpService.store(PASSWORD_RESET_PURPOSE, identifier, otp, otpTtlSeconds);
|
|
10834
|
-
|
|
10835
|
-
|
|
10836
|
-
|
|
11510
|
+
const provider = this.emailProvider;
|
|
11511
|
+
void (async () => {
|
|
11512
|
+
try {
|
|
11513
|
+
await provider.sendPasswordResetOtp(tenantId, email, otp);
|
|
11514
|
+
} catch (err) {
|
|
11515
|
+
const withheld = [
|
|
11516
|
+
otp,
|
|
11517
|
+
email
|
|
11518
|
+
];
|
|
11519
|
+
this.logger.error(safeLogLine(`sendPasswordResetOtp failed for user ${logSafe(redactSecrets(userId, withheld))}: ` + describeChannelStatus(err), withheld));
|
|
11520
|
+
}
|
|
11521
|
+
})();
|
|
10837
11522
|
}
|
|
10838
11523
|
// ---------------------------------------------------------------------------
|
|
10839
11524
|
// Private helpers — misc
|
|
@@ -11021,7 +11706,7 @@ var PasswordResetController = class {
|
|
|
11021
11706
|
*/
|
|
11022
11707
|
async changePassword(user, dto, req) {
|
|
11023
11708
|
const currentRefreshToken = this.tokenDelivery.extractRefreshToken(req);
|
|
11024
|
-
await this.passwordResetService.changePassword(user.sub, dto, currentRefreshToken);
|
|
11709
|
+
await this.passwordResetService.changePassword(user.sub, user.tenantId, dto, currentRefreshToken);
|
|
11025
11710
|
}
|
|
11026
11711
|
// ---------------------------------------------------------------------------
|
|
11027
11712
|
// POST /password/verify-otp
|
|
@@ -11393,7 +12078,7 @@ exports.PlatformAuthService = class _PlatformAuthService {
|
|
|
11393
12078
|
await this.bruteForce.resetFailures(bfIdentifier);
|
|
11394
12079
|
if (admin.mfaEnabled) {
|
|
11395
12080
|
const mfaTempToken = await this.tokenManager.issueMfaTempToken(admin.id, "platform");
|
|
11396
|
-
this.logger.log(`login: MFA challenge issued adminId=${admin.id}`);
|
|
12081
|
+
this.logger.log(`login: MFA challenge issued adminId=${logSafe(admin.id)}`);
|
|
11397
12082
|
return {
|
|
11398
12083
|
mfaRequired: true,
|
|
11399
12084
|
mfaTempToken
|
|
@@ -11401,9 +12086,9 @@ exports.PlatformAuthService = class _PlatformAuthService {
|
|
|
11401
12086
|
}
|
|
11402
12087
|
const { passwordHash: _passwordHash, mfaSecret: _mfaSecret, mfaRecoveryCodes: _mfaRecoveryCodes, ...safeAdmin } = admin;
|
|
11403
12088
|
const result = await this.tokenManager.issuePlatformTokens(safeAdmin, ip, userAgent);
|
|
11404
|
-
this.logger.log(`login: success adminId=${admin.id}`);
|
|
12089
|
+
this.logger.log(`login: success adminId=${logSafe(admin.id)}`);
|
|
11405
12090
|
void this.platformUserRepo.updateLastLogin(admin.id).catch((err) => {
|
|
11406
|
-
this.logger.error(
|
|
12091
|
+
this.logger.error(`updateLastLogin failed: ${describeChannelStatus(err)}`);
|
|
11407
12092
|
});
|
|
11408
12093
|
return result;
|
|
11409
12094
|
}
|
|
@@ -11421,8 +12106,8 @@ exports.PlatformAuthService = class _PlatformAuthService {
|
|
|
11421
12106
|
*/
|
|
11422
12107
|
async logout(accessToken, rawRefreshToken) {
|
|
11423
12108
|
const tokenHash = sha256(rawRefreshToken);
|
|
11424
|
-
const userId = await this.redis.readSessionOwner(`prt:${tokenHash}`);
|
|
11425
|
-
this.logger.log(`logout: adminId=${userId || "(no live session)"}`);
|
|
12109
|
+
const { userId } = await this.redis.readSessionOwner(`prt:${tokenHash}`);
|
|
12110
|
+
this.logger.log(`logout: adminId=${logSafe(userId || "(no live session)")}`);
|
|
11426
12111
|
try {
|
|
11427
12112
|
const payload = this.tokenManager.verifyPlatformIgnoringExpiry(accessToken);
|
|
11428
12113
|
const remainingTtl = payload.exp - Math.floor(Date.now() / 1e3);
|
|
@@ -11434,8 +12119,9 @@ exports.PlatformAuthService = class _PlatformAuthService {
|
|
|
11434
12119
|
await this.redis.del("prt:" + tokenHash);
|
|
11435
12120
|
await this.redis.del("prp:" + tokenHash);
|
|
11436
12121
|
if (userId) {
|
|
11437
|
-
|
|
11438
|
-
await this.redis.srem(
|
|
12122
|
+
const index = sessionIndexKey("platform", userId, this.options.hmacKey, void 0);
|
|
12123
|
+
await this.redis.srem(index, "prt:" + tokenHash);
|
|
12124
|
+
await this.redis.srem(index, "prp:" + tokenHash);
|
|
11439
12125
|
}
|
|
11440
12126
|
await this.redis.del("psd:" + tokenHash);
|
|
11441
12127
|
return userId;
|
|
@@ -11528,7 +12214,7 @@ exports.PlatformAuthService = class _PlatformAuthService {
|
|
|
11528
12214
|
* Revokes all active platform sessions for the given admin.
|
|
11529
12215
|
*
|
|
11530
12216
|
* Delegates to {@link AuthRedisService.invalidateUserSessions} which uses an atomic
|
|
11531
|
-
* Lua script to read the
|
|
12217
|
+
* Lua script to read the platform index SET, delete all session and grace-pointer
|
|
11532
12218
|
* keys, and remove the SET itself in a single Redis round-trip. This prevents the
|
|
11533
12219
|
* TOCTOU race that would arise from a non-atomic SMEMBERS + loop + DEL approach.
|
|
11534
12220
|
*
|
|
@@ -11542,8 +12228,8 @@ exports.PlatformAuthService = class _PlatformAuthService {
|
|
|
11542
12228
|
* @param userId - The platform admin's internal ID.
|
|
11543
12229
|
*/
|
|
11544
12230
|
async revokeAllPlatformSessions(userId) {
|
|
11545
|
-
await this.redis.invalidateUserSessions(userId, "platform");
|
|
11546
|
-
await this.redis.bumpUserTokenEpoch(userId, "platform");
|
|
12231
|
+
await this.redis.invalidateUserSessions(userId, void 0, "platform");
|
|
12232
|
+
await this.redis.bumpUserTokenEpoch(userId, void 0, "platform");
|
|
11547
12233
|
}
|
|
11548
12234
|
};
|
|
11549
12235
|
exports.PlatformAuthService = _ts_decorate46([
|
|
@@ -12081,7 +12767,11 @@ var SessionController = class {
|
|
|
12081
12767
|
async listSessions(user, req) {
|
|
12082
12768
|
const rawRefresh = this.tokenDelivery.extractRefreshToken(req);
|
|
12083
12769
|
const currentHash = rawRefresh ? sha256(rawRefresh) : void 0;
|
|
12084
|
-
return this.sessionService.listSessions(
|
|
12770
|
+
return this.sessionService.listSessions({
|
|
12771
|
+
userId: user.sub,
|
|
12772
|
+
tenantId: user.tenantId,
|
|
12773
|
+
currentSessionHash: currentHash
|
|
12774
|
+
});
|
|
12085
12775
|
}
|
|
12086
12776
|
// ---------------------------------------------------------------------------
|
|
12087
12777
|
// POST /sessions/revoke-all
|
|
@@ -12114,7 +12804,11 @@ var SessionController = class {
|
|
|
12114
12804
|
throw new AuthException(AUTH_ERROR_CODES.SESSION_NOT_FOUND);
|
|
12115
12805
|
}
|
|
12116
12806
|
const currentHash = sha256(rawRefresh);
|
|
12117
|
-
await this.sessionService.revokeAllExceptCurrent(
|
|
12807
|
+
await this.sessionService.revokeAllExceptCurrent({
|
|
12808
|
+
userId: user.sub,
|
|
12809
|
+
tenantId: user.tenantId,
|
|
12810
|
+
currentSessionHash: currentHash
|
|
12811
|
+
});
|
|
12118
12812
|
}
|
|
12119
12813
|
// ---------------------------------------------------------------------------
|
|
12120
12814
|
// DELETE /sessions/:id
|
|
@@ -12129,12 +12823,19 @@ var SessionController = class {
|
|
|
12129
12823
|
*
|
|
12130
12824
|
* @param user - Verified JWT payload from the access token.
|
|
12131
12825
|
* @param id - Full SHA-256 session hash from the `sessionHash` field of `SessionInfo`.
|
|
12132
|
-
* @throws {@link AuthException} `
|
|
12133
|
-
*
|
|
12826
|
+
* @throws {@link AuthException} `VALIDATION` when the value is not 64 lowercase hex characters
|
|
12827
|
+
* — which is what the 8-character display `id` is, so passing that is a caller error rather
|
|
12828
|
+
* than a missing session.
|
|
12829
|
+
* @throws {@link AuthException} `SESSION_NOT_FOUND` when the hash is well formed but names no
|
|
12830
|
+
* session belonging to this user.
|
|
12134
12831
|
* @returns 204 No Content on success.
|
|
12135
12832
|
*/
|
|
12136
12833
|
async revokeSession(user, id) {
|
|
12137
|
-
await this.sessionService.revokeOtherSession(
|
|
12834
|
+
await this.sessionService.revokeOtherSession({
|
|
12835
|
+
userId: user.sub,
|
|
12836
|
+
tenantId: user.tenantId,
|
|
12837
|
+
sessionHash: id
|
|
12838
|
+
});
|
|
12138
12839
|
}
|
|
12139
12840
|
};
|
|
12140
12841
|
_ts_decorate49([
|
|
@@ -12647,10 +13348,14 @@ exports.OAuthService = class _OAuthService {
|
|
|
12647
13348
|
const tokenResponse = await plugin.exchangeCode(code, codeVerifier);
|
|
12648
13349
|
profile = await plugin.fetchProfile(tokenResponse.access_token);
|
|
12649
13350
|
} catch (err) {
|
|
12650
|
-
this.logger.error(`OAuth plugin '${provider}' failed during code exchange or profile fetch
|
|
13351
|
+
this.logger.error(`OAuth plugin '${provider}' failed during code exchange or profile fetch: ` + describeChannelStatus(err));
|
|
12651
13352
|
throw new AuthException(AUTH_ERROR_CODES.OAUTH_FAILED);
|
|
12652
13353
|
}
|
|
12653
|
-
const existingAuthUser = await this.userRepo.findByOAuthId(
|
|
13354
|
+
const existingAuthUser = await this.userRepo.findByOAuthId({
|
|
13355
|
+
provider,
|
|
13356
|
+
providerId: profile.providerId,
|
|
13357
|
+
tenantId
|
|
13358
|
+
});
|
|
12654
13359
|
const existingUser = existingAuthUser ? toSafeUser4(existingAuthUser) : null;
|
|
12655
13360
|
const hookContext = {
|
|
12656
13361
|
tenantId,
|
|
@@ -12667,8 +13372,11 @@ exports.OAuthService = class _OAuthService {
|
|
|
12667
13372
|
switch (hookResult.action) {
|
|
12668
13373
|
case "create": {
|
|
12669
13374
|
const derivedName = profile.name ?? profile.email.split("@")[0] ?? profile.email;
|
|
12670
|
-
if (await this.userRepo.findByEmail(
|
|
12671
|
-
|
|
13375
|
+
if (await this.userRepo.findByEmail({
|
|
13376
|
+
email: profile.email,
|
|
13377
|
+
tenantId
|
|
13378
|
+
})) {
|
|
13379
|
+
this.logger.warn(`oauth: create refused \u2014 ${maskEmail(profile.email)} already exists in tenant ${logSafe(tenantId)}`);
|
|
12672
13380
|
throw new AuthException(AUTH_ERROR_CODES.OAUTH_EMAIL_MISMATCH);
|
|
12673
13381
|
}
|
|
12674
13382
|
authUser = await this.userRepo.createWithOAuth({
|
|
@@ -12689,8 +13397,16 @@ exports.OAuthService = class _OAuthService {
|
|
|
12689
13397
|
if (!existingAuthUser) {
|
|
12690
13398
|
throw new AuthException(AUTH_ERROR_CODES.OAUTH_FAILED);
|
|
12691
13399
|
}
|
|
12692
|
-
await this.userRepo.linkOAuth(
|
|
12693
|
-
|
|
13400
|
+
await this.userRepo.linkOAuth({
|
|
13401
|
+
id: existingAuthUser.id,
|
|
13402
|
+
tenantId: existingAuthUser.tenantId,
|
|
13403
|
+
provider,
|
|
13404
|
+
providerId: profile.providerId
|
|
13405
|
+
});
|
|
13406
|
+
const linked = await this.userRepo.findById({
|
|
13407
|
+
id: existingAuthUser.id,
|
|
13408
|
+
tenantId: existingAuthUser.tenantId
|
|
13409
|
+
});
|
|
12694
13410
|
if (!linked) {
|
|
12695
13411
|
throw new AuthException(AUTH_ERROR_CODES.OAUTH_FAILED);
|
|
12696
13412
|
}
|
|
@@ -12708,7 +13424,7 @@ exports.OAuthService = class _OAuthService {
|
|
|
12708
13424
|
}
|
|
12709
13425
|
if (authUser.mfaEnabled) {
|
|
12710
13426
|
const mfaTempToken = await this.tokenManager.issueMfaTempToken(authUser.id, "dashboard", authUser.tenantId);
|
|
12711
|
-
this.logger.log(`handleCallback: OAuth MFA challenge issued provider=${provider} userId=${authUser.id} tenantId=${logSafe(tenantId)} action=${hookResult.action}`);
|
|
13427
|
+
this.logger.log(`handleCallback: OAuth MFA challenge issued provider=${provider} userId=${logSafe(authUser.id)} tenantId=${logSafe(tenantId)} action=${hookResult.action}`);
|
|
12712
13428
|
return {
|
|
12713
13429
|
mfaRequired: true,
|
|
12714
13430
|
mfaTempToken
|
|
@@ -12717,9 +13433,15 @@ exports.OAuthService = class _OAuthService {
|
|
|
12717
13433
|
const safeUser = toSafeUser4(authUser);
|
|
12718
13434
|
const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
|
|
12719
13435
|
if (this.options.sessions.enabled) {
|
|
12720
|
-
await this.sessionService.createSession(
|
|
13436
|
+
await this.sessionService.createSession({
|
|
13437
|
+
userId: safeUser.id,
|
|
13438
|
+
tenantId: safeUser.tenantId,
|
|
13439
|
+
rawRefreshToken: result.rawRefreshToken,
|
|
13440
|
+
ip,
|
|
13441
|
+
userAgent
|
|
13442
|
+
});
|
|
12721
13443
|
}
|
|
12722
|
-
this.logger.log(`handleCallback: OAuth login success provider=${provider} userId=${safeUser.id} tenantId=${logSafe(tenantId)} action=${hookResult.action}`);
|
|
13444
|
+
this.logger.log(`handleCallback: OAuth login success provider=${provider} userId=${logSafe(safeUser.id)} tenantId=${logSafe(tenantId)} action=${hookResult.action}`);
|
|
12723
13445
|
return result;
|
|
12724
13446
|
}
|
|
12725
13447
|
// ---------------------------------------------------------------------------
|
|
@@ -13527,6 +14249,14 @@ var AUTH_SECURITY_SCHEMES = {
|
|
|
13527
14249
|
refreshCookie: "bymaxAuthRefreshCookie",
|
|
13528
14250
|
platformBearer: "bymaxPlatformAccessBearer"
|
|
13529
14251
|
};
|
|
14252
|
+
function deliversCookie(tokenDelivery) {
|
|
14253
|
+
return tokenDelivery === "cookie" || tokenDelivery === "both";
|
|
14254
|
+
}
|
|
14255
|
+
__name(deliversCookie, "deliversCookie");
|
|
14256
|
+
function deliversBearer(tokenDelivery) {
|
|
14257
|
+
return tokenDelivery === "bearer" || tokenDelivery === "both";
|
|
14258
|
+
}
|
|
14259
|
+
__name(deliversBearer, "deliversBearer");
|
|
13530
14260
|
var OPERATIONS = {
|
|
13531
14261
|
auth: {
|
|
13532
14262
|
"AuthController.register": "none",
|
|
@@ -13685,13 +14415,13 @@ var PLATFORM_REFRESH_BODY = {
|
|
|
13685
14415
|
}
|
|
13686
14416
|
};
|
|
13687
14417
|
function buildAuthOpenApiFragment(options, registered) {
|
|
13688
|
-
const cookieDelivery = options.tokenDelivery
|
|
13689
|
-
const bearerDelivery = options.tokenDelivery
|
|
14418
|
+
const cookieDelivery = deliversCookie(options.tokenDelivery);
|
|
14419
|
+
const bearerDelivery = deliversBearer(options.tokenDelivery);
|
|
13690
14420
|
const operations = {};
|
|
13691
14421
|
for (const [controller, handlers] of Object.entries(OPERATIONS)) {
|
|
13692
14422
|
if (!registered[controller]) continue;
|
|
13693
14423
|
for (const [handler, credential] of Object.entries(handlers)) {
|
|
13694
|
-
const described =
|
|
14424
|
+
const described = describe2(credential, cookieDelivery, bearerDelivery);
|
|
13695
14425
|
const note = OPERATION_DESCRIPTIONS.get(handler);
|
|
13696
14426
|
operations[handler] = note === void 0 ? described : {
|
|
13697
14427
|
...described,
|
|
@@ -13708,7 +14438,7 @@ function buildAuthOpenApiFragment(options, registered) {
|
|
|
13708
14438
|
};
|
|
13709
14439
|
}
|
|
13710
14440
|
__name(buildAuthOpenApiFragment, "buildAuthOpenApiFragment");
|
|
13711
|
-
function
|
|
14441
|
+
function describe2(credential, cookieDelivery, bearerDelivery) {
|
|
13712
14442
|
switch (credential) {
|
|
13713
14443
|
case "none":
|
|
13714
14444
|
return {
|
|
@@ -13778,7 +14508,7 @@ function describe(credential, cookieDelivery, bearerDelivery) {
|
|
|
13778
14508
|
};
|
|
13779
14509
|
}
|
|
13780
14510
|
}
|
|
13781
|
-
__name(
|
|
14511
|
+
__name(describe2, "describe");
|
|
13782
14512
|
function describeTwoCredentials(credential, cookieDelivery, bearerDelivery) {
|
|
13783
14513
|
const required = {
|
|
13784
14514
|
access: credential !== "optionalAccessAndRefresh",
|
|
@@ -14650,6 +15380,54 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
|
|
|
14650
15380
|
exports.BymaxAuthModule = _ts_decorate62([
|
|
14651
15381
|
common.Module({})
|
|
14652
15382
|
], exports.BymaxAuthModule);
|
|
15383
|
+
|
|
15384
|
+
// src/server/openapi/document-security.ts
|
|
15385
|
+
var NO_SCOPES = Object.freeze([]);
|
|
15386
|
+
function requirementFor(scheme) {
|
|
15387
|
+
return Object.freeze({
|
|
15388
|
+
[scheme]: NO_SCOPES
|
|
15389
|
+
});
|
|
15390
|
+
}
|
|
15391
|
+
__name(requirementFor, "requirementFor");
|
|
15392
|
+
function authDocumentSecurity({ guard, tokenDelivery }) {
|
|
15393
|
+
if (guard === "platform") {
|
|
15394
|
+
return Object.freeze([
|
|
15395
|
+
requirementFor(AUTH_SECURITY_SCHEMES.platformBearer)
|
|
15396
|
+
]);
|
|
15397
|
+
}
|
|
15398
|
+
const delivery = tokenDelivery ?? DEFAULT_OPTIONS.tokenDelivery;
|
|
15399
|
+
const schemes = [
|
|
15400
|
+
...deliversCookie(delivery) ? [
|
|
15401
|
+
AUTH_SECURITY_SCHEMES.accessCookie
|
|
15402
|
+
] : [],
|
|
15403
|
+
...deliversBearer(delivery) ? [
|
|
15404
|
+
AUTH_SECURITY_SCHEMES.accessBearer
|
|
15405
|
+
] : []
|
|
15406
|
+
];
|
|
15407
|
+
return Object.freeze(schemes.map(requirementFor));
|
|
15408
|
+
}
|
|
15409
|
+
__name(authDocumentSecurity, "authDocumentSecurity");
|
|
15410
|
+
var AUTH_EMAIL_KINDS = [
|
|
15411
|
+
"passwordResetToken",
|
|
15412
|
+
"passwordResetOtp",
|
|
15413
|
+
"emailVerificationOtp",
|
|
15414
|
+
"passwordChanged",
|
|
15415
|
+
"emailChangeVerification",
|
|
15416
|
+
"emailChanged",
|
|
15417
|
+
"mfaEnabled",
|
|
15418
|
+
"mfaDisabled",
|
|
15419
|
+
"newSessionAlert",
|
|
15420
|
+
"invitation"
|
|
15421
|
+
];
|
|
15422
|
+
Object.freeze(AUTH_EMAIL_KINDS);
|
|
15423
|
+
var CREDENTIAL_BEARING_KINDS = /* @__PURE__ */ new Set([
|
|
15424
|
+
"passwordResetToken",
|
|
15425
|
+
"passwordResetOtp",
|
|
15426
|
+
"emailVerificationOtp",
|
|
15427
|
+
"emailChangeVerification",
|
|
15428
|
+
"invitation"
|
|
15429
|
+
]);
|
|
15430
|
+
var KNOWN_EMAIL_KINDS = new Set(AUTH_EMAIL_KINDS);
|
|
14653
15431
|
var CODE_VALIDITY_TEXT = "It expires shortly, so use it soon.";
|
|
14654
15432
|
var UNEXPECTED_CHANGE_TEXT = "If this was not you, secure your account immediately: change your password and sign out of every session.";
|
|
14655
15433
|
var DEFAULT_MESSAGES = {
|
|
@@ -14751,8 +15529,16 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
|
|
|
14751
15529
|
logger = new common.Logger(_DefaultAuthEmailProvider.name);
|
|
14752
15530
|
/** The copy in effect: the defaults, with any provided overrides layered on top. */
|
|
14753
15531
|
messages;
|
|
14754
|
-
/**
|
|
14755
|
-
|
|
15532
|
+
/**
|
|
15533
|
+
* The resolved per-message policy.
|
|
15534
|
+
*
|
|
15535
|
+
* A `Map`, not the plain object the option accepts. An object lookup walks the prototype chain,
|
|
15536
|
+
* so `policy['toString']` answers with a function rather than `undefined` — unreachable here,
|
|
15537
|
+
* because the key is a closed union of ten literals this file writes, but "the key cannot be
|
|
15538
|
+
* dangerous" is a property of today's call sites and not of the lookup. A `Map` has no prototype
|
|
15539
|
+
* chain to walk, which makes it a property of the data structure instead.
|
|
15540
|
+
*/
|
|
15541
|
+
deliveryErrorPolicy;
|
|
14756
15542
|
/**
|
|
14757
15543
|
* @param sink - The delivery channel to send through.
|
|
14758
15544
|
* @param options - Optional copy overrides and delivery-error policy.
|
|
@@ -14763,41 +15549,62 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
|
|
|
14763
15549
|
...DEFAULT_MESSAGES,
|
|
14764
15550
|
...options?.messages
|
|
14765
15551
|
};
|
|
14766
|
-
|
|
15552
|
+
const configured = options?.onDeliveryError;
|
|
15553
|
+
this.deliveryErrorPolicy = new Map(typeof configured === "string" ? AUTH_EMAIL_KINDS.map((kind) => [
|
|
15554
|
+
kind,
|
|
15555
|
+
configured
|
|
15556
|
+
]) : (
|
|
15557
|
+
// `Object.entries` yields own enumerable properties only, so an inherited `toString` is
|
|
15558
|
+
// not reachable by construction rather than by a guard someone has to remember.
|
|
15559
|
+
//
|
|
15560
|
+
// A key the catalogue does not know is dropped, and the direction of that is deliberate:
|
|
15561
|
+
// a typo leaves the message on `'swallow'`, which is the safe value. A deployment gets
|
|
15562
|
+
// less throwing than it meant, never more exposure. TypeScript rejects the typo outright;
|
|
15563
|
+
// this is what happens to a JavaScript caller.
|
|
15564
|
+
Object.entries(configured ?? {}).filter(
|
|
15565
|
+
// The KEY is checked and nothing else. Filtering `undefined` values out as well was
|
|
15566
|
+
// tried and is dead code: a `Map` holding `[key, undefined]` and a `Map` without the
|
|
15567
|
+
// key both answer `undefined`, so no test can tell them apart — which the mutation
|
|
15568
|
+
// gate said, three times over. The value type is the one `Object.entries` gives for a
|
|
15569
|
+
// `Partial<Record<…>>`, so the predicate asserts nothing the compiler has not already
|
|
15570
|
+
// concluded; what it narrows is the key, and that IS checked.
|
|
15571
|
+
(entry) => KNOWN_EMAIL_KINDS.has(entry[0])
|
|
15572
|
+
)
|
|
15573
|
+
));
|
|
14767
15574
|
}
|
|
14768
15575
|
/** @inheritdoc */
|
|
14769
15576
|
async sendPasswordResetToken(tenantId, email, token, locale) {
|
|
14770
15577
|
await this.deliver(tenantId, email, this.messages.passwordResetToken({
|
|
14771
15578
|
token,
|
|
14772
15579
|
locale
|
|
14773
|
-
}));
|
|
15580
|
+
}), "passwordResetToken");
|
|
14774
15581
|
}
|
|
14775
15582
|
/** @inheritdoc */
|
|
14776
15583
|
async sendPasswordResetOtp(tenantId, email, otp, locale) {
|
|
14777
15584
|
await this.deliver(tenantId, email, this.messages.passwordResetOtp({
|
|
14778
15585
|
otp,
|
|
14779
15586
|
locale
|
|
14780
|
-
}));
|
|
15587
|
+
}), "passwordResetOtp");
|
|
14781
15588
|
}
|
|
14782
15589
|
/** @inheritdoc */
|
|
14783
15590
|
async sendEmailVerificationOtp(tenantId, email, otp, locale) {
|
|
14784
15591
|
await this.deliver(tenantId, email, this.messages.emailVerificationOtp({
|
|
14785
15592
|
otp,
|
|
14786
15593
|
locale
|
|
14787
|
-
}));
|
|
15594
|
+
}), "emailVerificationOtp");
|
|
14788
15595
|
}
|
|
14789
15596
|
/** @inheritdoc */
|
|
14790
15597
|
async sendPasswordChangedNotification(tenantId, email, locale) {
|
|
14791
15598
|
await this.deliver(tenantId, email, this.messages.passwordChanged({
|
|
14792
15599
|
locale
|
|
14793
|
-
}));
|
|
15600
|
+
}), "passwordChanged");
|
|
14794
15601
|
}
|
|
14795
15602
|
/** @inheritdoc */
|
|
14796
15603
|
async sendEmailChangeVerification(tenantId, newEmail, token, locale) {
|
|
14797
15604
|
await this.deliver(tenantId, newEmail, this.messages.emailChangeVerification({
|
|
14798
15605
|
token,
|
|
14799
15606
|
locale
|
|
14800
|
-
}));
|
|
15607
|
+
}), "emailChangeVerification");
|
|
14801
15608
|
}
|
|
14802
15609
|
/** @inheritdoc */
|
|
14803
15610
|
async sendEmailChangedNotification(tenantId, oldEmail, newEmail, locale) {
|
|
@@ -14805,33 +15612,33 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
|
|
|
14805
15612
|
oldEmail,
|
|
14806
15613
|
newEmail,
|
|
14807
15614
|
locale
|
|
14808
|
-
}));
|
|
15615
|
+
}), "emailChanged");
|
|
14809
15616
|
}
|
|
14810
15617
|
/** @inheritdoc */
|
|
14811
15618
|
async sendMfaEnabledNotification(tenantId, email, locale) {
|
|
14812
15619
|
await this.deliver(tenantId, email, this.messages.mfaEnabled({
|
|
14813
15620
|
locale
|
|
14814
|
-
}));
|
|
15621
|
+
}), "mfaEnabled");
|
|
14815
15622
|
}
|
|
14816
15623
|
/** @inheritdoc */
|
|
14817
15624
|
async sendMfaDisabledNotification(tenantId, email, locale) {
|
|
14818
15625
|
await this.deliver(tenantId, email, this.messages.mfaDisabled({
|
|
14819
15626
|
locale
|
|
14820
|
-
}));
|
|
15627
|
+
}), "mfaDisabled");
|
|
14821
15628
|
}
|
|
14822
15629
|
/** @inheritdoc */
|
|
14823
15630
|
async sendNewSessionAlert(tenantId, email, sessionInfo, locale) {
|
|
14824
15631
|
await this.deliver(tenantId, email, this.messages.newSessionAlert({
|
|
14825
15632
|
sessionInfo,
|
|
14826
15633
|
locale
|
|
14827
|
-
}));
|
|
15634
|
+
}), "newSessionAlert");
|
|
14828
15635
|
}
|
|
14829
15636
|
/** @inheritdoc */
|
|
14830
15637
|
async sendInvitation(tenantId, email, inviteData, locale) {
|
|
14831
15638
|
await this.deliver(tenantId, email, this.messages.invitation({
|
|
14832
15639
|
invite: inviteData,
|
|
14833
15640
|
locale
|
|
14834
|
-
}));
|
|
15641
|
+
}), "invitation");
|
|
14835
15642
|
}
|
|
14836
15643
|
/**
|
|
14837
15644
|
* Renders the body to HTML (unless the message already carries its own), hands the message to the
|
|
@@ -14840,8 +15647,15 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
|
|
|
14840
15647
|
* @param tenantId - Tenant the message is attributed to.
|
|
14841
15648
|
* @param to - Recipient address.
|
|
14842
15649
|
* @param message - The rendered subject and body, and optionally its own HTML.
|
|
14843
|
-
|
|
14844
|
-
|
|
15650
|
+
* @param label - Which message this is, as a fixed name this file owns. It goes in the log line
|
|
15651
|
+
* in place of the rendered SUBJECT, and the substitution is the point: a subject comes from
|
|
15652
|
+
* the `messages` catalogue, which a consumer may override, so logging it publishes a string
|
|
15653
|
+
* this library did not write. Redacting it is not enough — a renderer that TRANSFORMS a value
|
|
15654
|
+
* defeats a substring match, and `Code 123-456` for the OTP `123456` is a reasonable-looking
|
|
15655
|
+
* thing to write. The label carries the same information for an operator, identifies the
|
|
15656
|
+
* message more stably for a log parser, and cannot carry anything at all.
|
|
15657
|
+
*/
|
|
15658
|
+
async deliver(tenantId, to, message, label) {
|
|
14845
15659
|
const subject = sanitizeSubject(message.subject);
|
|
14846
15660
|
try {
|
|
14847
15661
|
await this.sink.send({
|
|
@@ -14849,11 +15663,23 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
|
|
|
14849
15663
|
to,
|
|
14850
15664
|
subject,
|
|
14851
15665
|
html: message.html ?? toHtml(message.text),
|
|
14852
|
-
text: message.text
|
|
15666
|
+
text: message.text,
|
|
15667
|
+
kind: label,
|
|
15668
|
+
// Stated at the only moment a sink could act on it. Whether it DOES is the sink's to
|
|
15669
|
+
// answer — see the field's own documentation for why this is a statement of fact rather
|
|
15670
|
+
// than a control, and why it is a flag rather than a list of values to redact.
|
|
15671
|
+
//
|
|
15672
|
+
// OR-ed rather than taken from either side alone, and the direction matters. The kind is
|
|
15673
|
+
// the baseline a renderer cannot weaken, so an override returning `false` on
|
|
15674
|
+
// `passwordResetOtp` changes nothing. The rendering can only ADD, which is the case the
|
|
15675
|
+
// kind cannot see: `options.messages` replaces a renderer outright, so a product whose
|
|
15676
|
+
// own `mfaEnabled` copy includes recovery codes has made a notice credential-bearing
|
|
15677
|
+
// while its kind still reads `mfaEnabled`.
|
|
15678
|
+
containsCredential: CREDENTIAL_BEARING_KINDS.has(label) || message.containsCredential === true
|
|
14853
15679
|
});
|
|
14854
15680
|
} catch (error) {
|
|
14855
|
-
this.logger.error(`delivery failed
|
|
14856
|
-
if (this.
|
|
15681
|
+
this.logger.error(`delivery failed sending ${label}: ${describeChannelStatus(error)}`);
|
|
15682
|
+
if (this.deliveryErrorPolicy.get(label) === "rethrow") {
|
|
14857
15683
|
throw error;
|
|
14858
15684
|
}
|
|
14859
15685
|
}
|
|
@@ -15237,7 +16063,7 @@ exports.AuthExceptionFilter = class _AuthExceptionFilter {
|
|
|
15237
16063
|
});
|
|
15238
16064
|
return;
|
|
15239
16065
|
}
|
|
15240
|
-
this.logger.error(
|
|
16066
|
+
this.logger.error(`unhandled exception: ${describeChannelStatus(exception)}`);
|
|
15241
16067
|
res.status(common.HttpStatus.INTERNAL_SERVER_ERROR).json({
|
|
15242
16068
|
error: {
|
|
15243
16069
|
code: AUTH_ERROR_CODES.INTERNAL,
|
|
@@ -15306,16 +16132,18 @@ exports.WsAuthExceptionFilter = class _WsAuthExceptionFilter {
|
|
|
15306
16132
|
client.emit("exception", payload);
|
|
15307
16133
|
return;
|
|
15308
16134
|
}
|
|
15309
|
-
this.logger.error(
|
|
16135
|
+
this.logger.error(`refused a request on a client this filter cannot answer: ${describeChannelStatus(exception)}`);
|
|
15310
16136
|
}
|
|
15311
16137
|
};
|
|
15312
16138
|
exports.WsAuthExceptionFilter = _ts_decorate68([
|
|
15313
16139
|
common.Catch(AuthException)
|
|
15314
16140
|
], exports.WsAuthExceptionFilter);
|
|
15315
16141
|
|
|
16142
|
+
exports.AUTH_EMAIL_KINDS = AUTH_EMAIL_KINDS;
|
|
15316
16143
|
exports.AUTH_ERROR_CODES = AUTH_ERROR_CODES;
|
|
15317
16144
|
exports.AUTH_ERROR_MESSAGES = AUTH_ERROR_MESSAGES;
|
|
15318
16145
|
exports.AUTH_ERROR_STATUS = AUTH_ERROR_STATUS;
|
|
16146
|
+
exports.AUTH_SECURITY_SCHEMES = AUTH_SECURITY_SCHEMES;
|
|
15319
16147
|
exports.AUTH_THROTTLE_CONFIGS = AUTH_THROTTLE_CONFIGS;
|
|
15320
16148
|
exports.AcceptInvitationDto = AcceptInvitationDto;
|
|
15321
16149
|
exports.AuthException = AuthException;
|
|
@@ -15354,12 +16182,16 @@ exports.SkipMfa = SkipMfa;
|
|
|
15354
16182
|
exports.VerifyEmailDto = VerifyEmailDto;
|
|
15355
16183
|
exports.VerifyOtpDto = VerifyOtpDto;
|
|
15356
16184
|
exports.WS_TICKET_TTL_SECONDS = WS_TICKET_TTL_SECONDS;
|
|
16185
|
+
exports.authDocumentSecurity = authDocumentSecurity;
|
|
15357
16186
|
exports.createAuthValidationPipe = createAuthValidationPipe;
|
|
15358
16187
|
exports.decrypt = decrypt;
|
|
16188
|
+
exports.describeChannelStatus = describeChannelStatus;
|
|
16189
|
+
exports.describeError = describeError;
|
|
15359
16190
|
exports.encrypt = encrypt;
|
|
15360
16191
|
exports.generateSecureToken = generateSecureToken;
|
|
15361
16192
|
exports.hasRole = hasRole;
|
|
15362
16193
|
exports.hmacSha256 = hmacSha256;
|
|
16194
|
+
exports.redactSecrets = redactSecrets;
|
|
15363
16195
|
exports.reduceToBaseWord = reduceToBaseWord;
|
|
15364
16196
|
exports.sanitizeHeaders = sanitizeHeaders;
|
|
15365
16197
|
exports.sha256 = sha256;
|