@bymax-one/nest-auth 1.4.3 → 1.4.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1195 -1
- package/README.md +405 -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 +1201 -366
- package/dist/server/index.d.cts +948 -131
- package/dist/server/index.d.ts +948 -131
- package/dist/server/index.mjs +1196 -367
- 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;
|
|
@@ -2917,11 +3104,12 @@ function _ts_param3(paramIndex, decorator) {
|
|
|
2917
3104
|
};
|
|
2918
3105
|
}
|
|
2919
3106
|
__name(_ts_param3, "_ts_param");
|
|
2920
|
-
exports.AuthRevocationService = class
|
|
3107
|
+
exports.AuthRevocationService = class _AuthRevocationService {
|
|
2921
3108
|
static {
|
|
2922
3109
|
__name(this, "AuthRevocationService");
|
|
2923
3110
|
}
|
|
2924
3111
|
redis;
|
|
3112
|
+
logger = new common.Logger(_AuthRevocationService.name);
|
|
2925
3113
|
/**
|
|
2926
3114
|
* @param redis - The auth module's Redis service, holding both revocation channels.
|
|
2927
3115
|
*/
|
|
@@ -2934,13 +3122,18 @@ exports.AuthRevocationService = class AuthRevocationService {
|
|
|
2934
3122
|
* @param payload - The verified token's `jti`, `sub` and stamped `epoch`.
|
|
2935
3123
|
* @param kind - Which plane the token belongs to; selects the epoch namespace, defaulting to the
|
|
2936
3124
|
* dashboard plane an ordinary user token uses. The per-token blacklist is shared across planes.
|
|
2937
|
-
* @returns `true` when the token is on the blacklist
|
|
3125
|
+
* @returns `true` when the token is on the blacklist, predates the user's current epoch, or is a
|
|
3126
|
+
* dashboard payload carrying no tenant — the last fails closed without a store read, and warns.
|
|
2938
3127
|
*/
|
|
2939
3128
|
async isAccessTokenRevoked(payload, kind = "dashboard") {
|
|
3129
|
+
if (kind === "dashboard" && (payload.tenantId === void 0 || payload.tenantId === "")) {
|
|
3130
|
+
this.logger.warn(`isAccessTokenRevoked: dashboard token refused without a store read \u2014 the payload carries no tenantId, so its epoch key cannot be named. Forward the tenant from the verified token; a dashboard check missing it fails closed by design`);
|
|
3131
|
+
return true;
|
|
3132
|
+
}
|
|
2940
3133
|
if (await this.redis.get(`rv:${payload.jti}`) !== null) {
|
|
2941
3134
|
return true;
|
|
2942
3135
|
}
|
|
2943
|
-
const epoch = await this.redis.getUserTokenEpoch(payload.sub, kind);
|
|
3136
|
+
const epoch = await this.redis.getUserTokenEpoch(payload.sub, payload.tenantId, kind);
|
|
2944
3137
|
return readStampedEpoch(payload) < epoch;
|
|
2945
3138
|
}
|
|
2946
3139
|
};
|
|
@@ -3549,7 +3742,10 @@ exports.UserStatusGuard = class UserStatusGuard {
|
|
|
3549
3742
|
let status = await this.redis.get(statusKey);
|
|
3550
3743
|
let verified = requireVerified ? await this.redis.get(verifiedKey) : null;
|
|
3551
3744
|
if (status === null || requireVerified && verified === null) {
|
|
3552
|
-
const userRecord = await this.userRepo.findById(
|
|
3745
|
+
const userRecord = await this.userRepo.findById({
|
|
3746
|
+
id: userId,
|
|
3747
|
+
tenantId
|
|
3748
|
+
});
|
|
3553
3749
|
if (!userRecord) {
|
|
3554
3750
|
throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
|
|
3555
3751
|
}
|
|
@@ -4147,7 +4343,12 @@ var PasswordService = class _PasswordService {
|
|
|
4147
4343
|
* documented behaviour, and worst during an incident, when changing the password is the
|
|
4148
4344
|
* urgent thing. A refusal to answer is not evidence against the password.
|
|
4149
4345
|
*
|
|
4150
|
-
* The plaintext is
|
|
4346
|
+
* The plaintext is not passed to the logger, and neither is the checker's ERROR — which is the
|
|
4347
|
+
* part that took a measurement to learn. A breach checker receives the plaintext by contract, so
|
|
4348
|
+
* an error it raises is a place the plaintext can be: an HTTP client that echoes the request it
|
|
4349
|
+
* failed on, a validation error quoting the value it rejected. `logger.error(msg, err)` then
|
|
4350
|
+
* publishes that, plus the stack and whatever properties the client hung on it. Same shape as
|
|
4351
|
+
* the mail-channel leak this library fixed in `DefaultAuthEmailProvider`, one port over.
|
|
4151
4352
|
*
|
|
4152
4353
|
* @param plain - The plaintext password the user is trying to set.
|
|
4153
4354
|
* @throws {@link AuthException} with `PASSWORD_COMPROMISED` when the corpus knows it.
|
|
@@ -4156,8 +4357,8 @@ var PasswordService = class _PasswordService {
|
|
|
4156
4357
|
let breached;
|
|
4157
4358
|
try {
|
|
4158
4359
|
breached = await this.breachChecker.isBreached(plain);
|
|
4159
|
-
} catch
|
|
4160
|
-
this.logger.error("breach check threw; admitting the password (the checker fails open)"
|
|
4360
|
+
} catch {
|
|
4361
|
+
this.logger.error("breach check threw; admitting the password (the checker fails open)");
|
|
4161
4362
|
return;
|
|
4162
4363
|
}
|
|
4163
4364
|
if (breached) {
|
|
@@ -4366,6 +4567,36 @@ exports.SessionService = class _SessionService {
|
|
|
4366
4567
|
// Public API
|
|
4367
4568
|
// ---------------------------------------------------------------------------
|
|
4368
4569
|
/**
|
|
4570
|
+
* Refuses a dashboard tenant that names nothing, at the public boundary.
|
|
4571
|
+
*
|
|
4572
|
+
* Every method on this service takes the tenant as a REQUIRED named field, and all of them are
|
|
4573
|
+
* exported — the object form replaced the positional one precisely so a `string` tenant could
|
|
4574
|
+
* not be transposed with a `string` user id or session hash. Naming it removes the transposition
|
|
4575
|
+
* but not the empty string: a caller can still pass `''`, and that is what this refuses.
|
|
4576
|
+
*
|
|
4577
|
+
* `userSubject` cannot enforce it instead: the rotation scripts must be
|
|
4578
|
+
* called with the empty PLACEHOLDER identity to discover a grace pointer, so the innermost
|
|
4579
|
+
* builder has to stay total, and an empty key in a script's KEYS array is not "no key" — the
|
|
4580
|
+
* `eval` wrapper prefixes it into a real key named `auth:`.
|
|
4581
|
+
*
|
|
4582
|
+
* So the refusal lives here, where a caller can actually be wrong. `''` derived
|
|
4583
|
+
* `dashboard:0::{userId}`, swept and bumped keys nobody writes, and returned normally — a
|
|
4584
|
+
* revocation reported as done while every session and access token it named stayed valid.
|
|
4585
|
+
*
|
|
4586
|
+
* @param tenantId - The tenant supplied by the caller.
|
|
4587
|
+
* @throws {@link AuthException} `VALIDATION` when it is blank.
|
|
4588
|
+
*/
|
|
4589
|
+
assertTenant(tenantId) {
|
|
4590
|
+
if (tenantId === "") {
|
|
4591
|
+
throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
|
|
4592
|
+
{
|
|
4593
|
+
field: "tenantId",
|
|
4594
|
+
message: "tenantId is required to name a session index"
|
|
4595
|
+
}
|
|
4596
|
+
]);
|
|
4597
|
+
}
|
|
4598
|
+
}
|
|
4599
|
+
/**
|
|
4369
4600
|
* Records a new session in Redis and enforces the concurrent session limit.
|
|
4370
4601
|
*
|
|
4371
4602
|
* Stores device and activity metadata under `sd:{hash}` with the same TTL
|
|
@@ -4382,13 +4613,11 @@ exports.SessionService = class _SessionService {
|
|
|
4382
4613
|
* before the SET member is committed, the limit check will see one fewer
|
|
4383
4614
|
* session than actually exists, allowing a permanent extra session.
|
|
4384
4615
|
*
|
|
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.
|
|
4616
|
+
* @param params - See {@link CreateSessionParams}.
|
|
4389
4617
|
* @returns The SHA-256 hash of `rawRefreshToken` used as the session key.
|
|
4390
4618
|
*/
|
|
4391
|
-
async createSession(userId, rawRefreshToken, ip, userAgent) {
|
|
4619
|
+
async createSession({ userId, tenantId, rawRefreshToken, ip, userAgent }) {
|
|
4620
|
+
this.assertTenant(tenantId);
|
|
4392
4621
|
const hash = sha256(rawRefreshToken);
|
|
4393
4622
|
const device = parseUserAgent(userAgent);
|
|
4394
4623
|
const now = Date.now();
|
|
@@ -4402,7 +4631,7 @@ exports.SessionService = class _SessionService {
|
|
|
4402
4631
|
lastActivityAt: now
|
|
4403
4632
|
};
|
|
4404
4633
|
await this.redis.set(`sd:${hash}`, JSON.stringify(detail), ttl);
|
|
4405
|
-
await this.enforceSessionLimit(userId, hash, ip, userAgent);
|
|
4634
|
+
await this.enforceSessionLimit(userId, tenantId, hash, ip, userAgent);
|
|
4406
4635
|
if (this.hooks?.onNewSession) {
|
|
4407
4636
|
const { onNewSession } = this.hooks;
|
|
4408
4637
|
const minimalSessionInfo = {
|
|
@@ -4415,13 +4644,16 @@ exports.SessionService = class _SessionService {
|
|
|
4415
4644
|
userAgent,
|
|
4416
4645
|
sanitizedHeaders: {}
|
|
4417
4646
|
};
|
|
4418
|
-
void this.userRepo.findById(
|
|
4647
|
+
void this.userRepo.findById({
|
|
4648
|
+
id: userId,
|
|
4649
|
+
tenantId
|
|
4650
|
+
}).then((user) => {
|
|
4419
4651
|
if (!user) return;
|
|
4420
4652
|
void Promise.resolve(onNewSession(toSafeUser(user), minimalSessionInfo, context)).catch((err) => {
|
|
4421
|
-
this.logger.error(
|
|
4653
|
+
this.logger.error(`onNewSession hook threw: ${describeChannelStatus(err)}`);
|
|
4422
4654
|
});
|
|
4423
4655
|
}).catch((err) => {
|
|
4424
|
-
this.logger.error(
|
|
4656
|
+
this.logger.error(`onNewSession hook \u2014 findById failed: ${describeChannelStatus(err)}`);
|
|
4425
4657
|
});
|
|
4426
4658
|
}
|
|
4427
4659
|
return hash;
|
|
@@ -4439,16 +4671,15 @@ exports.SessionService = class _SessionService {
|
|
|
4439
4671
|
*
|
|
4440
4672
|
* Results are sorted by `createdAt` descending (newest session first).
|
|
4441
4673
|
*
|
|
4442
|
-
* @param
|
|
4443
|
-
* @param currentSessionHash - Optional SHA-256 hash of the caller's active session;
|
|
4444
|
-
* matched session will have `isCurrent: true`.
|
|
4674
|
+
* @param params - See {@link ListSessionsParams}.
|
|
4445
4675
|
* @returns Array of {@link SessionInfo} sorted newest-first.
|
|
4446
4676
|
*/
|
|
4447
|
-
async listSessions(userId, currentSessionHash) {
|
|
4448
|
-
|
|
4449
|
-
|
|
4677
|
+
async listSessions({ userId, tenantId, currentSessionHash }) {
|
|
4678
|
+
this.assertTenant(tenantId);
|
|
4679
|
+
void this.redis.pruneExpiredGraceMembers(this.indexKey(userId, tenantId), "rp:").catch((err) => {
|
|
4680
|
+
this.logger.warn(`listSessions: grace-pointer prune failed: ${describeChannelStatus(err)}`);
|
|
4450
4681
|
});
|
|
4451
|
-
const members = await this.redis.smembers(
|
|
4682
|
+
const members = await this.redis.smembers(this.indexKey(userId, tenantId));
|
|
4452
4683
|
const rtMembers = members.filter((m) => m.startsWith("rt:"));
|
|
4453
4684
|
const results = [];
|
|
4454
4685
|
const staleKeys = [];
|
|
@@ -4498,8 +4729,8 @@ exports.SessionService = class _SessionService {
|
|
|
4498
4729
|
lastActivityAt: detail.lastActivityAt
|
|
4499
4730
|
});
|
|
4500
4731
|
}));
|
|
4501
|
-
void this.redis.pruneDeadMembers(
|
|
4502
|
-
this.logger.error(`listSessions: failed to prune ${staleKeys.length} dead member(s)
|
|
4732
|
+
void this.redis.pruneDeadMembers(this.indexKey(userId, tenantId), staleKeys).catch((err) => {
|
|
4733
|
+
this.logger.error(`listSessions: failed to prune ${staleKeys.length} dead member(s): ${describeChannelStatus(err)}`);
|
|
4503
4734
|
});
|
|
4504
4735
|
results.sort((a, b) => b.createdAt - a.createdAt);
|
|
4505
4736
|
return results;
|
|
@@ -4516,10 +4747,11 @@ exports.SessionService = class _SessionService {
|
|
|
4516
4747
|
* @param sessionHash - SHA-256 hash of the refresh token identifying the session.
|
|
4517
4748
|
* @throws {@link AuthException} `SESSION_NOT_FOUND` when the session is not owned by the user.
|
|
4518
4749
|
*/
|
|
4519
|
-
async revokeSession(userId, sessionHash) {
|
|
4750
|
+
async revokeSession({ userId, tenantId, sessionHash }) {
|
|
4751
|
+
this.assertTenant(tenantId);
|
|
4520
4752
|
this.assertValidSessionHash(sessionHash);
|
|
4521
4753
|
const result = await this.redis.eval(REVOKE_SESSION_LUA, [
|
|
4522
|
-
|
|
4754
|
+
this.indexKey(userId, tenantId),
|
|
4523
4755
|
`rt:${sessionHash}`,
|
|
4524
4756
|
`sd:${sessionHash}`
|
|
4525
4757
|
], [
|
|
@@ -4554,9 +4786,13 @@ exports.SessionService = class _SessionService {
|
|
|
4554
4786
|
* @param sessionHash - SHA-256 hash of the refresh token identifying the session.
|
|
4555
4787
|
* @throws {@link AuthException} `SESSION_NOT_FOUND` when the session is not owned by the user.
|
|
4556
4788
|
*/
|
|
4557
|
-
async revokeOtherSession(userId, sessionHash) {
|
|
4558
|
-
await this.revokeSession(
|
|
4559
|
-
|
|
4789
|
+
async revokeOtherSession({ userId, tenantId, sessionHash }) {
|
|
4790
|
+
await this.revokeSession({
|
|
4791
|
+
userId,
|
|
4792
|
+
tenantId,
|
|
4793
|
+
sessionHash
|
|
4794
|
+
});
|
|
4795
|
+
await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
|
|
4560
4796
|
}
|
|
4561
4797
|
/**
|
|
4562
4798
|
* Revokes all sessions for a user except the caller's current session.
|
|
@@ -4585,15 +4821,20 @@ exports.SessionService = class _SessionService {
|
|
|
4585
4821
|
* @throws {unknown} Propagates any error thrown by `revokeSession` — including
|
|
4586
4822
|
* {@link AuthException} with various codes, Redis errors, or other runtime errors.
|
|
4587
4823
|
*/
|
|
4588
|
-
async revokeAllExceptCurrent(userId, currentSessionHash) {
|
|
4589
|
-
this.
|
|
4590
|
-
|
|
4824
|
+
async revokeAllExceptCurrent({ userId, tenantId, currentSessionHash }) {
|
|
4825
|
+
this.assertTenant(tenantId);
|
|
4826
|
+
this.assertValidSessionHash(currentSessionHash, "currentSessionHash");
|
|
4827
|
+
const members = await this.redis.smembers(this.indexKey(userId, tenantId));
|
|
4591
4828
|
const rtMembers = members.filter((m) => m.startsWith("rt:"));
|
|
4592
4829
|
for (const member of rtMembers) {
|
|
4593
4830
|
const hash = member.slice(3);
|
|
4594
4831
|
if (timingSafeCompare(hash, currentSessionHash)) continue;
|
|
4595
4832
|
try {
|
|
4596
|
-
await this.revokeSession(
|
|
4833
|
+
await this.revokeSession({
|
|
4834
|
+
userId,
|
|
4835
|
+
tenantId,
|
|
4836
|
+
sessionHash: hash
|
|
4837
|
+
});
|
|
4597
4838
|
} catch (err) {
|
|
4598
4839
|
if (err instanceof AuthException) {
|
|
4599
4840
|
const body = err.getResponse();
|
|
@@ -4605,9 +4846,9 @@ exports.SessionService = class _SessionService {
|
|
|
4605
4846
|
const gracePointers = members.filter((m) => m.startsWith("rp:"));
|
|
4606
4847
|
for (const member of gracePointers) {
|
|
4607
4848
|
await this.redis.del(member);
|
|
4608
|
-
await this.redis.srem(
|
|
4849
|
+
await this.redis.srem(this.indexKey(userId, tenantId), member);
|
|
4609
4850
|
}
|
|
4610
|
-
await this.redis.bumpUserTokenEpoch(userId);
|
|
4851
|
+
await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
|
|
4611
4852
|
}
|
|
4612
4853
|
/**
|
|
4613
4854
|
* Rotates the session detail record from the old token hash to the new one.
|
|
@@ -4630,12 +4871,13 @@ exports.SessionService = class _SessionService {
|
|
|
4630
4871
|
* @param newHash - SHA-256 hex hash of the newly issued refresh token.
|
|
4631
4872
|
* @param ip - Client IP address from the current request.
|
|
4632
4873
|
* @param userAgent - Raw `User-Agent` header value from the current request.
|
|
4633
|
-
* @throws {@link AuthException} `
|
|
4634
|
-
*
|
|
4874
|
+
* @throws {@link AuthException} `VALIDATION` when either hash is not a valid 64-character
|
|
4875
|
+
* lowercase hex string. The `details` name which one — `oldHash` or `newHash` — because a
|
|
4876
|
+
* caller told only that "a hash" was malformed cannot act on it.
|
|
4635
4877
|
*/
|
|
4636
4878
|
async rotateSession(oldHash, newHash, ip, userAgent) {
|
|
4637
|
-
this.assertValidSessionHash(oldHash);
|
|
4638
|
-
this.assertValidSessionHash(newHash);
|
|
4879
|
+
this.assertValidSessionHash(oldHash, "oldHash");
|
|
4880
|
+
this.assertValidSessionHash(newHash, "newHash");
|
|
4639
4881
|
if (timingSafeCompare(oldHash, newHash)) {
|
|
4640
4882
|
return;
|
|
4641
4883
|
}
|
|
@@ -4680,19 +4922,48 @@ exports.SessionService = class _SessionService {
|
|
|
4680
4922
|
* attacker-controlled key names.
|
|
4681
4923
|
*
|
|
4682
4924
|
* @remarks
|
|
4683
|
-
* `SESSION_NOT_FOUND
|
|
4684
|
-
* callers
|
|
4685
|
-
*
|
|
4925
|
+
* **This used to answer `SESSION_NOT_FOUND`, and that was wrong.** The stated reason was to stop
|
|
4926
|
+
* callers enumerating valid hash formats — but the format is not a secret. It is 64 hex
|
|
4927
|
+
* characters, `SessionInfo.sessionHash` publishes it on every listed session, and the route's
|
|
4928
|
+
* own documentation describes it. Nothing is protected by hiding it, and the pairing had a real
|
|
4929
|
+
* cost: a consumer sending a malformed hash got the same answer as one sending a hash that had
|
|
4930
|
+
* already been revoked, so a UI bug read as a race between the session list and the click. That
|
|
4931
|
+
* is measured, not hypothetical — it cost a consumer session twenty minutes chasing a race that
|
|
4932
|
+
* cannot happen.
|
|
4933
|
+
*
|
|
4934
|
+
* A malformed hash is a caller error and now says so. A well-formed hash that names nothing
|
|
4935
|
+
* still answers `SESSION_NOT_FOUND`, which is where the no-enumeration argument does apply:
|
|
4936
|
+
* that one really would tell the caller whether a session exists.
|
|
4686
4937
|
*
|
|
4687
4938
|
* @param sessionHash - The session hash to validate.
|
|
4688
|
-
* @throws {@link AuthException} `
|
|
4939
|
+
* @throws {@link AuthException} `VALIDATION` when the value is not 64 lowercase hex characters.
|
|
4689
4940
|
*/
|
|
4690
|
-
assertValidSessionHash(sessionHash) {
|
|
4941
|
+
assertValidSessionHash(sessionHash, field = "sessionHash") {
|
|
4691
4942
|
if (!SESSION_HASH_RE.test(sessionHash)) {
|
|
4692
|
-
throw new AuthException(AUTH_ERROR_CODES.
|
|
4943
|
+
throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
|
|
4944
|
+
{
|
|
4945
|
+
field,
|
|
4946
|
+
message: `${field} must be 64 lowercase hexadecimal characters`
|
|
4947
|
+
}
|
|
4948
|
+
]);
|
|
4693
4949
|
}
|
|
4694
4950
|
}
|
|
4695
4951
|
/**
|
|
4952
|
+
* The Redis key of this user's session index.
|
|
4953
|
+
*
|
|
4954
|
+
* Derived rather than interpolated, and tenant-scoped: `IUserRepository.findById` takes a
|
|
4955
|
+
* tenant because ids may only be unique within one, so a bare-id index let a revoke aimed at
|
|
4956
|
+
* one tenant's user empty another's. The derivation lives in `user-keys.ts` because rust-auth
|
|
4957
|
+
* reads the same key from the same contract.
|
|
4958
|
+
*
|
|
4959
|
+
* @param userId - The account whose sessions the index tracks.
|
|
4960
|
+
* @param tenantId - The tenant that account belongs to.
|
|
4961
|
+
* @returns The un-namespaced index key.
|
|
4962
|
+
*/
|
|
4963
|
+
indexKey(userId, tenantId) {
|
|
4964
|
+
return sessionIndexKey("dashboard", userId, this.options.hmacKey, tenantId);
|
|
4965
|
+
}
|
|
4966
|
+
/**
|
|
4696
4967
|
* Enforces the concurrent session limit for a user by evicting the oldest
|
|
4697
4968
|
* sessions (FIFO) when the limit has been exceeded.
|
|
4698
4969
|
*
|
|
@@ -4709,15 +4980,16 @@ exports.SessionService = class _SessionService {
|
|
|
4709
4980
|
* risk is low for most `defaultMaxSessions` values (≥ 2).
|
|
4710
4981
|
*
|
|
4711
4982
|
* @param userId - Internal user ID whose session count is being checked.
|
|
4983
|
+
* @param tenantId - The tenant that user belongs to; part of the index key.
|
|
4712
4984
|
* @param newHash - SHA-256 hash of the newly issued refresh token (excluded from eviction).
|
|
4713
4985
|
* @param ip - Client IP address (forwarded to the `onSessionEvicted` hook context).
|
|
4714
4986
|
* @param userAgent - User-Agent string (forwarded to the `onSessionEvicted` hook context).
|
|
4715
4987
|
*/
|
|
4716
|
-
async enforceSessionLimit(userId, newHash, ip, userAgent) {
|
|
4717
|
-
await this.redis.pruneExpiredGraceMembers(
|
|
4718
|
-
const members = await this.redis.smembers(
|
|
4988
|
+
async enforceSessionLimit(userId, tenantId, newHash, ip, userAgent) {
|
|
4989
|
+
await this.redis.pruneExpiredGraceMembers(this.indexKey(userId, tenantId), "rp:");
|
|
4990
|
+
const members = await this.redis.smembers(this.indexKey(userId, tenantId));
|
|
4719
4991
|
const rtMembers = members.filter((m) => m.startsWith("rt:"));
|
|
4720
|
-
const limit = await this.resolveSessionLimit(userId);
|
|
4992
|
+
const limit = await this.resolveSessionLimit(userId, tenantId);
|
|
4721
4993
|
if (rtMembers.length <= limit) return;
|
|
4722
4994
|
const withTimestamps = await Promise.all(rtMembers.map(async (member) => {
|
|
4723
4995
|
const memberHash = member.slice(3);
|
|
@@ -4752,15 +5024,15 @@ exports.SessionService = class _SessionService {
|
|
|
4752
5024
|
for (const entry of toEvict) {
|
|
4753
5025
|
try {
|
|
4754
5026
|
await this.redis.del(`rt:${entry.memberHash}`);
|
|
4755
|
-
await this.redis.srem(
|
|
5027
|
+
await this.redis.srem(this.indexKey(userId, tenantId), entry.member);
|
|
4756
5028
|
await this.redis.del(`sd:${entry.memberHash}`);
|
|
4757
5029
|
} catch (err) {
|
|
4758
|
-
this.logger.error(`enforceSessionLimit: failed to evict session ${entry.memberHash} for user ${userId}
|
|
5030
|
+
this.logger.error(`enforceSessionLimit: failed to evict session ${entry.memberHash} for user ${logSafe(userId)}: ${describeChannelStatus(err)}`);
|
|
4759
5031
|
continue;
|
|
4760
5032
|
}
|
|
4761
5033
|
if (this.hooks?.onSessionEvicted) {
|
|
4762
5034
|
void Promise.resolve(this.hooks.onSessionEvicted(userId, entry.memberHash, context)).catch((err) => {
|
|
4763
|
-
this.logger.error(
|
|
5035
|
+
this.logger.error(`onSessionEvicted hook threw: ${describeChannelStatus(err)}`);
|
|
4764
5036
|
});
|
|
4765
5037
|
}
|
|
4766
5038
|
}
|
|
@@ -4782,24 +5054,28 @@ exports.SessionService = class _SessionService {
|
|
|
4782
5054
|
* *thrown* resolver was ever caught.
|
|
4783
5055
|
*
|
|
4784
5056
|
* @param userId - Internal user ID to resolve the limit for.
|
|
5057
|
+
* @param tenantId - Tenant that user belongs to; scopes the lookup behind the resolver.
|
|
4785
5058
|
* @returns Maximum allowed concurrent sessions for the given user.
|
|
4786
5059
|
*/
|
|
4787
|
-
async resolveSessionLimit(userId) {
|
|
5060
|
+
async resolveSessionLimit(userId, tenantId) {
|
|
4788
5061
|
const { maxSessionsResolver, defaultMaxSessions } = this.options.sessions;
|
|
4789
5062
|
if (!maxSessionsResolver) {
|
|
4790
5063
|
return defaultMaxSessions;
|
|
4791
5064
|
}
|
|
4792
5065
|
try {
|
|
4793
|
-
const user = await this.userRepo.findById(
|
|
5066
|
+
const user = await this.userRepo.findById({
|
|
5067
|
+
id: userId,
|
|
5068
|
+
tenantId
|
|
5069
|
+
});
|
|
4794
5070
|
if (!user) return defaultMaxSessions;
|
|
4795
5071
|
const resolved = await maxSessionsResolver(user);
|
|
4796
5072
|
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.`);
|
|
5073
|
+
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
5074
|
return defaultMaxSessions;
|
|
4799
5075
|
}
|
|
4800
5076
|
return resolved;
|
|
4801
5077
|
} catch (err) {
|
|
4802
|
-
this.logger.error(
|
|
5078
|
+
this.logger.error(`maxSessionsResolver threw \u2014 falling back to defaultMaxSessions: ${describeChannelStatus(err)}`);
|
|
4803
5079
|
return defaultMaxSessions;
|
|
4804
5080
|
}
|
|
4805
5081
|
}
|
|
@@ -4820,25 +5096,19 @@ exports.SessionService = _ts_decorate16([
|
|
|
4820
5096
|
])
|
|
4821
5097
|
], exports.SessionService);
|
|
4822
5098
|
|
|
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
5099
|
// src/server/constants/recent-auth.ts
|
|
4830
5100
|
var RECENT_AUTH_TTL_SECONDS = 300;
|
|
4831
5101
|
function recentAuthKey(plane, userId, hmacKey, tenantId) {
|
|
4832
|
-
return `ra:${hmacSha256(
|
|
5102
|
+
return `ra:${hmacSha256(userSubject(plane, userId, tenantId), hmacKey)}`;
|
|
4833
5103
|
}
|
|
4834
5104
|
__name(recentAuthKey, "recentAuthKey");
|
|
4835
5105
|
|
|
4836
|
-
// src/server/utils/
|
|
4837
|
-
var
|
|
4838
|
-
function
|
|
4839
|
-
return
|
|
5106
|
+
// src/server/utils/owner-fragment.ts
|
|
5107
|
+
var UNKNOWN_OWNER = "userId=<unknown: no live session remains in this family to name it>";
|
|
5108
|
+
function ownerFragment(ownerId) {
|
|
5109
|
+
return ownerId === "" ? UNKNOWN_OWNER : `userId=${logSafe(ownerId)}`;
|
|
4840
5110
|
}
|
|
4841
|
-
__name(
|
|
5111
|
+
__name(ownerFragment, "ownerFragment");
|
|
4842
5112
|
|
|
4843
5113
|
// src/server/services/token-manager.service.ts
|
|
4844
5114
|
function _ts_decorate17(decorators, target, key, desc) {
|
|
@@ -4971,7 +5241,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
4971
5241
|
* @returns Full auth result containing access token, raw refresh token, and user.
|
|
4972
5242
|
*/
|
|
4973
5243
|
async issueTokens(user, ip, userAgent, overrides) {
|
|
4974
|
-
const epoch = await this.redis.getUserTokenEpoch(user.id);
|
|
5244
|
+
const epoch = await this.redis.getUserTokenEpoch(user.id, user.tenantId, "dashboard");
|
|
4975
5245
|
const accessToken = this.issueAccess({
|
|
4976
5246
|
sub: user.id,
|
|
4977
5247
|
tenantId: user.tenantId,
|
|
@@ -4989,6 +5259,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
4989
5259
|
const ttl = this.options.jwt.refreshExpiresInDays * 86400;
|
|
4990
5260
|
await this.redis.writeNewSession({
|
|
4991
5261
|
kind: "dashboard",
|
|
5262
|
+
tenantId: user.tenantId,
|
|
4992
5263
|
tokenHash,
|
|
4993
5264
|
sessionJson: this.serializeSession(session),
|
|
4994
5265
|
familyId,
|
|
@@ -5018,7 +5289,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5018
5289
|
* @returns Platform auth result.
|
|
5019
5290
|
*/
|
|
5020
5291
|
async issuePlatformTokens(admin, ip, userAgent, overrides) {
|
|
5021
|
-
const epoch = await this.redis.getUserTokenEpoch(admin.id, "platform");
|
|
5292
|
+
const epoch = await this.redis.getUserTokenEpoch(admin.id, void 0, "platform");
|
|
5022
5293
|
const accessToken = this.issuePlatformAccess({
|
|
5023
5294
|
sub: admin.id,
|
|
5024
5295
|
role: admin.role,
|
|
@@ -5034,6 +5305,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5034
5305
|
const ttl = this.options.jwt.refreshExpiresInDays * 86400;
|
|
5035
5306
|
await this.redis.writeNewSession({
|
|
5036
5307
|
kind: "platform",
|
|
5308
|
+
tenantId: void 0,
|
|
5037
5309
|
tokenHash,
|
|
5038
5310
|
sessionJson: this.serializeSession(session),
|
|
5039
5311
|
familyId,
|
|
@@ -5112,9 +5384,11 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5112
5384
|
const graceTtl = this.options.jwt.refreshGraceWindowSeconds;
|
|
5113
5385
|
const seed = await this.readSeedSession(`rt:${oldHash}`, ip, userAgent);
|
|
5114
5386
|
this.assertWithinAbsoluteLifetime(seed);
|
|
5387
|
+
this.assertRotatableTenant(seed);
|
|
5115
5388
|
const newSession = this.buildSession(seed.userId, seed.tenantId, seed.role, ip, userAgent, seed.mfaEnabled, seed.familyId, seed.familyCreatedAt);
|
|
5116
5389
|
const outcome = await this.redis.rotateRefreshSession({
|
|
5117
5390
|
kind: "dashboard",
|
|
5391
|
+
tenantId: seed.tenantId,
|
|
5118
5392
|
oldHash,
|
|
5119
5393
|
newHash,
|
|
5120
5394
|
newSessionJson: this.serializeSession(newSession),
|
|
@@ -5132,8 +5406,8 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5132
5406
|
if (outcome.kind === "reused") {
|
|
5133
5407
|
this.logger.warn(`reissueTokens: reuse of a consumed refresh token detected \u2014 revoking the token family familyId=${logSafe(outcome.familyId)}`);
|
|
5134
5408
|
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);
|
|
5409
|
+
this.logger.warn(`reissueTokens: token family revoked after reuse detection ${ownerFragment(ownerId)} familyId=${logSafe(outcome.familyId)}`);
|
|
5410
|
+
this.emitReuseDetected(ownerId, outcome.familyId, ip, userAgent);
|
|
5137
5411
|
throw new AuthException(AUTH_ERROR_CODES.REFRESH_TOKEN_INVALID);
|
|
5138
5412
|
}
|
|
5139
5413
|
this.logger.warn("reissueTokens: no valid session or grace window found \u2014 REFRESH_TOKEN_INVALID");
|
|
@@ -5145,18 +5419,64 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5145
5419
|
* The owner is read from the stored session where it can be — a replay of a token whose live
|
|
5146
5420
|
* key is already gone leaves nothing to read, and the hook is skipped rather than fired with
|
|
5147
5421
|
* an empty identity that a consumer would have to guess about.
|
|
5422
|
+
*
|
|
5423
|
+
* **The context describes WHO PRESENTED the replayed token**, which is the whole reason a
|
|
5424
|
+
* consumer subscribes to this hook. `userId` says whose account the family belongs to; `ip` and
|
|
5425
|
+
* `userAgent` are the only description of the party holding the token that should not exist, so
|
|
5426
|
+
* a report carrying the first and not the second says a compromise happened and gives nothing
|
|
5427
|
+
* to act on. Both were previously dropped: the emit built an EMPTY context while
|
|
5428
|
+
* `reissueTokens` had both values in scope as its own parameters.
|
|
5429
|
+
*
|
|
5430
|
+
* `sanitizedHeaders` stays empty and that is honest — the rotation path receives the address
|
|
5431
|
+
* and the agent, never the header map, so there is nothing to sanitize. Inventing one would be
|
|
5432
|
+
* worse than an empty object a consumer can see is empty.
|
|
5433
|
+
*
|
|
5434
|
+
* @param userId - The account the revoked family belonged to.
|
|
5435
|
+
* @param familyId - The revoked family.
|
|
5436
|
+
* @param ip - Address the replayed token was presented from.
|
|
5437
|
+
* @param userAgent - Raw `User-Agent` of the presenting client.
|
|
5148
5438
|
*/
|
|
5149
|
-
emitReuseDetected(userId, familyId) {
|
|
5439
|
+
emitReuseDetected(userId, familyId, ip, userAgent) {
|
|
5150
5440
|
if (!this.hooks?.onRefreshTokenReuseDetected || userId === "") return;
|
|
5151
5441
|
try {
|
|
5152
5442
|
void Promise.resolve(this.hooks.onRefreshTokenReuseDetected({
|
|
5153
5443
|
userId,
|
|
5154
5444
|
familyId
|
|
5155
|
-
},
|
|
5156
|
-
|
|
5445
|
+
}, {
|
|
5446
|
+
...createEmptyHookContext(),
|
|
5447
|
+
ip,
|
|
5448
|
+
userAgent
|
|
5449
|
+
})).catch((err) => {
|
|
5450
|
+
this.logger.error(`onRefreshTokenReuseDetected hook threw: ${describeChannelStatus(err)}`);
|
|
5157
5451
|
});
|
|
5158
5452
|
} catch (err) {
|
|
5159
|
-
this.logger.error(
|
|
5453
|
+
this.logger.error(`onRefreshTokenReuseDetected hook threw synchronously: ${describeChannelStatus(err)}`);
|
|
5454
|
+
}
|
|
5455
|
+
}
|
|
5456
|
+
/**
|
|
5457
|
+
* Refuses to rotate a dashboard session whose record names no tenant.
|
|
5458
|
+
*
|
|
5459
|
+
* `parseSession` validates `userId`, `role` and `mfaEnabled` but not `tenantId`, so a record
|
|
5460
|
+
* written before the index carried one reaches here with the field absent. Rotating it would do
|
|
5461
|
+
* two wrong things at once: write the new session under `dashboard:9:undefined:{userId}`, an
|
|
5462
|
+
* index belonging to no tenant and swept by no revoke-all, and mint an access token with no
|
|
5463
|
+
* tenant claim — which every dashboard guard then refuses, so the caller gets a session that
|
|
5464
|
+
* cannot be used and cannot be revoked.
|
|
5465
|
+
*
|
|
5466
|
+
* Refusing is the same answer the migration note gives: a pre-upgrade session dies and the user
|
|
5467
|
+
* signs in again. That is a cost; rotating into a keyspace nobody sweeps is a hole.
|
|
5468
|
+
*
|
|
5469
|
+
* The platform plane is exempt — its subject carries no tenant segment by design.
|
|
5470
|
+
*
|
|
5471
|
+
* @param session - The seed session read from the presented token.
|
|
5472
|
+
* @throws {@link AuthException} with `REFRESH_TOKEN_INVALID`, indistinguishable from any other
|
|
5473
|
+
* invalid refresh: the remedy is the same and the difference would only tell a token holder
|
|
5474
|
+
* how old the record is.
|
|
5475
|
+
*/
|
|
5476
|
+
assertRotatableTenant(session) {
|
|
5477
|
+
if (session.userId === "") return;
|
|
5478
|
+
if (session.tenantId === void 0 || session.tenantId === "") {
|
|
5479
|
+
throw new AuthException(AUTH_ERROR_CODES.REFRESH_TOKEN_INVALID);
|
|
5160
5480
|
}
|
|
5161
5481
|
}
|
|
5162
5482
|
/**
|
|
@@ -5240,11 +5560,13 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5240
5560
|
async rotateFromGrace(graceSessionJson, ip, userAgent, refreshTtl) {
|
|
5241
5561
|
const graceSession = this.parseSession(graceSessionJson);
|
|
5242
5562
|
this.assertWithinAbsoluteLifetime(graceSession);
|
|
5563
|
+
this.assertRotatableTenant(graceSession);
|
|
5243
5564
|
const anotherNewRefresh = generateSecureToken();
|
|
5244
5565
|
const anotherNewHash = sha256(anotherNewRefresh);
|
|
5245
5566
|
const anotherSession = this.buildSession(graceSession.userId, graceSession.tenantId, graceSession.role, ip, userAgent, graceSession.mfaEnabled, graceSession.familyId, graceSession.familyCreatedAt);
|
|
5246
5567
|
const written = await this.redis.writeRecoveredSession({
|
|
5247
5568
|
kind: "dashboard",
|
|
5569
|
+
tenantId: graceSession.tenantId,
|
|
5248
5570
|
newHash: anotherNewHash,
|
|
5249
5571
|
newSessionJson: this.serializeSession(anotherSession),
|
|
5250
5572
|
familyId: graceSession.familyId,
|
|
@@ -5361,7 +5683,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5361
5683
|
* of this behaviour and direct users through the MFA challenge flow to re-acquire it.
|
|
5362
5684
|
*/
|
|
5363
5685
|
async buildRotatedResult(session, rawRefreshToken) {
|
|
5364
|
-
const epoch = await this.redis.getUserTokenEpoch(session.userId);
|
|
5686
|
+
const epoch = await this.redis.getUserTokenEpoch(session.userId, session.tenantId, "dashboard");
|
|
5365
5687
|
const accessToken = this.issueAccess({
|
|
5366
5688
|
sub: session.userId,
|
|
5367
5689
|
tenantId: session.tenantId,
|
|
@@ -5407,6 +5729,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5407
5729
|
const newSession = this.buildSession(seed.userId, "", seed.role, ip, userAgent, seed.mfaEnabled, seed.familyId, seed.familyCreatedAt);
|
|
5408
5730
|
const outcome = await this.redis.rotateRefreshSession({
|
|
5409
5731
|
kind: "platform",
|
|
5732
|
+
tenantId: void 0,
|
|
5410
5733
|
oldHash,
|
|
5411
5734
|
newHash,
|
|
5412
5735
|
newSessionJson: this.serializeSession(newSession),
|
|
@@ -5424,8 +5747,8 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5424
5747
|
if (outcome.kind === "reused") {
|
|
5425
5748
|
this.logger.warn(`reissuePlatformTokens: reuse of a consumed refresh token detected \u2014 revoking the token family familyId=${logSafe(outcome.familyId)}`);
|
|
5426
5749
|
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);
|
|
5750
|
+
this.logger.warn(`reissuePlatformTokens: token family revoked after reuse detection ${ownerFragment(ownerId)} familyId=${logSafe(outcome.familyId)}`);
|
|
5751
|
+
this.emitReuseDetected(ownerId, outcome.familyId, ip, userAgent);
|
|
5429
5752
|
throw new AuthException(AUTH_ERROR_CODES.REFRESH_TOKEN_INVALID);
|
|
5430
5753
|
}
|
|
5431
5754
|
this.logger.warn("reissuePlatformTokens: no valid session or grace window found \u2014 REFRESH_TOKEN_INVALID");
|
|
@@ -5460,6 +5783,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5460
5783
|
const anotherSession = this.buildSession(graceSession.userId, "", graceSession.role, ip, userAgent, graceSession.mfaEnabled, graceSession.familyId, graceSession.familyCreatedAt);
|
|
5461
5784
|
const written = await this.redis.writeRecoveredSession({
|
|
5462
5785
|
kind: "platform",
|
|
5786
|
+
tenantId: void 0,
|
|
5463
5787
|
newHash: anotherNewHash,
|
|
5464
5788
|
newSessionJson: this.serializeSession(anotherSession),
|
|
5465
5789
|
familyId: graceSession.familyId,
|
|
@@ -5469,7 +5793,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5469
5793
|
if (!written) {
|
|
5470
5794
|
throw new AuthException(AUTH_ERROR_CODES.REFRESH_TOKEN_INVALID);
|
|
5471
5795
|
}
|
|
5472
|
-
await this.redis.srem(
|
|
5796
|
+
await this.redis.srem(sessionIndexKey("platform", graceSession.userId, this.options.hmacKey, void 0), `prp:${oldHash}`);
|
|
5473
5797
|
await this.redis.del(`psd:${oldHash}`);
|
|
5474
5798
|
await this.writePlatformSessionDetail(anotherNewHash, ip, userAgent, refreshTtl);
|
|
5475
5799
|
return await this.buildPlatformRotatedResult(anotherSession, anotherNewRefresh);
|
|
@@ -5482,7 +5806,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5482
5806
|
* Platform admins must re-complete the MFA challenge flow to re-acquire a verified token.
|
|
5483
5807
|
*/
|
|
5484
5808
|
async buildPlatformRotatedResult(session, rawRefreshToken) {
|
|
5485
|
-
const epoch = await this.redis.getUserTokenEpoch(session.userId, "platform");
|
|
5809
|
+
const epoch = await this.redis.getUserTokenEpoch(session.userId, void 0, "platform");
|
|
5486
5810
|
const accessToken = this.issuePlatformAccess({
|
|
5487
5811
|
sub: session.userId,
|
|
5488
5812
|
role: session.role,
|
|
@@ -5529,7 +5853,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5529
5853
|
type: "platform",
|
|
5530
5854
|
mfaEnabled,
|
|
5531
5855
|
mfaVerified: claims.mfaVerified,
|
|
5532
|
-
epoch: await this.redis.getUserTokenEpoch(claims.sub, "platform")
|
|
5856
|
+
epoch: await this.redis.getUserTokenEpoch(claims.sub, void 0, "platform")
|
|
5533
5857
|
});
|
|
5534
5858
|
}
|
|
5535
5859
|
// ---------------------------------------------------------------------------
|
|
@@ -5604,7 +5928,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5604
5928
|
} : {},
|
|
5605
5929
|
// Stamped so the challenge token dies with the rest of the account's credentials. See
|
|
5606
5930
|
// the claim's own documentation for what it was surviving.
|
|
5607
|
-
epoch: await this.redis.getUserTokenEpoch(userId, context)
|
|
5931
|
+
epoch: await this.redis.getUserTokenEpoch(userId, tenantId, context)
|
|
5608
5932
|
};
|
|
5609
5933
|
const token = this.jwtService.sign(payload, {
|
|
5610
5934
|
expiresIn: `${MFA_TEMP_TOKEN_TTL_SECONDS}s`,
|
|
@@ -5656,7 +5980,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5656
5980
|
} catch {
|
|
5657
5981
|
throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
|
|
5658
5982
|
}
|
|
5659
|
-
if (payload.context === "dashboard" && payload.tenantId ===
|
|
5983
|
+
if (payload.context === "dashboard" && (payload.tenantId ?? "") === "" || payload.context === "platform" && payload.tenantId !== void 0) {
|
|
5660
5984
|
throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
|
|
5661
5985
|
}
|
|
5662
5986
|
const storedUserId = await this.redis.get(`mfa:${sha256(payload.jti)}`);
|
|
@@ -5666,7 +5990,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
5666
5990
|
if (storedUserId !== payload.sub) {
|
|
5667
5991
|
throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
|
|
5668
5992
|
}
|
|
5669
|
-
if (readStampedEpoch(payload) < await this.redis.getUserTokenEpoch(payload.sub, payload.context)) {
|
|
5993
|
+
if (readStampedEpoch(payload) < await this.redis.getUserTokenEpoch(payload.sub, payload.tenantId, payload.context)) {
|
|
5670
5994
|
throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
|
|
5671
5995
|
}
|
|
5672
5996
|
return {
|
|
@@ -5716,7 +6040,7 @@ TokenManagerService = _ts_decorate17([
|
|
|
5716
6040
|
function maskEmail(email) {
|
|
5717
6041
|
const atIndex = email.indexOf("@");
|
|
5718
6042
|
if (atIndex <= 0) return "***";
|
|
5719
|
-
return email[0] + "***@" + email.slice(atIndex + 1);
|
|
6043
|
+
return logSafe(email[0] + "***@" + email.slice(atIndex + 1));
|
|
5720
6044
|
}
|
|
5721
6045
|
__name(maskEmail, "maskEmail");
|
|
5722
6046
|
|
|
@@ -5751,6 +6075,19 @@ async function resolveTenantId(dtoTenantId, req, resolver) {
|
|
|
5751
6075
|
}
|
|
5752
6076
|
__name(resolveTenantId, "resolveTenantId");
|
|
5753
6077
|
|
|
6078
|
+
// src/server/utils/safe-log-line.ts
|
|
6079
|
+
var WITHHELD = "delivery details withheld: the composed line matched a value that must not be logged";
|
|
6080
|
+
function survives(line, secret) {
|
|
6081
|
+
if (secret.length === 0) return false;
|
|
6082
|
+
return line.includes(secret) || line.replace(/\D/g, "").includes(secret);
|
|
6083
|
+
}
|
|
6084
|
+
__name(survives, "survives");
|
|
6085
|
+
function safeLogLine(line, secrets) {
|
|
6086
|
+
if (!secrets.some((secret) => survives(line, secret))) return line;
|
|
6087
|
+
return redactSecrets(WITHHELD, secrets);
|
|
6088
|
+
}
|
|
6089
|
+
__name(safeLogLine, "safeLogLine");
|
|
6090
|
+
|
|
5754
6091
|
// src/server/utils/tenant-scoped.ts
|
|
5755
6092
|
function tenantScoped(user, tenantId) {
|
|
5756
6093
|
if (user === null) return null;
|
|
@@ -5856,14 +6193,21 @@ exports.AuthService = class _AuthService {
|
|
|
5856
6193
|
async rehashPassword(userId, tenantId, plain, verifiedHash) {
|
|
5857
6194
|
try {
|
|
5858
6195
|
const upgraded = await this.passwordService.hash(plain);
|
|
5859
|
-
const current = await this.userRepo.findById(
|
|
6196
|
+
const current = await this.userRepo.findById({
|
|
6197
|
+
id: userId,
|
|
6198
|
+
tenantId
|
|
6199
|
+
});
|
|
5860
6200
|
if (current?.passwordHash !== verifiedHash) {
|
|
5861
|
-
this.logger.log(`rehash on verify skipped \u2014 the stored hash changed userId=${userId}`);
|
|
6201
|
+
this.logger.log(`rehash on verify skipped \u2014 the stored hash changed userId=${logSafe(userId)}`);
|
|
5862
6202
|
return;
|
|
5863
6203
|
}
|
|
5864
|
-
await this.userRepo.updatePassword(
|
|
6204
|
+
await this.userRepo.updatePassword({
|
|
6205
|
+
id: userId,
|
|
6206
|
+
tenantId,
|
|
6207
|
+
passwordHash: upgraded
|
|
6208
|
+
});
|
|
5865
6209
|
} catch (err) {
|
|
5866
|
-
this.logger.error(
|
|
6210
|
+
this.logger.error(`rehash on verify failed \u2014 the stored hash is unchanged: ${describeChannelStatus(err)}`);
|
|
5867
6211
|
}
|
|
5868
6212
|
}
|
|
5869
6213
|
// ---------------------------------------------------------------------------
|
|
@@ -5908,7 +6252,10 @@ exports.AuthService = class _AuthService {
|
|
|
5908
6252
|
hookOverrides = hookResult.modifiedData;
|
|
5909
6253
|
}
|
|
5910
6254
|
}
|
|
5911
|
-
const existing = await this.userRepo.findByEmail(
|
|
6255
|
+
const existing = await this.userRepo.findByEmail({
|
|
6256
|
+
email: dto.email,
|
|
6257
|
+
tenantId
|
|
6258
|
+
});
|
|
5912
6259
|
if (existing) {
|
|
5913
6260
|
await this.passwordService.compareDummy(dto.password);
|
|
5914
6261
|
throw new AuthException(AUTH_ERROR_CODES.EMAIL_ALREADY_EXISTS);
|
|
@@ -5938,12 +6285,18 @@ exports.AuthService = class _AuthService {
|
|
|
5938
6285
|
const safeUser = toSafeUser2(newUser);
|
|
5939
6286
|
const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
|
|
5940
6287
|
if (this.options.sessions.enabled) {
|
|
5941
|
-
await this.sessionService.createSession(
|
|
6288
|
+
await this.sessionService.createSession({
|
|
6289
|
+
userId: safeUser.id,
|
|
6290
|
+
tenantId: safeUser.tenantId,
|
|
6291
|
+
rawRefreshToken: result.rawRefreshToken,
|
|
6292
|
+
ip,
|
|
6293
|
+
userAgent
|
|
6294
|
+
});
|
|
5942
6295
|
}
|
|
5943
|
-
this.logger.log(`register: user registered userId=${newUser.id} tenantId=${logSafe(tenantId)}`);
|
|
6296
|
+
this.logger.log(`register: user registered userId=${logSafe(newUser.id)} tenantId=${logSafe(tenantId)}`);
|
|
5944
6297
|
if (this.hooks?.afterRegister) {
|
|
5945
6298
|
void Promise.resolve(this.hooks.afterRegister(safeUser, context)).catch((err) => {
|
|
5946
|
-
this.logger.error(
|
|
6299
|
+
this.logger.error(`afterRegister hook threw: ${describeChannelStatus(err)}`);
|
|
5947
6300
|
});
|
|
5948
6301
|
}
|
|
5949
6302
|
return result;
|
|
@@ -5995,7 +6348,10 @@ exports.AuthService = class _AuthService {
|
|
|
5995
6348
|
if (this.hooks?.beforeLogin) {
|
|
5996
6349
|
await this.hooks.beforeLogin(dto.email, tenantId, context);
|
|
5997
6350
|
}
|
|
5998
|
-
const user = await this.userRepo.findByEmail(
|
|
6351
|
+
const user = await this.userRepo.findByEmail({
|
|
6352
|
+
email: dto.email,
|
|
6353
|
+
tenantId
|
|
6354
|
+
});
|
|
5999
6355
|
const tenantMismatch = user !== null && user.tenantId !== tenantId;
|
|
6000
6356
|
if (tenantMismatch && !this.warnedTenantMismatch) {
|
|
6001
6357
|
this.warnedTenantMismatch = true;
|
|
@@ -6045,7 +6401,7 @@ exports.AuthService = class _AuthService {
|
|
|
6045
6401
|
}
|
|
6046
6402
|
if (user.mfaEnabled) {
|
|
6047
6403
|
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)}`);
|
|
6404
|
+
this.logger.log(`login: MFA challenge issued userId=${logSafe(user.id)} tenantId=${logSafe(tenantId)}`);
|
|
6049
6405
|
return {
|
|
6050
6406
|
mfaRequired: true,
|
|
6051
6407
|
mfaTempToken
|
|
@@ -6054,15 +6410,26 @@ exports.AuthService = class _AuthService {
|
|
|
6054
6410
|
const safeUser = toSafeUser2(user);
|
|
6055
6411
|
const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
|
|
6056
6412
|
if (this.options.sessions.enabled) {
|
|
6057
|
-
await this.sessionService.createSession(
|
|
6413
|
+
await this.sessionService.createSession({
|
|
6414
|
+
userId: safeUser.id,
|
|
6415
|
+
tenantId: safeUser.tenantId,
|
|
6416
|
+
rawRefreshToken: result.rawRefreshToken,
|
|
6417
|
+
ip,
|
|
6418
|
+
userAgent
|
|
6419
|
+
});
|
|
6058
6420
|
}
|
|
6059
|
-
this.logger.log(`login: success userId=${safeUser.id} tenantId=${logSafe(tenantId)}`);
|
|
6060
|
-
void this.userRepo.updateLastLogin(
|
|
6061
|
-
|
|
6421
|
+
this.logger.log(`login: success userId=${logSafe(safeUser.id)} tenantId=${logSafe(tenantId)}`);
|
|
6422
|
+
void this.userRepo.updateLastLogin({
|
|
6423
|
+
id: user.id,
|
|
6424
|
+
tenantId
|
|
6425
|
+
}).catch((err) => {
|
|
6426
|
+
this.logger.error(`updateLastLogin failed: ${describeError(err, [
|
|
6427
|
+
user.id
|
|
6428
|
+
])}`);
|
|
6062
6429
|
});
|
|
6063
6430
|
if (this.hooks?.afterLogin) {
|
|
6064
6431
|
void Promise.resolve(this.hooks.afterLogin(safeUser, context)).catch((err) => {
|
|
6065
|
-
this.logger.error(
|
|
6432
|
+
this.logger.error(`afterLogin hook threw: ${describeChannelStatus(err)}`);
|
|
6066
6433
|
});
|
|
6067
6434
|
}
|
|
6068
6435
|
return result;
|
|
@@ -6094,8 +6461,8 @@ exports.AuthService = class _AuthService {
|
|
|
6094
6461
|
*/
|
|
6095
6462
|
async logout(accessToken, rawRefreshToken) {
|
|
6096
6463
|
const sessionHash = sha256(rawRefreshToken);
|
|
6097
|
-
const userId = await this.redis.readSessionOwner(`rt:${sessionHash}`);
|
|
6098
|
-
this.logger.log(`logout: userId=${userId || "(no live session)"}`);
|
|
6464
|
+
const { userId, tenantId } = await this.redis.readSessionOwner(`rt:${sessionHash}`);
|
|
6465
|
+
this.logger.log(`logout: userId=${logSafe(userId || "(no live session)")}`);
|
|
6099
6466
|
try {
|
|
6100
6467
|
const payload = this.tokenManager.verifyIgnoringExpiry(accessToken);
|
|
6101
6468
|
const now = Math.floor(Date.now() / 1e3);
|
|
@@ -6107,17 +6474,23 @@ exports.AuthService = class _AuthService {
|
|
|
6107
6474
|
}
|
|
6108
6475
|
await this.redis.del(`rt:${sessionHash}`);
|
|
6109
6476
|
await this.redis.del(`rp:${sessionHash}`);
|
|
6110
|
-
if (this.options.sessions.enabled && userId) {
|
|
6111
|
-
await this.sessionService.revokeSession(
|
|
6477
|
+
if (this.options.sessions.enabled && userId && tenantId !== void 0) {
|
|
6478
|
+
await this.sessionService.revokeSession({
|
|
6479
|
+
userId,
|
|
6480
|
+
tenantId,
|
|
6481
|
+
sessionHash
|
|
6482
|
+
}).catch((err) => {
|
|
6112
6483
|
const errCode = err instanceof AuthException ? err.getResponse().error.code : void 0;
|
|
6113
6484
|
if (errCode !== AUTH_ERROR_CODES.SESSION_NOT_FOUND) {
|
|
6114
|
-
this.logger.warn(`logout: session cleanup failed \u2014 ${
|
|
6485
|
+
this.logger.warn(`logout: session cleanup failed \u2014 ${describeChannelStatus(err)}`);
|
|
6115
6486
|
}
|
|
6116
6487
|
});
|
|
6117
6488
|
}
|
|
6118
6489
|
if (this.hooks?.afterLogout && userId) {
|
|
6119
6490
|
void Promise.resolve(this.hooks.afterLogout(userId, createEmptyHookContext())).catch((err) => {
|
|
6120
|
-
this.logger.error(
|
|
6491
|
+
this.logger.error(`afterLogout hook threw: ${describeError(err, [
|
|
6492
|
+
userId
|
|
6493
|
+
])}`);
|
|
6121
6494
|
});
|
|
6122
6495
|
}
|
|
6123
6496
|
return userId;
|
|
@@ -6139,15 +6512,24 @@ exports.AuthService = class _AuthService {
|
|
|
6139
6512
|
*/
|
|
6140
6513
|
async refresh(oldRefreshToken, ip, userAgent) {
|
|
6141
6514
|
const result = await this.tokenManager.reissueTokens(oldRefreshToken, ip, userAgent);
|
|
6142
|
-
const user = await this.userRepo.findById(
|
|
6515
|
+
const user = await this.userRepo.findById({
|
|
6516
|
+
id: result.session.userId,
|
|
6517
|
+
tenantId: result.session.tenantId
|
|
6518
|
+
});
|
|
6143
6519
|
if (!user) {
|
|
6144
|
-
await this.revokeAllSessions(
|
|
6520
|
+
await this.revokeAllSessions({
|
|
6521
|
+
userId: result.session.userId,
|
|
6522
|
+
tenantId: result.session.tenantId
|
|
6523
|
+
});
|
|
6145
6524
|
throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
|
|
6146
6525
|
}
|
|
6147
6526
|
try {
|
|
6148
6527
|
this.assertUserNotBlocked(user);
|
|
6149
6528
|
} catch (err) {
|
|
6150
|
-
await this.revokeAllSessions(
|
|
6529
|
+
await this.revokeAllSessions({
|
|
6530
|
+
userId: result.session.userId,
|
|
6531
|
+
tenantId: result.session.tenantId
|
|
6532
|
+
});
|
|
6151
6533
|
throw err;
|
|
6152
6534
|
}
|
|
6153
6535
|
if (this.options.emailVerification.required && !user.emailVerified) {
|
|
@@ -6167,12 +6549,12 @@ exports.AuthService = class _AuthService {
|
|
|
6167
6549
|
// cleared on this session stays cleared, and re-stamping the authority must not
|
|
6168
6550
|
// silently demand it again.
|
|
6169
6551
|
mfaVerified: rotated.mfaVerified,
|
|
6170
|
-
epoch: await this.redis.getUserTokenEpoch(user.id)
|
|
6552
|
+
epoch: await this.redis.getUserTokenEpoch(user.id, user.tenantId, "dashboard")
|
|
6171
6553
|
});
|
|
6172
6554
|
}
|
|
6173
6555
|
if (this.options.sessions.enabled) {
|
|
6174
6556
|
void this.sessionService.rotateSession(sha256(oldRefreshToken), sha256(result.rawRefreshToken), ip, userAgent).catch((err) => {
|
|
6175
|
-
this.logger.warn(`refresh: session detail rotation failed \u2014 ${
|
|
6557
|
+
this.logger.warn(`refresh: session detail rotation failed \u2014 ${describeChannelStatus(err)}`);
|
|
6176
6558
|
});
|
|
6177
6559
|
}
|
|
6178
6560
|
return {
|
|
@@ -6201,11 +6583,21 @@ exports.AuthService = class _AuthService {
|
|
|
6201
6583
|
* The epoch is bumped after the sweep, not before: a failure in the sweep then leaves the
|
|
6202
6584
|
* operation visibly incomplete rather than reading as done while the sessions live on.
|
|
6203
6585
|
*
|
|
6204
|
-
* @param
|
|
6586
|
+
* @param params - See {@link RevokeAllSessionsParams}. Both keyspaces are scoped to the tenant,
|
|
6587
|
+
* so naming the wrong one revokes the colliding id in another tenant instead.
|
|
6588
|
+
* @throws {@link AuthException} `VALIDATION` when the tenant is blank.
|
|
6205
6589
|
*/
|
|
6206
|
-
async revokeAllSessions(userId) {
|
|
6207
|
-
|
|
6208
|
-
|
|
6590
|
+
async revokeAllSessions({ userId, tenantId }) {
|
|
6591
|
+
if (tenantId === "") {
|
|
6592
|
+
throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
|
|
6593
|
+
{
|
|
6594
|
+
field: "tenantId",
|
|
6595
|
+
message: "tenantId is required to revoke a user's sessions"
|
|
6596
|
+
}
|
|
6597
|
+
]);
|
|
6598
|
+
}
|
|
6599
|
+
await this.redis.invalidateUserSessions(userId, tenantId, "dashboard");
|
|
6600
|
+
await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
|
|
6209
6601
|
}
|
|
6210
6602
|
// ---------------------------------------------------------------------------
|
|
6211
6603
|
// GetMe
|
|
@@ -6214,11 +6606,16 @@ exports.AuthService = class _AuthService {
|
|
|
6214
6606
|
* Retrieves the full safe user record for the currently authenticated user.
|
|
6215
6607
|
*
|
|
6216
6608
|
* @param userId - Subject claim from the verified JWT.
|
|
6609
|
+
* @param tenantId - Tenant claim from the same token; scopes the lookup, because a repository
|
|
6610
|
+
* id is unique only within a tenant.
|
|
6217
6611
|
* @returns Safe user object (credential fields excluded).
|
|
6218
6612
|
* @throws {@link AuthException} with `TOKEN_INVALID` if the user no longer exists.
|
|
6219
6613
|
*/
|
|
6220
|
-
async getMe(userId) {
|
|
6221
|
-
const user = await this.userRepo.findById(
|
|
6614
|
+
async getMe(userId, tenantId) {
|
|
6615
|
+
const user = await this.userRepo.findById({
|
|
6616
|
+
id: userId,
|
|
6617
|
+
tenantId
|
|
6618
|
+
});
|
|
6222
6619
|
if (!user) {
|
|
6223
6620
|
throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
|
|
6224
6621
|
}
|
|
@@ -6271,8 +6668,11 @@ exports.AuthService = class _AuthService {
|
|
|
6271
6668
|
* @throws `MFA_REQUIRED` when the target user has MFA enabled — the
|
|
6272
6669
|
* consumer must route through the MFA challenge flow for that user.
|
|
6273
6670
|
*/
|
|
6274
|
-
async issueTokensForUserId(userId, ip, userAgent) {
|
|
6275
|
-
const user = await this.userRepo.findById(
|
|
6671
|
+
async issueTokensForUserId(userId, tenantId, ip, userAgent) {
|
|
6672
|
+
const user = await this.userRepo.findById({
|
|
6673
|
+
id: userId,
|
|
6674
|
+
tenantId
|
|
6675
|
+
});
|
|
6276
6676
|
if (!user) {
|
|
6277
6677
|
throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
|
|
6278
6678
|
}
|
|
@@ -6286,11 +6686,22 @@ exports.AuthService = class _AuthService {
|
|
|
6286
6686
|
const safeUser = toSafeUser2(user);
|
|
6287
6687
|
const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
|
|
6288
6688
|
if (this.options.sessions.enabled) {
|
|
6289
|
-
await this.sessionService.createSession(
|
|
6689
|
+
await this.sessionService.createSession({
|
|
6690
|
+
userId: safeUser.id,
|
|
6691
|
+
tenantId: safeUser.tenantId,
|
|
6692
|
+
rawRefreshToken: result.rawRefreshToken,
|
|
6693
|
+
ip,
|
|
6694
|
+
userAgent
|
|
6695
|
+
});
|
|
6290
6696
|
}
|
|
6291
|
-
this.logger.log(`issueTokensForUserId: success userId=${safeUser.id} tenantId=${logSafe(safeUser.tenantId)}`);
|
|
6292
|
-
void this.userRepo.updateLastLogin(
|
|
6293
|
-
|
|
6697
|
+
this.logger.log(`issueTokensForUserId: success userId=${logSafe(safeUser.id)} tenantId=${logSafe(safeUser.tenantId)}`);
|
|
6698
|
+
void this.userRepo.updateLastLogin({
|
|
6699
|
+
id: user.id,
|
|
6700
|
+
tenantId: safeUser.tenantId
|
|
6701
|
+
}).catch((err) => {
|
|
6702
|
+
this.logger.error(`updateLastLogin failed: ${describeError(err, [
|
|
6703
|
+
user.id
|
|
6704
|
+
])}`);
|
|
6294
6705
|
});
|
|
6295
6706
|
if (this.hooks?.afterLogin) {
|
|
6296
6707
|
void Promise.resolve(this.hooks.afterLogin(safeUser, {
|
|
@@ -6299,7 +6710,7 @@ exports.AuthService = class _AuthService {
|
|
|
6299
6710
|
userAgent,
|
|
6300
6711
|
sanitizedHeaders: {}
|
|
6301
6712
|
})).catch((err) => {
|
|
6302
|
-
this.logger.error(
|
|
6713
|
+
this.logger.error(`afterLogin hook threw: ${describeChannelStatus(err)}`);
|
|
6303
6714
|
});
|
|
6304
6715
|
}
|
|
6305
6716
|
return result;
|
|
@@ -6327,16 +6738,23 @@ exports.AuthService = class _AuthService {
|
|
|
6327
6738
|
tenantId = await this.resolveTenantId(tenantId, req);
|
|
6328
6739
|
email = normalizeEmail(email);
|
|
6329
6740
|
await this.otpService.verify("email_verification", this.otpIdentifier(tenantId, email), otp);
|
|
6330
|
-
const user = tenantScoped(await this.userRepo.findByEmail(
|
|
6741
|
+
const user = tenantScoped(await this.userRepo.findByEmail({
|
|
6742
|
+
email,
|
|
6743
|
+
tenantId
|
|
6744
|
+
}), tenantId);
|
|
6331
6745
|
if (!user) {
|
|
6332
6746
|
throw new AuthException(AUTH_ERROR_CODES.OTP_INVALID);
|
|
6333
6747
|
}
|
|
6334
|
-
await this.userRepo.updateEmailVerified(
|
|
6748
|
+
await this.userRepo.updateEmailVerified({
|
|
6749
|
+
id: user.id,
|
|
6750
|
+
tenantId,
|
|
6751
|
+
verified: true
|
|
6752
|
+
});
|
|
6335
6753
|
await this.redis.del(`uev:${encodeURIComponent(tenantId)}:${encodeURIComponent(user.id)}`);
|
|
6336
|
-
this.logger.log(`verifyEmail: email verified userId=${user.id} tenantId=${logSafe(tenantId)}`);
|
|
6754
|
+
this.logger.log(`verifyEmail: email verified userId=${logSafe(user.id)} tenantId=${logSafe(tenantId)}`);
|
|
6337
6755
|
if (this.hooks?.afterEmailVerified) {
|
|
6338
6756
|
void Promise.resolve(this.hooks.afterEmailVerified(toSafeUser2(user), createEmptyHookContext())).catch((err) => {
|
|
6339
|
-
this.logger.error(
|
|
6757
|
+
this.logger.error(`afterEmailVerified hook threw: ${describeChannelStatus(err)}`);
|
|
6340
6758
|
});
|
|
6341
6759
|
}
|
|
6342
6760
|
}
|
|
@@ -6360,7 +6778,10 @@ exports.AuthService = class _AuthService {
|
|
|
6360
6778
|
await sleep(Math.max(0, ANTI_ENUM_MIN_MS - (Date.now() - start)));
|
|
6361
6779
|
return;
|
|
6362
6780
|
}
|
|
6363
|
-
const user = tenantScoped(await this.userRepo.findByEmail(
|
|
6781
|
+
const user = tenantScoped(await this.userRepo.findByEmail({
|
|
6782
|
+
email,
|
|
6783
|
+
tenantId
|
|
6784
|
+
}), tenantId);
|
|
6364
6785
|
if (user && !user.emailVerified) {
|
|
6365
6786
|
await this.sendVerificationOtp(tenantId, email, user.id);
|
|
6366
6787
|
}
|
|
@@ -6396,6 +6817,67 @@ exports.AuthService = class _AuthService {
|
|
|
6396
6817
|
await this.bruteForce.resetFailures(identifier);
|
|
6397
6818
|
this.logger.log(`unlockAccount: lockout cleared email=${maskEmail(normalizeEmail(email))} tenantId=${logSafe(tenantId)}`);
|
|
6398
6819
|
}
|
|
6820
|
+
/**
|
|
6821
|
+
* Reports whether an account is currently locked out by brute-force protection.
|
|
6822
|
+
*
|
|
6823
|
+
* The counterpart to {@link unlockAccount}, and the reason it exists: the write side was
|
|
6824
|
+
* public while the read side was not, so a host could offer an Unlock control and could not
|
|
6825
|
+
* tell anyone whether it had anything to do.
|
|
6826
|
+
*
|
|
6827
|
+
* A consumer cannot derive this themselves even with the source in hand. The counter is keyed
|
|
6828
|
+
* by an HMAC of `dashboard:{tenantId}:{email}` under the library's own `hmacKey`, which is
|
|
6829
|
+
* derived rather than supplied — and reproducing the preimage is precisely what keeping the
|
|
6830
|
+
* derivation in one place prevents. A third copy in a consumer repository is a third chance to
|
|
6831
|
+
* drift, and the failure is silent: a key that never exists reads as "not locked out" for every
|
|
6832
|
+
* account, including locked ones. A false negative on a security indicator, reported
|
|
6833
|
+
* confidently.
|
|
6834
|
+
*
|
|
6835
|
+
* **Cheap enough to put on every row of a list, with one caveat that is the host's.** Issuing
|
|
6836
|
+
* these concurrently overlaps the waits, so twenty of them cost close to what one costs; issuing
|
|
6837
|
+
* them with `await` inside a loop serialises the round trips and cost sixteen times as much when
|
|
6838
|
+
* the reporter measured it against a local Redis. That ratio is a property of concurrency, not a
|
|
6839
|
+
* guarantee this library makes: each call is its own Redis command, the ioredis client is
|
|
6840
|
+
* supplied by the host, and whether those commands are also BATCHED into one write depends on
|
|
6841
|
+
* `enableAutoPipelining`, which ioredis leaves off by default. Use `Promise.all`; do not treat
|
|
6842
|
+
* any absolute number here as a contract.
|
|
6843
|
+
*
|
|
6844
|
+
* Like {@link unlockAccount}, this ships **no route**. Whether a caller may ask about an account
|
|
6845
|
+
* they do not own is a decision only the host can make, and a lockout flag reachable without
|
|
6846
|
+
* authorisation is an oracle about other people's accounts.
|
|
6847
|
+
*
|
|
6848
|
+
* @param email - The account's address. Normalized here exactly as login normalizes it, or the
|
|
6849
|
+
* derived key misses the counter the lockout actually wrote.
|
|
6850
|
+
* @param tenantId - The tenant the account belongs to.
|
|
6851
|
+
* @returns `true` while the account is locked out.
|
|
6852
|
+
*/
|
|
6853
|
+
async isAccountLockedOut(email, tenantId) {
|
|
6854
|
+
return await this.bruteForce.isLockedOut(this.lockoutIdentifier(tenantId, normalizeEmail(email)));
|
|
6855
|
+
}
|
|
6856
|
+
/**
|
|
6857
|
+
* Reports how many seconds remain on an account's lockout.
|
|
6858
|
+
*
|
|
6859
|
+
* Separate from {@link isAccountLockedOut} because a bare flag with no horizon is the interface
|
|
6860
|
+
* that invites the support call the indicator was meant to prevent: it says an account is
|
|
6861
|
+
* locked and cannot say for how long, so the only honest advice is "try again later".
|
|
6862
|
+
*
|
|
6863
|
+
* **Gated on the lockout, not merely on the key.** `BruteForceService.getRemainingLockoutSeconds`
|
|
6864
|
+
* returns the TTL of the failure counter, and `recordFailure` creates that counter on the FIRST
|
|
6865
|
+
* failure — so the raw TTL is positive from one failed attempt onward, long before the threshold
|
|
6866
|
+
* is reached. Returned unchecked it would tell a console "locked for 14 minutes" about an
|
|
6867
|
+
* account that is not locked and whose next attempt would succeed. The threshold is therefore
|
|
6868
|
+
* read first, which costs a second Redis command only on the accounts that are actually locked.
|
|
6869
|
+
*
|
|
6870
|
+
* Ships no route, for the reason given on {@link isAccountLockedOut}.
|
|
6871
|
+
*
|
|
6872
|
+
* @param email - The account's address, normalized here as login normalizes it.
|
|
6873
|
+
* @param tenantId - The tenant the account belongs to.
|
|
6874
|
+
* @returns Seconds until the lockout expires, or `0` when the account is not locked out.
|
|
6875
|
+
*/
|
|
6876
|
+
async getAccountLockoutSeconds(email, tenantId) {
|
|
6877
|
+
const identifier = this.lockoutIdentifier(tenantId, normalizeEmail(email));
|
|
6878
|
+
if (!await this.bruteForce.isLockedOut(identifier)) return 0;
|
|
6879
|
+
return await this.bruteForce.getRemainingLockoutSeconds(identifier);
|
|
6880
|
+
}
|
|
6399
6881
|
// ---------------------------------------------------------------------------
|
|
6400
6882
|
// Private helpers
|
|
6401
6883
|
// ---------------------------------------------------------------------------
|
|
@@ -6495,10 +6977,10 @@ exports.AuthService = class _AuthService {
|
|
|
6495
6977
|
fireAndForget(run, name) {
|
|
6496
6978
|
try {
|
|
6497
6979
|
void Promise.resolve(run()).catch((err) => {
|
|
6498
|
-
this.logger.error(`${name} hook threw
|
|
6980
|
+
this.logger.error(`${name} hook threw: ${describeChannelStatus(err)}`);
|
|
6499
6981
|
});
|
|
6500
6982
|
} catch (err) {
|
|
6501
|
-
this.logger.error(`${name} hook threw synchronously
|
|
6983
|
+
this.logger.error(`${name} hook threw synchronously: ${describeChannelStatus(err)}`);
|
|
6502
6984
|
}
|
|
6503
6985
|
}
|
|
6504
6986
|
assertUserNotBlocked(user) {
|
|
@@ -6514,9 +6996,18 @@ exports.AuthService = class _AuthService {
|
|
|
6514
6996
|
const ttl = this.options.emailVerification.otpTtlSeconds;
|
|
6515
6997
|
const otp = this.otpService.generate(length);
|
|
6516
6998
|
await this.otpService.store("email_verification", identifier, otp, ttl);
|
|
6517
|
-
|
|
6518
|
-
|
|
6519
|
-
|
|
6999
|
+
const provider = this.emailProvider;
|
|
7000
|
+
void (async () => {
|
|
7001
|
+
try {
|
|
7002
|
+
await provider.sendEmailVerificationOtp(tenantId, email, otp);
|
|
7003
|
+
} catch (err) {
|
|
7004
|
+
const withheld = [
|
|
7005
|
+
otp,
|
|
7006
|
+
email
|
|
7007
|
+
];
|
|
7008
|
+
this.logger.error(safeLogLine(`sendEmailVerificationOtp failed for user ${logSafe(redactSecrets(userId, withheld))}: ` + describeChannelStatus(err), withheld));
|
|
7009
|
+
}
|
|
7010
|
+
})();
|
|
6520
7011
|
}
|
|
6521
7012
|
};
|
|
6522
7013
|
exports.AuthService = _ts_decorate18([
|
|
@@ -6612,10 +7103,13 @@ exports.WsTicketService = class _WsTicketService {
|
|
|
6612
7103
|
throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
|
|
6613
7104
|
}
|
|
6614
7105
|
if (payload.mfaEnabled && payload.mfaVerified !== true) {
|
|
6615
|
-
this.logger.warn(`ws-ticket: refused, MFA not satisfied userId=${payload.sub}`);
|
|
7106
|
+
this.logger.warn(`ws-ticket: refused, MFA not satisfied userId=${logSafe(payload.sub)}`);
|
|
6616
7107
|
throw new AuthException(AUTH_ERROR_CODES.MFA_REQUIRED);
|
|
6617
7108
|
}
|
|
6618
|
-
const user = await this.userRepo.findById(
|
|
7109
|
+
const user = await this.userRepo.findById({
|
|
7110
|
+
id: payload.sub,
|
|
7111
|
+
tenantId: payload.tenantId
|
|
7112
|
+
});
|
|
6619
7113
|
if (!user) throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
|
|
6620
7114
|
assertNotBlocked(user.status, this.options.blockedStatuses);
|
|
6621
7115
|
const snapshot = {
|
|
@@ -6627,7 +7121,7 @@ exports.WsTicketService = class _WsTicketService {
|
|
|
6627
7121
|
mfaVerified: payload.mfaVerified
|
|
6628
7122
|
};
|
|
6629
7123
|
const ticket = await this.redis.mintWsTicket(snapshot, WS_TICKET_TTL_SECONDS);
|
|
6630
|
-
this.logger.log(`ws-ticket: issued userId=${payload.sub} tenantId=${payload.tenantId}`);
|
|
7124
|
+
this.logger.log(`ws-ticket: issued userId=${logSafe(payload.sub)} tenantId=${logSafe(payload.tenantId)}`);
|
|
6631
7125
|
return {
|
|
6632
7126
|
ticket,
|
|
6633
7127
|
expiresIn: WS_TICKET_TTL_SECONDS
|
|
@@ -6791,10 +7285,11 @@ var AuthController = class {
|
|
|
6791
7285
|
* and so refuses an unverified or blocked account. The account's own `status` and
|
|
6792
7286
|
* `emailVerified` fields are in the returned record for the client to branch on.
|
|
6793
7287
|
*
|
|
6794
|
-
* @param user - JWT payload from the verified access token.
|
|
7288
|
+
* @param user - JWT payload from the verified access token. Both the subject and the tenant
|
|
7289
|
+
* are read from it: an account is named by the pair, never by the id alone.
|
|
6795
7290
|
*/
|
|
6796
7291
|
async me(user) {
|
|
6797
|
-
return this.authService.getMe(user.sub);
|
|
7292
|
+
return this.authService.getMe(user.sub, user.tenantId);
|
|
6798
7293
|
}
|
|
6799
7294
|
/**
|
|
6800
7295
|
* Mints a single-use ticket for authenticating a WebSocket upgrade.
|
|
@@ -7147,6 +7642,8 @@ exports.EmailChangeService = class _EmailChangeService {
|
|
|
7147
7642
|
* new address. Nothing about the account changes until that token comes back.
|
|
7148
7643
|
*
|
|
7149
7644
|
* @param userId - The authenticated caller, from their own claims — never the body.
|
|
7645
|
+
* @param tenantId - The tenant that caller belongs to, from the same claims; scopes the
|
|
7646
|
+
* account read, because a repository id is unique only within a tenant.
|
|
7150
7647
|
* @param dto - The new address and the current password.
|
|
7151
7648
|
* @throws {@link AuthException} `INVALID_CREDENTIALS` when the account has no local password
|
|
7152
7649
|
* or the submitted one is wrong — the same code a failed login returns, so a thief holding
|
|
@@ -7154,21 +7651,24 @@ exports.EmailChangeService = class _EmailChangeService {
|
|
|
7154
7651
|
* @throws {@link AuthException} `EMAIL_ALREADY_EXISTS` when the address is the account's own
|
|
7155
7652
|
* or belongs to another account in the tenant.
|
|
7156
7653
|
*/
|
|
7157
|
-
async requestChange(userId, dto) {
|
|
7654
|
+
async requestChange(userId, tenantId, dto) {
|
|
7158
7655
|
const newEmail = normalizeEmail(dto.newEmail);
|
|
7159
|
-
const user = await this.userRepo.findById(
|
|
7656
|
+
const user = await this.userRepo.findById({
|
|
7657
|
+
id: userId,
|
|
7658
|
+
tenantId
|
|
7659
|
+
});
|
|
7160
7660
|
if (!user?.passwordHash) {
|
|
7161
7661
|
throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
|
|
7162
7662
|
}
|
|
7163
|
-
const bfIdentifier = hmacSha256(`reauth:email-change:${userId}`, this.options.hmacKey);
|
|
7663
|
+
const bfIdentifier = hmacSha256(`reauth:email-change:${userSubject("dashboard", userId, tenantId)}`, this.options.hmacKey);
|
|
7164
7664
|
if (await this.bruteForce.isLockedOut(bfIdentifier)) {
|
|
7165
|
-
this.logger.warn(`requestChange: account locked userId=${userId}`);
|
|
7665
|
+
this.logger.warn(`requestChange: account locked userId=${logSafe(userId)}`);
|
|
7166
7666
|
throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
|
|
7167
7667
|
}
|
|
7168
7668
|
const matches = await this.passwordService.compare(dto.currentPassword, user.passwordHash);
|
|
7169
7669
|
if (!matches) {
|
|
7170
7670
|
await this.bruteForce.recordFailure(bfIdentifier);
|
|
7171
|
-
this.logger.warn(`requestChange: current password rejected userId=${userId}`);
|
|
7671
|
+
this.logger.warn(`requestChange: current password rejected userId=${logSafe(userId)}`);
|
|
7172
7672
|
throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
|
|
7173
7673
|
}
|
|
7174
7674
|
await this.bruteForce.resetFailures(bfIdentifier);
|
|
@@ -7184,8 +7684,12 @@ exports.EmailChangeService = class _EmailChangeService {
|
|
|
7184
7684
|
passwordFingerprint: sha256(user.passwordHash)
|
|
7185
7685
|
};
|
|
7186
7686
|
await this.redis.set(`ec:${sha256(rawToken)}`, JSON.stringify(context), this.options.emailChange.tokenTtlSeconds);
|
|
7187
|
-
|
|
7188
|
-
|
|
7687
|
+
try {
|
|
7688
|
+
await this.emailProvider.sendEmailChangeVerification?.(user.tenantId, newEmail, rawToken);
|
|
7689
|
+
} catch (err) {
|
|
7690
|
+
throw new Error(describeChannelStatus(err));
|
|
7691
|
+
}
|
|
7692
|
+
this.logger.log(`requestChange: verification sent userId=${logSafe(userId)} newEmail=${maskEmail(newEmail)}`);
|
|
7189
7693
|
}
|
|
7190
7694
|
// ---------------------------------------------------------------------------
|
|
7191
7695
|
// confirmChange()
|
|
@@ -7208,7 +7712,10 @@ exports.EmailChangeService = class _EmailChangeService {
|
|
|
7208
7712
|
if (context === null) {
|
|
7209
7713
|
throw new AuthException(AUTH_ERROR_CODES.EMAIL_CHANGE_TOKEN_INVALID);
|
|
7210
7714
|
}
|
|
7211
|
-
const user = await this.userRepo.findById(
|
|
7715
|
+
const user = await this.userRepo.findById({
|
|
7716
|
+
id: context.userId,
|
|
7717
|
+
tenantId: context.tenantId
|
|
7718
|
+
});
|
|
7212
7719
|
if (!user) {
|
|
7213
7720
|
throw new AuthException(AUTH_ERROR_CODES.EMAIL_CHANGE_TOKEN_INVALID);
|
|
7214
7721
|
}
|
|
@@ -7216,8 +7723,12 @@ exports.EmailChangeService = class _EmailChangeService {
|
|
|
7216
7723
|
assertNotBlocked(user.status, this.options.blockedStatuses);
|
|
7217
7724
|
await this.assertAddressIsFree(user, context.newEmail);
|
|
7218
7725
|
const oldEmail = user.email;
|
|
7219
|
-
await this.userRepo.updateEmail(
|
|
7220
|
-
|
|
7726
|
+
await this.userRepo.updateEmail({
|
|
7727
|
+
id: context.userId,
|
|
7728
|
+
tenantId: context.tenantId,
|
|
7729
|
+
email: context.newEmail
|
|
7730
|
+
});
|
|
7731
|
+
this.logger.log(`confirmChange: address changed userId=${logSafe(context.userId)} from=${maskEmail(oldEmail)} to=${maskEmail(context.newEmail)}`);
|
|
7221
7732
|
await this.notifyOldAddress(user.tenantId, oldEmail, context.newEmail);
|
|
7222
7733
|
}
|
|
7223
7734
|
// ---------------------------------------------------------------------------
|
|
@@ -7242,7 +7753,10 @@ exports.EmailChangeService = class _EmailChangeService {
|
|
|
7242
7753
|
if (normalizeEmail(user.email) === newEmail) {
|
|
7243
7754
|
throw new AuthException(AUTH_ERROR_CODES.EMAIL_ALREADY_EXISTS);
|
|
7244
7755
|
}
|
|
7245
|
-
const existing = await this.userRepo.findByEmail(
|
|
7756
|
+
const existing = await this.userRepo.findByEmail({
|
|
7757
|
+
email: newEmail,
|
|
7758
|
+
tenantId: user.tenantId
|
|
7759
|
+
});
|
|
7246
7760
|
if (existing) {
|
|
7247
7761
|
throw new AuthException(AUTH_ERROR_CODES.EMAIL_ALREADY_EXISTS);
|
|
7248
7762
|
}
|
|
@@ -7270,7 +7784,7 @@ exports.EmailChangeService = class _EmailChangeService {
|
|
|
7270
7784
|
if (stored === void 0 || stored === "") return;
|
|
7271
7785
|
const current = user.passwordHash === null ? null : sha256(user.passwordHash);
|
|
7272
7786
|
if (current === null || stored !== current) {
|
|
7273
|
-
this.logger.warn(`confirmChange: token no longer bound to the account password userId=${context.userId}`);
|
|
7787
|
+
this.logger.warn(`confirmChange: token no longer bound to the account password userId=${logSafe(context.userId)}`);
|
|
7274
7788
|
throw new AuthException(AUTH_ERROR_CODES.EMAIL_CHANGE_TOKEN_INVALID);
|
|
7275
7789
|
}
|
|
7276
7790
|
}
|
|
@@ -7303,7 +7817,7 @@ exports.EmailChangeService = class _EmailChangeService {
|
|
|
7303
7817
|
try {
|
|
7304
7818
|
await this.emailProvider.sendEmailChangedNotification(tenantId, oldEmail, newEmail);
|
|
7305
7819
|
} catch (err) {
|
|
7306
|
-
this.logger.error(
|
|
7820
|
+
this.logger.error(`confirmChange: notification to the previous address failed: ` + describeChannelStatus(err));
|
|
7307
7821
|
}
|
|
7308
7822
|
}
|
|
7309
7823
|
};
|
|
@@ -7382,7 +7896,7 @@ var EmailChangeController = class {
|
|
|
7382
7896
|
// carries it: a suspended account holding a live access token must not be able to move the
|
|
7383
7897
|
// credential its recovery depends on.
|
|
7384
7898
|
async requestChange(dto, user) {
|
|
7385
|
-
await this.emailChangeService.requestChange(user.sub, dto);
|
|
7899
|
+
await this.emailChangeService.requestChange(user.sub, user.tenantId, dto);
|
|
7386
7900
|
}
|
|
7387
7901
|
// ---------------------------------------------------------------------------
|
|
7388
7902
|
// POST /email/change/confirm
|
|
@@ -7490,8 +8004,9 @@ var AcceptInvitationDto = class {
|
|
|
7490
8004
|
*
|
|
7491
8005
|
* Maximum 128 characters as a practical
|
|
7492
8006
|
* input bound to prevent DoS via pathological scrypt inputs.
|
|
7493
|
-
* The service layer hashes this value immediately — it is never logged or
|
|
7494
|
-
*
|
|
8007
|
+
* The service layer hashes this value immediately — it is never logged or persisted in plaintext
|
|
8008
|
+
* BY THIS LIBRARY. A breach checker you supply receives it by contract, and an error it raises
|
|
8009
|
+
* is a place it can be; see `PasswordService.assertNotCompromised` for the ceiling.
|
|
7495
8010
|
*/
|
|
7496
8011
|
password;
|
|
7497
8012
|
};
|
|
@@ -7708,7 +8223,10 @@ exports.InvitationService = class _InvitationService {
|
|
|
7708
8223
|
if (!Object.hasOwn(hierarchy, role)) {
|
|
7709
8224
|
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
|
|
7710
8225
|
}
|
|
7711
|
-
const inviter = await this.userRepo.findById(
|
|
8226
|
+
const inviter = await this.userRepo.findById({
|
|
8227
|
+
id: inviterUserId,
|
|
8228
|
+
tenantId
|
|
8229
|
+
});
|
|
7712
8230
|
if (!inviter) {
|
|
7713
8231
|
throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
|
|
7714
8232
|
}
|
|
@@ -7736,13 +8254,17 @@ exports.InvitationService = class _InvitationService {
|
|
|
7736
8254
|
await this.redis.set(tokenKey, JSON.stringify(stored), ttl);
|
|
7737
8255
|
const displayTenantName = tenantName ?? tenantId;
|
|
7738
8256
|
const expiresAt = new Date(Date.now() + ttl * 1e3);
|
|
7739
|
-
|
|
7740
|
-
|
|
7741
|
-
|
|
7742
|
-
|
|
7743
|
-
|
|
7744
|
-
|
|
7745
|
-
|
|
8257
|
+
try {
|
|
8258
|
+
await this.emailProvider.sendInvitation(tenantId, normalizedEmail, {
|
|
8259
|
+
inviterName: inviter.name,
|
|
8260
|
+
tenantName: displayTenantName,
|
|
8261
|
+
inviteToken: rawToken,
|
|
8262
|
+
expiresAt
|
|
8263
|
+
});
|
|
8264
|
+
} catch (err) {
|
|
8265
|
+
throw new Error(describeChannelStatus(err));
|
|
8266
|
+
}
|
|
8267
|
+
this.logger.log(`invite: invitation created email=${maskEmail(normalizedEmail)} role=${logSafe(role)} tenantId=${logSafe(tenantId)} inviterUserId=${logSafe(inviterUserId)}`);
|
|
7746
8268
|
}
|
|
7747
8269
|
// ---------------------------------------------------------------------------
|
|
7748
8270
|
// acceptInvitation()
|
|
@@ -7942,7 +8464,10 @@ exports.InvitationService = class _InvitationService {
|
|
|
7942
8464
|
*/
|
|
7943
8465
|
async revokeInvitation(revokerUserId, email, tenantId) {
|
|
7944
8466
|
const normalizedEmail = normalizeEmail(email);
|
|
7945
|
-
const revoker = await this.userRepo.findById(
|
|
8467
|
+
const revoker = await this.userRepo.findById({
|
|
8468
|
+
id: revokerUserId,
|
|
8469
|
+
tenantId
|
|
8470
|
+
});
|
|
7946
8471
|
if (!revoker) {
|
|
7947
8472
|
throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
|
|
7948
8473
|
}
|
|
@@ -7958,12 +8483,12 @@ exports.InvitationService = class _InvitationService {
|
|
|
7958
8483
|
const raw = await this.redis.get(`inv:${tokenHash}`);
|
|
7959
8484
|
const invitation = raw === null ? null : this.parseInvitation(raw);
|
|
7960
8485
|
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`);
|
|
8486
|
+
this.logger.warn(`revokeInvitation: refused email=${maskEmail(normalizedEmail)} tenantId=${logSafe(tenantId)} revokerUserId=${logSafe(revokerUserId)} \u2014 outranked by the invitation`);
|
|
7962
8487
|
return false;
|
|
7963
8488
|
}
|
|
7964
8489
|
await this.redis.del(indexKey);
|
|
7965
8490
|
const removed = await this.redis.del(`inv:${tokenHash}`);
|
|
7966
|
-
this.logger.log(`revokeInvitation: invitation withdrawn email=${maskEmail(normalizedEmail)} tenantId=${logSafe(tenantId)} revokerUserId=${revokerUserId}`);
|
|
8491
|
+
this.logger.log(`revokeInvitation: invitation withdrawn email=${maskEmail(normalizedEmail)} tenantId=${logSafe(tenantId)} revokerUserId=${logSafe(revokerUserId)}`);
|
|
7967
8492
|
return removed;
|
|
7968
8493
|
}
|
|
7969
8494
|
/**
|
|
@@ -8010,10 +8535,13 @@ exports.InvitationService = class _InvitationService {
|
|
|
8010
8535
|
* grant what the invitation grants.
|
|
8011
8536
|
*/
|
|
8012
8537
|
async assertInviterStillAuthorised(invitation) {
|
|
8013
|
-
const inviter = await this.userRepo.findById(
|
|
8538
|
+
const inviter = await this.userRepo.findById({
|
|
8539
|
+
id: invitation.inviterUserId,
|
|
8540
|
+
tenantId: invitation.tenantId
|
|
8541
|
+
});
|
|
8014
8542
|
const stillAuthorised = inviter !== null && this.inGoodStanding(inviter) && inviter.tenantId === invitation.tenantId && hasRole(inviter.role, invitation.role, this.options.roles.hierarchy);
|
|
8015
8543
|
if (!stillAuthorised) {
|
|
8016
|
-
this.logger.warn(`acceptInvitation: the inviter can no longer grant this invitation inviterUserId=${invitation.inviterUserId} role=${invitation.role}`);
|
|
8544
|
+
this.logger.warn(`acceptInvitation: the inviter can no longer grant this invitation inviterUserId=${logSafe(invitation.inviterUserId)} role=${logSafe(invitation.role)}`);
|
|
8017
8545
|
throw new AuthException(AUTH_ERROR_CODES.INVALID_INVITATION_TOKEN);
|
|
8018
8546
|
}
|
|
8019
8547
|
}
|
|
@@ -8040,7 +8568,10 @@ exports.InvitationService = class _InvitationService {
|
|
|
8040
8568
|
throw new AuthException(AUTH_ERROR_CODES.INVALID_INVITATION_TOKEN);
|
|
8041
8569
|
}
|
|
8042
8570
|
await this.assertInviterStillAuthorised(invitation);
|
|
8043
|
-
const existing = await this.userRepo.findByEmail(
|
|
8571
|
+
const existing = await this.userRepo.findByEmail({
|
|
8572
|
+
email: invitation.email,
|
|
8573
|
+
tenantId: invitation.tenantId
|
|
8574
|
+
});
|
|
8044
8575
|
if (existing) {
|
|
8045
8576
|
throw new AuthException(AUTH_ERROR_CODES.EMAIL_ALREADY_EXISTS);
|
|
8046
8577
|
}
|
|
@@ -8057,16 +8588,22 @@ exports.InvitationService = class _InvitationService {
|
|
|
8057
8588
|
const { passwordHash: _ph, mfaSecret: _ms, mfaRecoveryCodes: _mrc, ...safeUser } = authUser;
|
|
8058
8589
|
const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
|
|
8059
8590
|
if (this.options.sessions.enabled) {
|
|
8060
|
-
await this.sessionService.createSession(
|
|
8591
|
+
await this.sessionService.createSession({
|
|
8592
|
+
userId: safeUser.id,
|
|
8593
|
+
tenantId: safeUser.tenantId,
|
|
8594
|
+
rawRefreshToken: result.rawRefreshToken,
|
|
8595
|
+
ip,
|
|
8596
|
+
userAgent
|
|
8597
|
+
});
|
|
8061
8598
|
}
|
|
8062
|
-
this.logger.log(`acceptInvitation: invitation accepted userId=${safeUser.id} tenantId=${invitation.tenantId} role=${invitation.role}`);
|
|
8599
|
+
this.logger.log(`acceptInvitation: invitation accepted userId=${logSafe(safeUser.id)} tenantId=${logSafe(invitation.tenantId)} role=${logSafe(invitation.role)}`);
|
|
8063
8600
|
if (this.hooks?.afterInvitationAccepted) {
|
|
8064
8601
|
void Promise.resolve(this.hooks.afterInvitationAccepted(safeUser, {
|
|
8065
8602
|
ip,
|
|
8066
8603
|
userAgent,
|
|
8067
8604
|
sanitizedHeaders: sanitizeHeaders(headers)
|
|
8068
8605
|
})).catch((err) => {
|
|
8069
|
-
this.logger.error(
|
|
8606
|
+
this.logger.error(`afterInvitationAccepted hook threw: ${describeChannelStatus(err)}`);
|
|
8070
8607
|
});
|
|
8071
8608
|
}
|
|
8072
8609
|
return result;
|
|
@@ -8612,6 +9149,7 @@ function isMfaSetupData(value) {
|
|
|
8612
9149
|
return typeof v["encryptedSecret"] === "string" && typeof v["encryptedPlainCodes"] === "string" && Array.isArray(v["hashedCodes"]) && v["hashedCodes"].every((code) => typeof code === "string");
|
|
8613
9150
|
}
|
|
8614
9151
|
__name(isMfaSetupData, "isMfaSetupData");
|
|
9152
|
+
var PLANE_TENANT_MESSAGE = "tenantId must be a non-empty value on the dashboard plane and absent on the platform plane";
|
|
8615
9153
|
exports.MfaService = class _MfaService {
|
|
8616
9154
|
static {
|
|
8617
9155
|
__name(this, "MfaService");
|
|
@@ -8677,10 +9215,15 @@ exports.MfaService = class _MfaService {
|
|
|
8677
9215
|
if (context === "platform" && this.platformUserRepo) {
|
|
8678
9216
|
await this.platformUserRepo.updateMfa(userId, update);
|
|
8679
9217
|
} else {
|
|
8680
|
-
|
|
9218
|
+
this.assertDashboardTenant(tenantId);
|
|
9219
|
+
await this.userRepo.updateMfa({
|
|
9220
|
+
id: userId,
|
|
9221
|
+
tenantId,
|
|
9222
|
+
data: update
|
|
9223
|
+
});
|
|
8681
9224
|
}
|
|
8682
9225
|
} catch (err) {
|
|
8683
|
-
this.logger.error(
|
|
9226
|
+
this.logger.error(`re-encryption under the current MFA key failed: ${describeChannelStatus(err)}`);
|
|
8684
9227
|
}
|
|
8685
9228
|
}
|
|
8686
9229
|
/**
|
|
@@ -8721,7 +9264,7 @@ exports.MfaService = class _MfaService {
|
|
|
8721
9264
|
* @throws {@link AuthException} `MFA_STATE_CONFLICT` when another transition holds the lock.
|
|
8722
9265
|
*/
|
|
8723
9266
|
async transitionMfaRecord(context, userId, tenantId, mutate) {
|
|
8724
|
-
const scopedLockKey = `mfalock:${hmacSha256(
|
|
9267
|
+
const scopedLockKey = `mfalock:${hmacSha256(userSubject(context, userId, tenantId), this.options.hmacKey)}`;
|
|
8725
9268
|
const legacyLockKey = `mfalock:${hmacSha256(`${context}:${userId}`, this.options.hmacKey)}`;
|
|
8726
9269
|
const acquireLegacy = legacyLockKey !== scopedLockKey;
|
|
8727
9270
|
const lockToken = crypto.randomBytes(16).toString("hex");
|
|
@@ -8748,7 +9291,12 @@ exports.MfaService = class _MfaService {
|
|
|
8748
9291
|
if (context === "platform" && this.platformUserRepo) {
|
|
8749
9292
|
await this.platformUserRepo.updateMfa(userId, write);
|
|
8750
9293
|
} else {
|
|
8751
|
-
|
|
9294
|
+
this.assertDashboardTenant(tenantId);
|
|
9295
|
+
await this.userRepo.updateMfa({
|
|
9296
|
+
id: userId,
|
|
9297
|
+
tenantId,
|
|
9298
|
+
data: write
|
|
9299
|
+
});
|
|
8752
9300
|
}
|
|
8753
9301
|
return true;
|
|
8754
9302
|
} finally {
|
|
@@ -8828,7 +9376,7 @@ exports.MfaService = class _MfaService {
|
|
|
8828
9376
|
try {
|
|
8829
9377
|
parsed = JSON.parse(raw);
|
|
8830
9378
|
} catch {
|
|
8831
|
-
this.logger.warn(`parseSetupData: pending-setup payload is not valid JSON userId=${userId}`);
|
|
9379
|
+
this.logger.warn(`parseSetupData: pending-setup payload is not valid JSON userId=${logSafe(userId)}`);
|
|
8832
9380
|
throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
|
|
8833
9381
|
}
|
|
8834
9382
|
if (!isMfaSetupData(parsed)) {
|
|
@@ -8850,7 +9398,7 @@ exports.MfaService = class _MfaService {
|
|
|
8850
9398
|
try {
|
|
8851
9399
|
parsed = JSON.parse(raw);
|
|
8852
9400
|
} catch {
|
|
8853
|
-
this.logger.warn(`parsePlainRecoveryCodes: decrypted payload is not valid JSON userId=${userId}`);
|
|
9401
|
+
this.logger.warn(`parsePlainRecoveryCodes: decrypted payload is not valid JSON userId=${logSafe(userId)}`);
|
|
8854
9402
|
throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
|
|
8855
9403
|
}
|
|
8856
9404
|
if (!Array.isArray(parsed) || parsed.some((code) => typeof code !== "string")) {
|
|
@@ -8953,7 +9501,7 @@ exports.MfaService = class _MfaService {
|
|
|
8953
9501
|
* @returns `true` when this challenge is the one that claimed it.
|
|
8954
9502
|
*/
|
|
8955
9503
|
async claimRecoveryCode(context, userId, code, tenantId) {
|
|
8956
|
-
const claimKey = `rcu:${hmacSha256(`${
|
|
9504
|
+
const claimKey = `rcu:${hmacSha256(`${userSubject(context, userId, tenantId)}:${code}`, this.options.hmacKey)}`;
|
|
8957
9505
|
return await this.redis.setnx(claimKey, RECOVERY_CODE_CLAIM_TTL_SECONDS);
|
|
8958
9506
|
}
|
|
8959
9507
|
/**
|
|
@@ -9019,7 +9567,7 @@ exports.MfaService = class _MfaService {
|
|
|
9019
9567
|
const user = await this.fetchUserForContext(context, userId, tenantId);
|
|
9020
9568
|
if (user.mfaEnabled) throw new AuthException(AUTH_ERROR_CODES.MFA_ALREADY_ENABLED);
|
|
9021
9569
|
await this.assertReauthenticated(context, userId, user.passwordHash, password, tenantId);
|
|
9022
|
-
const setupKey = `mfa_setup:${hmacSha256(
|
|
9570
|
+
const setupKey = `mfa_setup:${hmacSha256(userSubject(context, userId, tenantId), this.options.hmacKey)}`;
|
|
9023
9571
|
const existingFast = await this.redis.get(setupKey);
|
|
9024
9572
|
if (existingFast !== null) {
|
|
9025
9573
|
const data = this.parseSetupData(existingFast, userId);
|
|
@@ -9062,7 +9610,7 @@ exports.MfaService = class _MfaService {
|
|
|
9062
9610
|
await this.redis.set(setupKey, payload, MFA_SETUP_TTL_SECONDS);
|
|
9063
9611
|
}
|
|
9064
9612
|
const qrCodeUri = buildTotpUri(secretBase32, user.email, this.mfaOptions.issuer);
|
|
9065
|
-
this.logger.log(`setup: MFA setup initiated userId=${userId} context=${context}`);
|
|
9613
|
+
this.logger.log(`setup: MFA setup initiated userId=${logSafe(userId)} context=${context}`);
|
|
9066
9614
|
return {
|
|
9067
9615
|
secret: secretBase32,
|
|
9068
9616
|
qrCodeUri,
|
|
@@ -9099,7 +9647,7 @@ exports.MfaService = class _MfaService {
|
|
|
9099
9647
|
}
|
|
9100
9648
|
const user = await this.fetchUserForContext(context, userId, tenantId);
|
|
9101
9649
|
if (user.mfaEnabled) throw new AuthException(AUTH_ERROR_CODES.MFA_ALREADY_ENABLED);
|
|
9102
|
-
const setupKey = `mfa_setup:${hmacSha256(
|
|
9650
|
+
const setupKey = `mfa_setup:${hmacSha256(userSubject(context, userId, tenantId), this.options.hmacKey)}`;
|
|
9103
9651
|
const raw = await this.redis.get(setupKey);
|
|
9104
9652
|
if (raw === null) throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
|
|
9105
9653
|
const data = this.parseSetupData(raw, userId);
|
|
@@ -9107,12 +9655,12 @@ exports.MfaService = class _MfaService {
|
|
|
9107
9655
|
const totpWindow = this.mfaOptions.totpWindow;
|
|
9108
9656
|
const codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, code, totpWindow, tenantId);
|
|
9109
9657
|
if (!codeValid) {
|
|
9110
|
-
this.logger.warn(`verifyAndEnable: invalid TOTP code userId=${userId}`);
|
|
9658
|
+
this.logger.warn(`verifyAndEnable: invalid TOTP code userId=${logSafe(userId)}`);
|
|
9111
9659
|
throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
|
|
9112
9660
|
}
|
|
9113
9661
|
const consumed = await this.redis.getdel(setupKey);
|
|
9114
9662
|
if (consumed === null) {
|
|
9115
|
-
this.logger.warn(`verifyAndEnable: setup key consumed by concurrent request userId=${userId}`);
|
|
9663
|
+
this.logger.warn(`verifyAndEnable: setup key consumed by concurrent request userId=${logSafe(userId)}`);
|
|
9116
9664
|
throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
|
|
9117
9665
|
}
|
|
9118
9666
|
await this.transitionMfaRecord(context, userId, tenantId, () => ({
|
|
@@ -9120,10 +9668,10 @@ exports.MfaService = class _MfaService {
|
|
|
9120
9668
|
mfaSecret: data.encryptedSecret,
|
|
9121
9669
|
mfaRecoveryCodes: data.hashedCodes
|
|
9122
9670
|
}));
|
|
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
|
-
|
|
9671
|
+
await this.redis.invalidateUserSessions(userId, tenantId, context);
|
|
9672
|
+
await this.redis.bumpUserTokenEpoch(userId, tenantId, context);
|
|
9673
|
+
this.logger.log(`verifyAndEnable: MFA enabled userId=${logSafe(userId)} context=${context}`);
|
|
9674
|
+
this.notify("verifyAndEnable", userId, user, (provider, tenant, email) => provider.sendMfaEnabledNotification(tenant, email));
|
|
9127
9675
|
if (this.hooks.afterMfaEnabled) {
|
|
9128
9676
|
const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
|
|
9129
9677
|
void Promise.resolve(this.hooks.afterMfaEnabled(safeUser, {
|
|
@@ -9157,7 +9705,7 @@ exports.MfaService = class _MfaService {
|
|
|
9157
9705
|
async challenge(mfaTempToken, code, ip, userAgent) {
|
|
9158
9706
|
const { userId, context, tenantId, jti: tempTokenJti } = await this.tokenManager.verifyMfaTempToken(mfaTempToken);
|
|
9159
9707
|
if (await this.isMfaFlowLockedOut("challenge", context, userId, tenantId)) {
|
|
9160
|
-
this.logger.warn(`challenge: account locked userId=${userId}`);
|
|
9708
|
+
this.logger.warn(`challenge: account locked userId=${logSafe(userId)}`);
|
|
9161
9709
|
throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
|
|
9162
9710
|
}
|
|
9163
9711
|
const user = await this.fetchUserForContext(context, userId, tenantId);
|
|
@@ -9178,7 +9726,7 @@ exports.MfaService = class _MfaService {
|
|
|
9178
9726
|
}
|
|
9179
9727
|
if (!codeValid) {
|
|
9180
9728
|
await this.recordMfaFlowFailure("challenge", context, userId, tenantId);
|
|
9181
|
-
this.logger.warn(`challenge: invalid MFA code userId=${userId} context=${context}`);
|
|
9729
|
+
this.logger.warn(`challenge: invalid MFA code userId=${logSafe(userId)} context=${context}`);
|
|
9182
9730
|
throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
|
|
9183
9731
|
}
|
|
9184
9732
|
await this.resetMfaFlowFailures("challenge", context, userId, tenantId);
|
|
@@ -9211,14 +9759,20 @@ exports.MfaService = class _MfaService {
|
|
|
9211
9759
|
} else if (encryptedUnderRetiredKey) {
|
|
9212
9760
|
void this.reencryptSecret(userId, context, secretBase32, user.mfaRecoveryCodes ?? [], tenantId);
|
|
9213
9761
|
}
|
|
9214
|
-
this.logger.log(`challenge: MFA challenge passed userId=${userId} context=${context}`);
|
|
9762
|
+
this.logger.log(`challenge: MFA challenge passed userId=${logSafe(userId)} context=${context}`);
|
|
9215
9763
|
if (context === "dashboard") {
|
|
9216
9764
|
const safeUser = this.toSafeUser(user);
|
|
9217
9765
|
const result2 = await this.tokenManager.issueTokens(safeUser, ip, userAgent, {
|
|
9218
9766
|
mfaVerified: true
|
|
9219
9767
|
});
|
|
9220
9768
|
if (this.options.sessions.enabled) {
|
|
9221
|
-
await this.sessionService.createSession(
|
|
9769
|
+
await this.sessionService.createSession({
|
|
9770
|
+
userId: safeUser.id,
|
|
9771
|
+
tenantId: safeUser.tenantId,
|
|
9772
|
+
rawRefreshToken: result2.rawRefreshToken,
|
|
9773
|
+
ip,
|
|
9774
|
+
userAgent
|
|
9775
|
+
});
|
|
9222
9776
|
}
|
|
9223
9777
|
if (this.hooks.afterLogin) {
|
|
9224
9778
|
void Promise.resolve(this.hooks.afterLogin(safeUser, {
|
|
@@ -9276,7 +9830,7 @@ exports.MfaService = class _MfaService {
|
|
|
9276
9830
|
const user = await this.fetchUserForContext(context, userId, tenantId);
|
|
9277
9831
|
if (!user.mfaEnabled) throw new AuthException(AUTH_ERROR_CODES.MFA_NOT_ENABLED);
|
|
9278
9832
|
if (await this.isMfaFlowLockedOut("disable", context, userId, tenantId)) {
|
|
9279
|
-
this.logger.warn(`disable: account locked userId=${userId} context=${context}`);
|
|
9833
|
+
this.logger.warn(`disable: account locked userId=${logSafe(userId)} context=${context}`);
|
|
9280
9834
|
throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
|
|
9281
9835
|
}
|
|
9282
9836
|
if (!user.mfaSecret) {
|
|
@@ -9287,7 +9841,7 @@ exports.MfaService = class _MfaService {
|
|
|
9287
9841
|
const codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, code, totpWindow, tenantId);
|
|
9288
9842
|
if (!codeValid) {
|
|
9289
9843
|
await this.recordMfaFlowFailure("disable", context, userId, tenantId);
|
|
9290
|
-
this.logger.warn(`disable: invalid MFA code userId=${userId} context=${context}`);
|
|
9844
|
+
this.logger.warn(`disable: invalid MFA code userId=${logSafe(userId)} context=${context}`);
|
|
9291
9845
|
throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
|
|
9292
9846
|
}
|
|
9293
9847
|
await this.resetMfaFlowFailures("disable", context, userId, tenantId);
|
|
@@ -9296,10 +9850,10 @@ exports.MfaService = class _MfaService {
|
|
|
9296
9850
|
mfaSecret: null,
|
|
9297
9851
|
mfaRecoveryCodes: null
|
|
9298
9852
|
}));
|
|
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
|
-
|
|
9853
|
+
await this.redis.invalidateUserSessions(userId, tenantId, context);
|
|
9854
|
+
await this.redis.bumpUserTokenEpoch(userId, tenantId, context);
|
|
9855
|
+
this.logger.log(`disable: MFA disabled userId=${logSafe(userId)} context=${context}`);
|
|
9856
|
+
this.notify("disable", userId, user, (provider, tenant, email) => provider.sendMfaDisabledNotification(tenant, email));
|
|
9303
9857
|
const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
|
|
9304
9858
|
if (this.hooks.afterMfaDisabled) {
|
|
9305
9859
|
void Promise.resolve(this.hooks.afterMfaDisabled(safeUser, {
|
|
@@ -9355,7 +9909,7 @@ exports.MfaService = class _MfaService {
|
|
|
9355
9909
|
this.assertPlaneTenant(context, tenantId);
|
|
9356
9910
|
const user = await this.fetchUserForContext(context, userId, tenantId);
|
|
9357
9911
|
if (!user.mfaEnabled) {
|
|
9358
|
-
this.logger.log(`resetMfa: no second factor to remove userId=${userId} context=${context}`);
|
|
9912
|
+
this.logger.log(`resetMfa: no second factor to remove userId=${logSafe(userId)} context=${context}`);
|
|
9359
9913
|
return;
|
|
9360
9914
|
}
|
|
9361
9915
|
await this.transitionMfaRecord(context, userId, tenantId, () => ({
|
|
@@ -9363,10 +9917,10 @@ exports.MfaService = class _MfaService {
|
|
|
9363
9917
|
mfaSecret: null,
|
|
9364
9918
|
mfaRecoveryCodes: null
|
|
9365
9919
|
}));
|
|
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
|
-
|
|
9920
|
+
await this.redis.invalidateUserSessions(userId, tenantId, context);
|
|
9921
|
+
await this.redis.bumpUserTokenEpoch(userId, tenantId, context);
|
|
9922
|
+
this.logger.warn(`resetMfa: MFA removed administratively userId=${logSafe(userId)} context=${context}`);
|
|
9923
|
+
this.notify("resetMfa", userId, user, (provider, tenant, email) => provider.sendMfaDisabledNotification(tenant, email));
|
|
9370
9924
|
const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
|
|
9371
9925
|
if (this.hooks.afterMfaDisabled) {
|
|
9372
9926
|
void Promise.resolve(this.hooks.afterMfaDisabled(safeUser, {
|
|
@@ -9427,7 +9981,7 @@ exports.MfaService = class _MfaService {
|
|
|
9427
9981
|
const user = await this.fetchUserForContext(context, userId, tenantId);
|
|
9428
9982
|
if (!user.mfaEnabled) throw new AuthException(AUTH_ERROR_CODES.MFA_NOT_ENABLED);
|
|
9429
9983
|
if (await this.isMfaFlowLockedOut("disable", context, userId, tenantId)) {
|
|
9430
|
-
this.logger.warn(`regenerateRecoveryCodes: account locked userId=${userId} context=${context}`);
|
|
9984
|
+
this.logger.warn(`regenerateRecoveryCodes: account locked userId=${logSafe(userId)} context=${context}`);
|
|
9431
9985
|
throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
|
|
9432
9986
|
}
|
|
9433
9987
|
if (!user.mfaSecret) {
|
|
@@ -9438,7 +9992,7 @@ exports.MfaService = class _MfaService {
|
|
|
9438
9992
|
const codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, totpCode, totpWindow, tenantId);
|
|
9439
9993
|
if (!codeValid) {
|
|
9440
9994
|
await this.recordMfaFlowFailure("disable", context, userId, tenantId);
|
|
9441
|
-
this.logger.warn(`regenerateRecoveryCodes: invalid MFA code userId=${userId} context=${context}`);
|
|
9995
|
+
this.logger.warn(`regenerateRecoveryCodes: invalid MFA code userId=${logSafe(userId)} context=${context}`);
|
|
9442
9996
|
throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
|
|
9443
9997
|
}
|
|
9444
9998
|
await this.resetMfaFlowFailures("disable", context, userId, tenantId);
|
|
@@ -9453,7 +10007,7 @@ exports.MfaService = class _MfaService {
|
|
|
9453
10007
|
};
|
|
9454
10008
|
});
|
|
9455
10009
|
if (!replaced) throw new AuthException(AUTH_ERROR_CODES.MFA_NOT_ENABLED);
|
|
9456
|
-
this.logger.log(`regenerateRecoveryCodes: recovery codes regenerated userId=${userId} context=${context}`);
|
|
10010
|
+
this.logger.log(`regenerateRecoveryCodes: recovery codes regenerated userId=${logSafe(userId)} context=${context}`);
|
|
9457
10011
|
if (this.hooks.afterMfaRecoveryCodesRegenerated) {
|
|
9458
10012
|
const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
|
|
9459
10013
|
void Promise.resolve(this.hooks.afterMfaRecoveryCodesRegenerated(safeUser, {
|
|
@@ -9473,17 +10027,21 @@ exports.MfaService = class _MfaService {
|
|
|
9473
10027
|
/**
|
|
9474
10028
|
* Verifies a TOTP code and enforces anti-replay within the validation window.
|
|
9475
10029
|
*
|
|
9476
|
-
* Stores a Redis key `tu:{hmac}` where `hmac = hmacSha256("{
|
|
9477
|
-
*
|
|
9478
|
-
* rejected as a replay.
|
|
9479
|
-
*
|
|
10030
|
+
* Stores a Redis key `tu:{hmac}` where `hmac = hmacSha256("{userSubject}:{code}", hmacKey)` —
|
|
10031
|
+
* so the marker is scoped to the plane and, on the dashboard plane, to the tenant. A second
|
|
10032
|
+
* submission of the same code within the TTL is rejected as a replay. Binding the marker to
|
|
10033
|
+
* both the subject and the code value prevents code disclosure in Redis and cross-user,
|
|
10034
|
+
* cross-tenant and cross-plane replay alike.
|
|
10035
|
+
*
|
|
10036
|
+
* A second marker under the pre-scoping preimage `{context}:{userId}:{code}` is written and
|
|
10037
|
+
* required alongside it; see the call site for why both must be fresh during a rolling upgrade.
|
|
9480
10038
|
*
|
|
9481
10039
|
* @returns `true` if the code is valid and has not been replayed, `false` otherwise.
|
|
9482
10040
|
*/
|
|
9483
10041
|
async verifyTotpWithAntiReplay(context, userId, secretBase32, code, window, tenantId) {
|
|
9484
10042
|
if (!verifyTotp(secretBase32, code, window)) return false;
|
|
9485
10043
|
const ttl = totpAntiReplayTtlSeconds(window);
|
|
9486
|
-
const scopedReplayKey = `tu:${hmacSha256(`${
|
|
10044
|
+
const scopedReplayKey = `tu:${hmacSha256(`${userSubject(context, userId, tenantId)}:${code}`, this.options.hmacKey)}`;
|
|
9487
10045
|
const legacyReplayKey = `tu:${hmacSha256(`${context}:${userId}:${code}`, this.options.hmacKey)}`;
|
|
9488
10046
|
const scopedIsNew = await this.redis.setnx(scopedReplayKey, ttl);
|
|
9489
10047
|
if (scopedReplayKey === legacyReplayKey) return scopedIsNew;
|
|
@@ -9518,13 +10076,13 @@ exports.MfaService = class _MfaService {
|
|
|
9518
10076
|
if (passwordHash === null) {
|
|
9519
10077
|
const recent = await this.redis.get(recentAuthKey(context, userId, this.options.hmacKey, tenantId));
|
|
9520
10078
|
if (recent === null) {
|
|
9521
|
-
this.logger.warn(`reauthenticate: no recent authentication userId=${userId} context=${context}`);
|
|
10079
|
+
this.logger.warn(`reauthenticate: no recent authentication userId=${logSafe(userId)} context=${context}`);
|
|
9522
10080
|
throw new AuthException(AUTH_ERROR_CODES.REAUTHENTICATION_REQUIRED);
|
|
9523
10081
|
}
|
|
9524
10082
|
return;
|
|
9525
10083
|
}
|
|
9526
10084
|
if (await this.isMfaFlowLockedOut("reauth", context, userId, tenantId)) {
|
|
9527
|
-
this.logger.warn(`reauthenticate: account locked userId=${userId} context=${context}`);
|
|
10085
|
+
this.logger.warn(`reauthenticate: account locked userId=${logSafe(userId)} context=${context}`);
|
|
9528
10086
|
throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
|
|
9529
10087
|
}
|
|
9530
10088
|
const supplied = password ?? "";
|
|
@@ -9536,31 +10094,28 @@ exports.MfaService = class _MfaService {
|
|
|
9536
10094
|
await this.resetMfaFlowFailures("reauth", context, userId, tenantId);
|
|
9537
10095
|
}
|
|
9538
10096
|
/**
|
|
9539
|
-
*
|
|
9540
|
-
* account is blocked.
|
|
10097
|
+
* Asserts a dashboard-plane call carries a tenant, narrowing it to `string` for the caller.
|
|
9541
10098
|
*
|
|
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.
|
|
10099
|
+
* This is the dashboard half of {@link assertPlaneTenant}, split out for one reason: an
|
|
10100
|
+
* assertion signature is the only way to state "past this point the tenant is present" to the
|
|
10101
|
+
* type system. `IUserRepository.findById` requires the tenant, and the account read behind the
|
|
10102
|
+
* MFA flows sits under a `context === 'dashboard'` branch where a `void` guard run earlier in
|
|
10103
|
+
* the caller has narrowed nothing. Without this the branch had to pass `string | undefined`
|
|
10104
|
+
* into a `string` parameter, which is precisely the tenant-blind read the guard exists to stop.
|
|
9554
10105
|
*
|
|
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.
|
|
10106
|
+
* @param tenantId - The tenant supplied by the caller, if any.
|
|
10107
|
+
* @throws {@link AuthException} `VALIDATION` (400) when it is missing or blank.
|
|
9563
10108
|
*/
|
|
10109
|
+
assertDashboardTenant(tenantId) {
|
|
10110
|
+
if (tenantId === void 0 || tenantId === "") {
|
|
10111
|
+
throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
|
|
10112
|
+
{
|
|
10113
|
+
field: "tenantId",
|
|
10114
|
+
message: PLANE_TENANT_MESSAGE
|
|
10115
|
+
}
|
|
10116
|
+
]);
|
|
10117
|
+
}
|
|
10118
|
+
}
|
|
9564
10119
|
/**
|
|
9565
10120
|
* A dashboard MFA flow MUST carry the tenant it was authenticated in; a platform flow MUST NOT.
|
|
9566
10121
|
*
|
|
@@ -9577,11 +10132,15 @@ exports.MfaService = class _MfaService {
|
|
|
9577
10132
|
* platform call supplies one.
|
|
9578
10133
|
*/
|
|
9579
10134
|
assertPlaneTenant(context, tenantId) {
|
|
9580
|
-
if (context === "dashboard"
|
|
10135
|
+
if (context === "dashboard") {
|
|
10136
|
+
this.assertDashboardTenant(tenantId);
|
|
10137
|
+
return;
|
|
10138
|
+
}
|
|
10139
|
+
if (tenantId !== void 0) {
|
|
9581
10140
|
throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
|
|
9582
10141
|
{
|
|
9583
10142
|
field: "tenantId",
|
|
9584
|
-
message:
|
|
10143
|
+
message: PLANE_TENANT_MESSAGE
|
|
9585
10144
|
}
|
|
9586
10145
|
]);
|
|
9587
10146
|
}
|
|
@@ -9593,7 +10152,7 @@ exports.MfaService = class _MfaService {
|
|
|
9593
10152
|
*
|
|
9594
10153
|
* A rolling upgrade runs old and new code against one Redis at once: on the dashboard plane an
|
|
9595
10154
|
* old pod counts a failure under `{flow}:{plane}:{userId}` while a new pod counts it under
|
|
9596
|
-
* `{flow}:{
|
|
10155
|
+
* `{flow}:{userSubject}`, and either alone leaves a hole — a lockout an old pod filled would not
|
|
9597
10156
|
* stop a new pod, and a success on one would not clear the other. For one release every read
|
|
9598
10157
|
* consults both and every write touches both, so the two move as one; a later release drops the
|
|
9599
10158
|
* legacy arm. On the platform plane the two ids are identical (no tenant ever entered the
|
|
@@ -9604,7 +10163,7 @@ exports.MfaService = class _MfaService {
|
|
|
9604
10163
|
mfaFlowCounterIds(flow, context, userId, tenantId) {
|
|
9605
10164
|
return {
|
|
9606
10165
|
legacy: hmacSha256(`${flow}:${context}:${userId}`, this.options.hmacKey),
|
|
9607
|
-
scoped: hmacSha256(`${flow}:${
|
|
10166
|
+
scoped: hmacSha256(`${flow}:${userSubject(context, userId, tenantId)}`, this.options.hmacKey)
|
|
9608
10167
|
};
|
|
9609
10168
|
}
|
|
9610
10169
|
/**
|
|
@@ -9634,9 +10193,79 @@ exports.MfaService = class _MfaService {
|
|
|
9634
10193
|
await this.bruteForce.resetFailures(scoped);
|
|
9635
10194
|
if (legacy !== scoped) await this.bruteForce.resetFailures(legacy);
|
|
9636
10195
|
}
|
|
10196
|
+
/**
|
|
10197
|
+
* Sends an MFA state-change notice, fire-and-forget, with the recipient kept out of the log.
|
|
10198
|
+
*
|
|
10199
|
+
* **Not awaited, and that is the fix, not a shortcut.** These three sends used to be awaited
|
|
10200
|
+
* with no `catch`, so a rejected delivery travelled out of the service to `AuthExceptionFilter`
|
|
10201
|
+
* — which answered the caller with an error for an operation that had ALREADY completed. By
|
|
10202
|
+
* that point the secret is written, the sessions are invalidated and the token epoch is bumped;
|
|
10203
|
+
* the user's second factor is on, and telling them it failed is how they end up locked out of
|
|
10204
|
+
* an account they just secured. `PasswordResetService.notifyPasswordChanged` had reached the
|
|
10205
|
+
* same conclusion for the same reason.
|
|
10206
|
+
*
|
|
10207
|
+
* **And the address does not reach the log.** The filter logged that error raw, and an SMTP
|
|
10208
|
+
* rejection routinely NAMES the recipient it refused (`550 user@example.com: recipient
|
|
10209
|
+
* rejected`) — no quoted body required, which makes it the likeliest exposure of the set.
|
|
10210
|
+
* `describeChannelStatus` publishes nothing the channel wrote, and nothing parsed off it either,
|
|
10211
|
+
* so no part of that name comes through. `withheld` covers the fields this line composes rather than the error, and
|
|
10212
|
+
* `safeLogLine` checks the seam the template opens between them.
|
|
10213
|
+
*
|
|
10214
|
+
* @param origin - The calling flow, for the log line.
|
|
10215
|
+
* @param userId - Whose account changed.
|
|
10216
|
+
* @param user - The account, read for its tenant and address.
|
|
10217
|
+
* @param send - Which notice to dispatch.
|
|
10218
|
+
*/
|
|
10219
|
+
notify(origin, userId, user, send) {
|
|
10220
|
+
const provider = this.emailProvider;
|
|
10221
|
+
const tenantId = emailTenantOf(user);
|
|
10222
|
+
const email = user.email;
|
|
10223
|
+
const withheld = [
|
|
10224
|
+
email
|
|
10225
|
+
];
|
|
10226
|
+
void (async () => {
|
|
10227
|
+
try {
|
|
10228
|
+
await send(provider, tenantId, email);
|
|
10229
|
+
} catch (err) {
|
|
10230
|
+
this.logger.error(safeLogLine(`${origin}: MFA notice delivery failed for user ${logSafe(userId)}: ` + describeChannelStatus(err), withheld));
|
|
10231
|
+
}
|
|
10232
|
+
})();
|
|
10233
|
+
}
|
|
10234
|
+
/**
|
|
10235
|
+
* Fetches a user from the correct repository based on the MFA context, and refuses one whose
|
|
10236
|
+
* account is blocked.
|
|
10237
|
+
*
|
|
10238
|
+
* The status gate lives here rather than in each caller because every entry point that
|
|
10239
|
+
* reaches this method changes or spends an authentication factor, and every one of them
|
|
10240
|
+
* must refuse a suspended or banned account. It used to live in `challenge` alone, so
|
|
10241
|
+
* `setup`, `verifyAndEnable`, `disable` and `regenerateRecoveryCodes` had no gate at all:
|
|
10242
|
+
* an operator who suspended a compromised account bought nothing against an attacker still
|
|
10243
|
+
* holding an unexpired access token, who could turn the second factor off — or enrol their
|
|
10244
|
+
* own authenticator over it — for the token's remaining lifetime. Nothing else covers that
|
|
10245
|
+
* window: no status change bumps the token epoch, so the per-request check is the only
|
|
10246
|
+
* defence, and neither MFA controller composes `UserStatusGuard` (the platform plane has no
|
|
10247
|
+
* status guard at all). Every other authority-bearing route in the library does gate on
|
|
10248
|
+
* status; changing an authentication factor is at least as privileged as minting an
|
|
10249
|
+
* invitation.
|
|
10250
|
+
*
|
|
10251
|
+
* Gating the fetch rather than the callers is deliberate: a method added later inherits the
|
|
10252
|
+
* check instead of having to remember it.
|
|
10253
|
+
*
|
|
10254
|
+
* @param context - Which identity plane the caller is acting on.
|
|
10255
|
+
* @param userId - The subject taken from the verified token.
|
|
10256
|
+
* @param tenantId - The tenant the caller was authenticated in, on the dashboard plane;
|
|
10257
|
+
* absent on the platform plane, whose admins belong to none.
|
|
10258
|
+
* @returns The account record, guaranteed to be in good standing.
|
|
10259
|
+
* @throws `TOKEN_INVALID` if the user is not found.
|
|
10260
|
+
* @throws {@link AuthException} the status error when the account is blocked.
|
|
10261
|
+
*/
|
|
9637
10262
|
async fetchUserForContext(context, userId, tenantId) {
|
|
9638
10263
|
if (context === "dashboard") {
|
|
9639
|
-
|
|
10264
|
+
this.assertDashboardTenant(tenantId);
|
|
10265
|
+
const user = await this.userRepo.findById({
|
|
10266
|
+
id: userId,
|
|
10267
|
+
tenantId
|
|
10268
|
+
});
|
|
9640
10269
|
if (!user) throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
|
|
9641
10270
|
assertNotBlocked(user.status, this.options.blockedStatuses);
|
|
9642
10271
|
return user;
|
|
@@ -10446,7 +11075,10 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10446
11075
|
return;
|
|
10447
11076
|
}
|
|
10448
11077
|
try {
|
|
10449
|
-
const user = tenantScoped(await this.userRepo.findByEmail(
|
|
11078
|
+
const user = tenantScoped(await this.userRepo.findByEmail({
|
|
11079
|
+
email: dto.email,
|
|
11080
|
+
tenantId
|
|
11081
|
+
}), tenantId);
|
|
10450
11082
|
if (user && !this.isBlocked(user.status)) {
|
|
10451
11083
|
const { method } = this.options.passwordReset;
|
|
10452
11084
|
if (method === "otp") {
|
|
@@ -10456,7 +11088,7 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10456
11088
|
}
|
|
10457
11089
|
}
|
|
10458
11090
|
} catch (err) {
|
|
10459
|
-
this.logger.error(
|
|
11091
|
+
this.logger.error(`initiateReset: unexpected error: ${describeChannelStatus(err)}`);
|
|
10460
11092
|
} finally {
|
|
10461
11093
|
await sleep(Math.max(0, ANTI_ENUM_MIN_MS2 - (Date.now() - start)));
|
|
10462
11094
|
}
|
|
@@ -10544,7 +11176,10 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10544
11176
|
};
|
|
10545
11177
|
const identifier = this.otpIdentifier(tenantId, dto.email);
|
|
10546
11178
|
await this.otpService.verify(PASSWORD_RESET_PURPOSE, identifier, dto.otp);
|
|
10547
|
-
const user = tenantScoped(await this.userRepo.findByEmail(
|
|
11179
|
+
const user = tenantScoped(await this.userRepo.findByEmail({
|
|
11180
|
+
email: dto.email,
|
|
11181
|
+
tenantId
|
|
11182
|
+
}), tenantId);
|
|
10548
11183
|
if (!user) {
|
|
10549
11184
|
throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
|
|
10550
11185
|
}
|
|
@@ -10553,7 +11188,7 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10553
11188
|
userId: user.id,
|
|
10554
11189
|
email: dto.email,
|
|
10555
11190
|
tenantId,
|
|
10556
|
-
passwordFingerprint: await this.passwordFingerprintOf(user.id)
|
|
11191
|
+
passwordFingerprint: await this.passwordFingerprintOf(user.id, user.tenantId)
|
|
10557
11192
|
};
|
|
10558
11193
|
await this.redis.set(`pw_vtok:${sha256(rawVerifiedToken)}`, JSON.stringify(context), VERIFIED_TOKEN_TTL_SECONDS);
|
|
10559
11194
|
return rawVerifiedToken;
|
|
@@ -10585,12 +11220,15 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10585
11220
|
return;
|
|
10586
11221
|
}
|
|
10587
11222
|
try {
|
|
10588
|
-
const user = tenantScoped(await this.userRepo.findByEmail(
|
|
11223
|
+
const user = tenantScoped(await this.userRepo.findByEmail({
|
|
11224
|
+
email: dto.email,
|
|
11225
|
+
tenantId
|
|
11226
|
+
}), tenantId);
|
|
10589
11227
|
if (user && !this.isBlocked(user.status)) {
|
|
10590
11228
|
await this.sendOtp(dto.email, tenantId, user.id);
|
|
10591
11229
|
}
|
|
10592
11230
|
} catch (err) {
|
|
10593
|
-
this.logger.error(
|
|
11231
|
+
this.logger.error(`resendOtp: unexpected error: ${describeChannelStatus(err)}`);
|
|
10594
11232
|
} finally {
|
|
10595
11233
|
await sleep(Math.max(0, ANTI_ENUM_MIN_MS2 - (Date.now() - start)));
|
|
10596
11234
|
}
|
|
@@ -10616,7 +11254,7 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10616
11254
|
throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
|
|
10617
11255
|
}
|
|
10618
11256
|
await this.assertResetTokenStillBound(context);
|
|
10619
|
-
await this.applyPasswordReset(context.userId, newPassword);
|
|
11257
|
+
await this.applyPasswordReset(context.userId, context.tenantId, newPassword);
|
|
10620
11258
|
}
|
|
10621
11259
|
/**
|
|
10622
11260
|
* Direct OTP reset path: verifies and consumes the OTP, then updates the password.
|
|
@@ -10624,11 +11262,14 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10624
11262
|
async resetWithOtp(email, tenantId, otp, newPassword) {
|
|
10625
11263
|
const identifier = this.otpIdentifier(tenantId, email);
|
|
10626
11264
|
await this.otpService.verify(PASSWORD_RESET_PURPOSE, identifier, otp);
|
|
10627
|
-
const user = tenantScoped(await this.userRepo.findByEmail(
|
|
11265
|
+
const user = tenantScoped(await this.userRepo.findByEmail({
|
|
11266
|
+
email,
|
|
11267
|
+
tenantId
|
|
11268
|
+
}), tenantId);
|
|
10628
11269
|
if (!user) {
|
|
10629
11270
|
throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
|
|
10630
11271
|
}
|
|
10631
|
-
await this.applyPasswordReset(user.id, newPassword);
|
|
11272
|
+
await this.applyPasswordReset(user.id, user.tenantId, newPassword);
|
|
10632
11273
|
}
|
|
10633
11274
|
/**
|
|
10634
11275
|
* VerifiedToken reset path: atomically consumes the verifiedToken from Redis
|
|
@@ -10644,7 +11285,7 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10644
11285
|
throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
|
|
10645
11286
|
}
|
|
10646
11287
|
await this.assertResetTokenStillBound(context);
|
|
10647
|
-
await this.applyPasswordReset(context.userId, newPassword);
|
|
11288
|
+
await this.applyPasswordReset(context.userId, context.tenantId, newPassword);
|
|
10648
11289
|
}
|
|
10649
11290
|
/**
|
|
10650
11291
|
* Hashes the new password and updates it in the user repository.
|
|
@@ -10698,31 +11339,42 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10698
11339
|
* @throws {@link AuthException} `PASSWORD_COMPROMISED` when the new password is refused by
|
|
10699
11340
|
* the configured breach checker.
|
|
10700
11341
|
*/
|
|
10701
|
-
async changePassword(userId, dto, currentRefreshToken) {
|
|
10702
|
-
const user = await this.userRepo.findById(
|
|
11342
|
+
async changePassword(userId, tenantId, dto, currentRefreshToken) {
|
|
11343
|
+
const user = await this.userRepo.findById({
|
|
11344
|
+
id: userId,
|
|
11345
|
+
tenantId
|
|
11346
|
+
});
|
|
10703
11347
|
if (!user?.passwordHash) {
|
|
10704
11348
|
throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
|
|
10705
11349
|
}
|
|
10706
|
-
const bfIdentifier = hmacSha256(`reauth:change-password:${userId}`, this.options.hmacKey);
|
|
11350
|
+
const bfIdentifier = hmacSha256(`reauth:change-password:${userSubject("dashboard", userId, tenantId)}`, this.options.hmacKey);
|
|
10707
11351
|
if (await this.bruteForce.isLockedOut(bfIdentifier)) {
|
|
10708
|
-
this.logger.warn(`changePassword: account locked userId=${userId}`);
|
|
11352
|
+
this.logger.warn(`changePassword: account locked userId=${logSafe(userId)}`);
|
|
10709
11353
|
throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
|
|
10710
11354
|
}
|
|
10711
11355
|
const matches = await this.passwordService.compare(dto.currentPassword, user.passwordHash);
|
|
10712
11356
|
if (!matches) {
|
|
10713
11357
|
await this.bruteForce.recordFailure(bfIdentifier);
|
|
10714
|
-
this.logger.warn(`changePassword: current password rejected userId=${userId}`);
|
|
11358
|
+
this.logger.warn(`changePassword: current password rejected userId=${logSafe(userId)}`);
|
|
10715
11359
|
throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
|
|
10716
11360
|
}
|
|
10717
11361
|
await this.bruteForce.resetFailures(bfIdentifier);
|
|
10718
11362
|
await this.passwordService.assertAcceptable(dto.newPassword, "newPassword");
|
|
10719
11363
|
const passwordHash = await this.passwordService.hash(dto.newPassword);
|
|
10720
|
-
await this.userRepo.updatePassword(
|
|
11364
|
+
await this.userRepo.updatePassword({
|
|
11365
|
+
id: userId,
|
|
11366
|
+
tenantId,
|
|
11367
|
+
passwordHash
|
|
11368
|
+
});
|
|
10721
11369
|
if (currentRefreshToken !== void 0 && currentRefreshToken.length > 0) {
|
|
10722
|
-
await this.sessionService.revokeAllExceptCurrent(
|
|
11370
|
+
await this.sessionService.revokeAllExceptCurrent({
|
|
11371
|
+
userId,
|
|
11372
|
+
tenantId: user.tenantId,
|
|
11373
|
+
currentSessionHash: sha256(currentRefreshToken)
|
|
11374
|
+
});
|
|
10723
11375
|
} else {
|
|
10724
|
-
await this.redis.invalidateUserSessions(userId);
|
|
10725
|
-
await this.redis.bumpUserTokenEpoch(userId);
|
|
11376
|
+
await this.redis.invalidateUserSessions(userId, user.tenantId, "dashboard");
|
|
11377
|
+
await this.redis.bumpUserTokenEpoch(userId, user.tenantId, "dashboard");
|
|
10726
11378
|
}
|
|
10727
11379
|
await this.notifyPasswordChanged(user);
|
|
10728
11380
|
}
|
|
@@ -10740,9 +11392,17 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10740
11392
|
async notifyPasswordChanged(user) {
|
|
10741
11393
|
const send = this.emailProvider?.sendPasswordChangedNotification;
|
|
10742
11394
|
if (send === void 0) return;
|
|
10743
|
-
|
|
10744
|
-
|
|
10745
|
-
|
|
11395
|
+
const provider = this.emailProvider;
|
|
11396
|
+
const withheld = [
|
|
11397
|
+
user.email
|
|
11398
|
+
];
|
|
11399
|
+
void (async () => {
|
|
11400
|
+
try {
|
|
11401
|
+
await send.call(provider, user.tenantId, user.email);
|
|
11402
|
+
} catch (err) {
|
|
11403
|
+
this.logger.error(safeLogLine(`notifyPasswordChanged: delivery failed for user ${logSafe(user.id)}: ` + describeChannelStatus(err), withheld));
|
|
11404
|
+
}
|
|
11405
|
+
})();
|
|
10746
11406
|
}
|
|
10747
11407
|
/**
|
|
10748
11408
|
* A digest of the account's current password hash, used to bind a reset token to it.
|
|
@@ -10752,8 +11412,11 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10752
11412
|
* local password yields the empty string, which is a value like any other: a token minted
|
|
10753
11413
|
* then is invalidated as soon as one is set.
|
|
10754
11414
|
*/
|
|
10755
|
-
async passwordFingerprintOf(userId) {
|
|
10756
|
-
const user = await this.userRepo.findById(
|
|
11415
|
+
async passwordFingerprintOf(userId, tenantId) {
|
|
11416
|
+
const user = await this.userRepo.findById({
|
|
11417
|
+
id: userId,
|
|
11418
|
+
tenantId
|
|
11419
|
+
});
|
|
10757
11420
|
return user?.passwordHash ? sha256(user.passwordHash) : "";
|
|
10758
11421
|
}
|
|
10759
11422
|
/**
|
|
@@ -10771,21 +11434,28 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10771
11434
|
*/
|
|
10772
11435
|
async assertResetTokenStillBound(context) {
|
|
10773
11436
|
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}`);
|
|
11437
|
+
if (context.passwordFingerprint === await this.passwordFingerprintOf(context.userId, context.tenantId)) return;
|
|
11438
|
+
this.logger.warn(`reset: refusing a token issued against a password that has since changed userId=${logSafe(context.userId)}`);
|
|
10776
11439
|
throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
|
|
10777
11440
|
}
|
|
10778
|
-
async applyPasswordReset(userId, newPassword) {
|
|
11441
|
+
async applyPasswordReset(userId, tenantId, newPassword) {
|
|
10779
11442
|
const passwordHash = await this.passwordService.hash(newPassword);
|
|
10780
|
-
await this.userRepo.updatePassword(
|
|
10781
|
-
|
|
10782
|
-
|
|
10783
|
-
|
|
11443
|
+
await this.userRepo.updatePassword({
|
|
11444
|
+
id: userId,
|
|
11445
|
+
tenantId,
|
|
11446
|
+
passwordHash
|
|
11447
|
+
});
|
|
11448
|
+
await this.redis.invalidateUserSessions(userId, tenantId, "dashboard");
|
|
11449
|
+
await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
|
|
11450
|
+
const user = await this.userRepo.findById({
|
|
11451
|
+
id: userId,
|
|
11452
|
+
tenantId
|
|
11453
|
+
});
|
|
10784
11454
|
if (user) {
|
|
10785
11455
|
await this.notifyPasswordChanged(user);
|
|
10786
11456
|
if (this.hooks?.afterPasswordReset) {
|
|
10787
11457
|
void Promise.resolve(this.hooks.afterPasswordReset(toSafeUser3(user), createEmptyHookContext())).catch((err) => {
|
|
10788
|
-
this.logger.error(
|
|
11458
|
+
this.logger.error(`afterPasswordReset hook threw: ${describeChannelStatus(err)}`);
|
|
10789
11459
|
});
|
|
10790
11460
|
}
|
|
10791
11461
|
}
|
|
@@ -10808,15 +11478,24 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10808
11478
|
userId,
|
|
10809
11479
|
email,
|
|
10810
11480
|
tenantId,
|
|
10811
|
-
passwordFingerprint: await this.passwordFingerprintOf(userId)
|
|
11481
|
+
passwordFingerprint: await this.passwordFingerprintOf(userId, tenantId)
|
|
10812
11482
|
};
|
|
10813
11483
|
await this.redis.set(tokenKey, JSON.stringify(context), this.options.passwordReset.tokenTtlSeconds);
|
|
10814
|
-
|
|
10815
|
-
|
|
10816
|
-
|
|
10817
|
-
|
|
10818
|
-
})
|
|
10819
|
-
|
|
11484
|
+
const provider = this.emailProvider;
|
|
11485
|
+
void (async () => {
|
|
11486
|
+
try {
|
|
11487
|
+
await provider.sendPasswordResetToken(tenantId, email, rawToken);
|
|
11488
|
+
} catch (err) {
|
|
11489
|
+
const withheld = [
|
|
11490
|
+
rawToken,
|
|
11491
|
+
email
|
|
11492
|
+
];
|
|
11493
|
+
this.logger.error(safeLogLine(`sendPasswordResetToken failed for user ${logSafe(userId)}: ` + describeChannelStatus(err), withheld));
|
|
11494
|
+
void this.redis.del(tokenKey).catch((delErr) => {
|
|
11495
|
+
this.logger.error(`pw_reset rollback delete failed for user ${logSafe(userId)}: ${describeChannelStatus(delErr)}`);
|
|
11496
|
+
});
|
|
11497
|
+
}
|
|
11498
|
+
})();
|
|
10820
11499
|
}
|
|
10821
11500
|
/**
|
|
10822
11501
|
* Generates and stores a password-reset OTP, then sends it to the user's email.
|
|
@@ -10831,9 +11510,18 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
10831
11510
|
const identifier = this.otpIdentifier(tenantId, email);
|
|
10832
11511
|
const otp = this.otpService.generate(otpLength);
|
|
10833
11512
|
await this.otpService.store(PASSWORD_RESET_PURPOSE, identifier, otp, otpTtlSeconds);
|
|
10834
|
-
|
|
10835
|
-
|
|
10836
|
-
|
|
11513
|
+
const provider = this.emailProvider;
|
|
11514
|
+
void (async () => {
|
|
11515
|
+
try {
|
|
11516
|
+
await provider.sendPasswordResetOtp(tenantId, email, otp);
|
|
11517
|
+
} catch (err) {
|
|
11518
|
+
const withheld = [
|
|
11519
|
+
otp,
|
|
11520
|
+
email
|
|
11521
|
+
];
|
|
11522
|
+
this.logger.error(safeLogLine(`sendPasswordResetOtp failed for user ${logSafe(redactSecrets(userId, withheld))}: ` + describeChannelStatus(err), withheld));
|
|
11523
|
+
}
|
|
11524
|
+
})();
|
|
10837
11525
|
}
|
|
10838
11526
|
// ---------------------------------------------------------------------------
|
|
10839
11527
|
// Private helpers — misc
|
|
@@ -11021,7 +11709,7 @@ var PasswordResetController = class {
|
|
|
11021
11709
|
*/
|
|
11022
11710
|
async changePassword(user, dto, req) {
|
|
11023
11711
|
const currentRefreshToken = this.tokenDelivery.extractRefreshToken(req);
|
|
11024
|
-
await this.passwordResetService.changePassword(user.sub, dto, currentRefreshToken);
|
|
11712
|
+
await this.passwordResetService.changePassword(user.sub, user.tenantId, dto, currentRefreshToken);
|
|
11025
11713
|
}
|
|
11026
11714
|
// ---------------------------------------------------------------------------
|
|
11027
11715
|
// POST /password/verify-otp
|
|
@@ -11393,7 +12081,7 @@ exports.PlatformAuthService = class _PlatformAuthService {
|
|
|
11393
12081
|
await this.bruteForce.resetFailures(bfIdentifier);
|
|
11394
12082
|
if (admin.mfaEnabled) {
|
|
11395
12083
|
const mfaTempToken = await this.tokenManager.issueMfaTempToken(admin.id, "platform");
|
|
11396
|
-
this.logger.log(`login: MFA challenge issued adminId=${admin.id}`);
|
|
12084
|
+
this.logger.log(`login: MFA challenge issued adminId=${logSafe(admin.id)}`);
|
|
11397
12085
|
return {
|
|
11398
12086
|
mfaRequired: true,
|
|
11399
12087
|
mfaTempToken
|
|
@@ -11401,9 +12089,9 @@ exports.PlatformAuthService = class _PlatformAuthService {
|
|
|
11401
12089
|
}
|
|
11402
12090
|
const { passwordHash: _passwordHash, mfaSecret: _mfaSecret, mfaRecoveryCodes: _mfaRecoveryCodes, ...safeAdmin } = admin;
|
|
11403
12091
|
const result = await this.tokenManager.issuePlatformTokens(safeAdmin, ip, userAgent);
|
|
11404
|
-
this.logger.log(`login: success adminId=${admin.id}`);
|
|
12092
|
+
this.logger.log(`login: success adminId=${logSafe(admin.id)}`);
|
|
11405
12093
|
void this.platformUserRepo.updateLastLogin(admin.id).catch((err) => {
|
|
11406
|
-
this.logger.error(
|
|
12094
|
+
this.logger.error(`updateLastLogin failed: ${describeChannelStatus(err)}`);
|
|
11407
12095
|
});
|
|
11408
12096
|
return result;
|
|
11409
12097
|
}
|
|
@@ -11421,8 +12109,8 @@ exports.PlatformAuthService = class _PlatformAuthService {
|
|
|
11421
12109
|
*/
|
|
11422
12110
|
async logout(accessToken, rawRefreshToken) {
|
|
11423
12111
|
const tokenHash = sha256(rawRefreshToken);
|
|
11424
|
-
const userId = await this.redis.readSessionOwner(`prt:${tokenHash}`);
|
|
11425
|
-
this.logger.log(`logout: adminId=${userId || "(no live session)"}`);
|
|
12112
|
+
const { userId } = await this.redis.readSessionOwner(`prt:${tokenHash}`);
|
|
12113
|
+
this.logger.log(`logout: adminId=${logSafe(userId || "(no live session)")}`);
|
|
11426
12114
|
try {
|
|
11427
12115
|
const payload = this.tokenManager.verifyPlatformIgnoringExpiry(accessToken);
|
|
11428
12116
|
const remainingTtl = payload.exp - Math.floor(Date.now() / 1e3);
|
|
@@ -11434,8 +12122,9 @@ exports.PlatformAuthService = class _PlatformAuthService {
|
|
|
11434
12122
|
await this.redis.del("prt:" + tokenHash);
|
|
11435
12123
|
await this.redis.del("prp:" + tokenHash);
|
|
11436
12124
|
if (userId) {
|
|
11437
|
-
|
|
11438
|
-
await this.redis.srem(
|
|
12125
|
+
const index = sessionIndexKey("platform", userId, this.options.hmacKey, void 0);
|
|
12126
|
+
await this.redis.srem(index, "prt:" + tokenHash);
|
|
12127
|
+
await this.redis.srem(index, "prp:" + tokenHash);
|
|
11439
12128
|
}
|
|
11440
12129
|
await this.redis.del("psd:" + tokenHash);
|
|
11441
12130
|
return userId;
|
|
@@ -11528,7 +12217,7 @@ exports.PlatformAuthService = class _PlatformAuthService {
|
|
|
11528
12217
|
* Revokes all active platform sessions for the given admin.
|
|
11529
12218
|
*
|
|
11530
12219
|
* Delegates to {@link AuthRedisService.invalidateUserSessions} which uses an atomic
|
|
11531
|
-
* Lua script to read the
|
|
12220
|
+
* Lua script to read the platform index SET, delete all session and grace-pointer
|
|
11532
12221
|
* keys, and remove the SET itself in a single Redis round-trip. This prevents the
|
|
11533
12222
|
* TOCTOU race that would arise from a non-atomic SMEMBERS + loop + DEL approach.
|
|
11534
12223
|
*
|
|
@@ -11542,8 +12231,8 @@ exports.PlatformAuthService = class _PlatformAuthService {
|
|
|
11542
12231
|
* @param userId - The platform admin's internal ID.
|
|
11543
12232
|
*/
|
|
11544
12233
|
async revokeAllPlatformSessions(userId) {
|
|
11545
|
-
await this.redis.invalidateUserSessions(userId, "platform");
|
|
11546
|
-
await this.redis.bumpUserTokenEpoch(userId, "platform");
|
|
12234
|
+
await this.redis.invalidateUserSessions(userId, void 0, "platform");
|
|
12235
|
+
await this.redis.bumpUserTokenEpoch(userId, void 0, "platform");
|
|
11547
12236
|
}
|
|
11548
12237
|
};
|
|
11549
12238
|
exports.PlatformAuthService = _ts_decorate46([
|
|
@@ -12081,7 +12770,11 @@ var SessionController = class {
|
|
|
12081
12770
|
async listSessions(user, req) {
|
|
12082
12771
|
const rawRefresh = this.tokenDelivery.extractRefreshToken(req);
|
|
12083
12772
|
const currentHash = rawRefresh ? sha256(rawRefresh) : void 0;
|
|
12084
|
-
return this.sessionService.listSessions(
|
|
12773
|
+
return this.sessionService.listSessions({
|
|
12774
|
+
userId: user.sub,
|
|
12775
|
+
tenantId: user.tenantId,
|
|
12776
|
+
currentSessionHash: currentHash
|
|
12777
|
+
});
|
|
12085
12778
|
}
|
|
12086
12779
|
// ---------------------------------------------------------------------------
|
|
12087
12780
|
// POST /sessions/revoke-all
|
|
@@ -12114,7 +12807,11 @@ var SessionController = class {
|
|
|
12114
12807
|
throw new AuthException(AUTH_ERROR_CODES.SESSION_NOT_FOUND);
|
|
12115
12808
|
}
|
|
12116
12809
|
const currentHash = sha256(rawRefresh);
|
|
12117
|
-
await this.sessionService.revokeAllExceptCurrent(
|
|
12810
|
+
await this.sessionService.revokeAllExceptCurrent({
|
|
12811
|
+
userId: user.sub,
|
|
12812
|
+
tenantId: user.tenantId,
|
|
12813
|
+
currentSessionHash: currentHash
|
|
12814
|
+
});
|
|
12118
12815
|
}
|
|
12119
12816
|
// ---------------------------------------------------------------------------
|
|
12120
12817
|
// DELETE /sessions/:id
|
|
@@ -12129,12 +12826,19 @@ var SessionController = class {
|
|
|
12129
12826
|
*
|
|
12130
12827
|
* @param user - Verified JWT payload from the access token.
|
|
12131
12828
|
* @param id - Full SHA-256 session hash from the `sessionHash` field of `SessionInfo`.
|
|
12132
|
-
* @throws {@link AuthException} `
|
|
12133
|
-
*
|
|
12829
|
+
* @throws {@link AuthException} `VALIDATION` when the value is not 64 lowercase hex characters
|
|
12830
|
+
* — which is what the 8-character display `id` is, so passing that is a caller error rather
|
|
12831
|
+
* than a missing session.
|
|
12832
|
+
* @throws {@link AuthException} `SESSION_NOT_FOUND` when the hash is well formed but names no
|
|
12833
|
+
* session belonging to this user.
|
|
12134
12834
|
* @returns 204 No Content on success.
|
|
12135
12835
|
*/
|
|
12136
12836
|
async revokeSession(user, id) {
|
|
12137
|
-
await this.sessionService.revokeOtherSession(
|
|
12837
|
+
await this.sessionService.revokeOtherSession({
|
|
12838
|
+
userId: user.sub,
|
|
12839
|
+
tenantId: user.tenantId,
|
|
12840
|
+
sessionHash: id
|
|
12841
|
+
});
|
|
12138
12842
|
}
|
|
12139
12843
|
};
|
|
12140
12844
|
_ts_decorate49([
|
|
@@ -12647,10 +13351,14 @@ exports.OAuthService = class _OAuthService {
|
|
|
12647
13351
|
const tokenResponse = await plugin.exchangeCode(code, codeVerifier);
|
|
12648
13352
|
profile = await plugin.fetchProfile(tokenResponse.access_token);
|
|
12649
13353
|
} catch (err) {
|
|
12650
|
-
this.logger.error(`OAuth plugin '${provider}' failed during code exchange or profile fetch
|
|
13354
|
+
this.logger.error(`OAuth plugin '${provider}' failed during code exchange or profile fetch: ` + describeChannelStatus(err));
|
|
12651
13355
|
throw new AuthException(AUTH_ERROR_CODES.OAUTH_FAILED);
|
|
12652
13356
|
}
|
|
12653
|
-
const existingAuthUser = await this.userRepo.findByOAuthId(
|
|
13357
|
+
const existingAuthUser = await this.userRepo.findByOAuthId({
|
|
13358
|
+
provider,
|
|
13359
|
+
providerId: profile.providerId,
|
|
13360
|
+
tenantId
|
|
13361
|
+
});
|
|
12654
13362
|
const existingUser = existingAuthUser ? toSafeUser4(existingAuthUser) : null;
|
|
12655
13363
|
const hookContext = {
|
|
12656
13364
|
tenantId,
|
|
@@ -12667,8 +13375,11 @@ exports.OAuthService = class _OAuthService {
|
|
|
12667
13375
|
switch (hookResult.action) {
|
|
12668
13376
|
case "create": {
|
|
12669
13377
|
const derivedName = profile.name ?? profile.email.split("@")[0] ?? profile.email;
|
|
12670
|
-
if (await this.userRepo.findByEmail(
|
|
12671
|
-
|
|
13378
|
+
if (await this.userRepo.findByEmail({
|
|
13379
|
+
email: profile.email,
|
|
13380
|
+
tenantId
|
|
13381
|
+
})) {
|
|
13382
|
+
this.logger.warn(`oauth: create refused \u2014 ${maskEmail(profile.email)} already exists in tenant ${logSafe(tenantId)}`);
|
|
12672
13383
|
throw new AuthException(AUTH_ERROR_CODES.OAUTH_EMAIL_MISMATCH);
|
|
12673
13384
|
}
|
|
12674
13385
|
authUser = await this.userRepo.createWithOAuth({
|
|
@@ -12689,8 +13400,16 @@ exports.OAuthService = class _OAuthService {
|
|
|
12689
13400
|
if (!existingAuthUser) {
|
|
12690
13401
|
throw new AuthException(AUTH_ERROR_CODES.OAUTH_FAILED);
|
|
12691
13402
|
}
|
|
12692
|
-
await this.userRepo.linkOAuth(
|
|
12693
|
-
|
|
13403
|
+
await this.userRepo.linkOAuth({
|
|
13404
|
+
id: existingAuthUser.id,
|
|
13405
|
+
tenantId: existingAuthUser.tenantId,
|
|
13406
|
+
provider,
|
|
13407
|
+
providerId: profile.providerId
|
|
13408
|
+
});
|
|
13409
|
+
const linked = await this.userRepo.findById({
|
|
13410
|
+
id: existingAuthUser.id,
|
|
13411
|
+
tenantId: existingAuthUser.tenantId
|
|
13412
|
+
});
|
|
12694
13413
|
if (!linked) {
|
|
12695
13414
|
throw new AuthException(AUTH_ERROR_CODES.OAUTH_FAILED);
|
|
12696
13415
|
}
|
|
@@ -12708,7 +13427,7 @@ exports.OAuthService = class _OAuthService {
|
|
|
12708
13427
|
}
|
|
12709
13428
|
if (authUser.mfaEnabled) {
|
|
12710
13429
|
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}`);
|
|
13430
|
+
this.logger.log(`handleCallback: OAuth MFA challenge issued provider=${provider} userId=${logSafe(authUser.id)} tenantId=${logSafe(tenantId)} action=${hookResult.action}`);
|
|
12712
13431
|
return {
|
|
12713
13432
|
mfaRequired: true,
|
|
12714
13433
|
mfaTempToken
|
|
@@ -12717,9 +13436,15 @@ exports.OAuthService = class _OAuthService {
|
|
|
12717
13436
|
const safeUser = toSafeUser4(authUser);
|
|
12718
13437
|
const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
|
|
12719
13438
|
if (this.options.sessions.enabled) {
|
|
12720
|
-
await this.sessionService.createSession(
|
|
13439
|
+
await this.sessionService.createSession({
|
|
13440
|
+
userId: safeUser.id,
|
|
13441
|
+
tenantId: safeUser.tenantId,
|
|
13442
|
+
rawRefreshToken: result.rawRefreshToken,
|
|
13443
|
+
ip,
|
|
13444
|
+
userAgent
|
|
13445
|
+
});
|
|
12721
13446
|
}
|
|
12722
|
-
this.logger.log(`handleCallback: OAuth login success provider=${provider} userId=${safeUser.id} tenantId=${logSafe(tenantId)} action=${hookResult.action}`);
|
|
13447
|
+
this.logger.log(`handleCallback: OAuth login success provider=${provider} userId=${logSafe(safeUser.id)} tenantId=${logSafe(tenantId)} action=${hookResult.action}`);
|
|
12723
13448
|
return result;
|
|
12724
13449
|
}
|
|
12725
13450
|
// ---------------------------------------------------------------------------
|
|
@@ -13527,6 +14252,14 @@ var AUTH_SECURITY_SCHEMES = {
|
|
|
13527
14252
|
refreshCookie: "bymaxAuthRefreshCookie",
|
|
13528
14253
|
platformBearer: "bymaxPlatformAccessBearer"
|
|
13529
14254
|
};
|
|
14255
|
+
function deliversCookie(tokenDelivery) {
|
|
14256
|
+
return tokenDelivery === "cookie" || tokenDelivery === "both";
|
|
14257
|
+
}
|
|
14258
|
+
__name(deliversCookie, "deliversCookie");
|
|
14259
|
+
function deliversBearer(tokenDelivery) {
|
|
14260
|
+
return tokenDelivery === "bearer" || tokenDelivery === "both";
|
|
14261
|
+
}
|
|
14262
|
+
__name(deliversBearer, "deliversBearer");
|
|
13530
14263
|
var OPERATIONS = {
|
|
13531
14264
|
auth: {
|
|
13532
14265
|
"AuthController.register": "none",
|
|
@@ -13685,13 +14418,13 @@ var PLATFORM_REFRESH_BODY = {
|
|
|
13685
14418
|
}
|
|
13686
14419
|
};
|
|
13687
14420
|
function buildAuthOpenApiFragment(options, registered) {
|
|
13688
|
-
const cookieDelivery = options.tokenDelivery
|
|
13689
|
-
const bearerDelivery = options.tokenDelivery
|
|
14421
|
+
const cookieDelivery = deliversCookie(options.tokenDelivery);
|
|
14422
|
+
const bearerDelivery = deliversBearer(options.tokenDelivery);
|
|
13690
14423
|
const operations = {};
|
|
13691
14424
|
for (const [controller, handlers] of Object.entries(OPERATIONS)) {
|
|
13692
14425
|
if (!registered[controller]) continue;
|
|
13693
14426
|
for (const [handler, credential] of Object.entries(handlers)) {
|
|
13694
|
-
const described =
|
|
14427
|
+
const described = describe2(credential, cookieDelivery, bearerDelivery);
|
|
13695
14428
|
const note = OPERATION_DESCRIPTIONS.get(handler);
|
|
13696
14429
|
operations[handler] = note === void 0 ? described : {
|
|
13697
14430
|
...described,
|
|
@@ -13708,7 +14441,7 @@ function buildAuthOpenApiFragment(options, registered) {
|
|
|
13708
14441
|
};
|
|
13709
14442
|
}
|
|
13710
14443
|
__name(buildAuthOpenApiFragment, "buildAuthOpenApiFragment");
|
|
13711
|
-
function
|
|
14444
|
+
function describe2(credential, cookieDelivery, bearerDelivery) {
|
|
13712
14445
|
switch (credential) {
|
|
13713
14446
|
case "none":
|
|
13714
14447
|
return {
|
|
@@ -13778,7 +14511,7 @@ function describe(credential, cookieDelivery, bearerDelivery) {
|
|
|
13778
14511
|
};
|
|
13779
14512
|
}
|
|
13780
14513
|
}
|
|
13781
|
-
__name(
|
|
14514
|
+
__name(describe2, "describe");
|
|
13782
14515
|
function describeTwoCredentials(credential, cookieDelivery, bearerDelivery) {
|
|
13783
14516
|
const required = {
|
|
13784
14517
|
access: credential !== "optionalAccessAndRefresh",
|
|
@@ -14650,6 +15383,54 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
|
|
|
14650
15383
|
exports.BymaxAuthModule = _ts_decorate62([
|
|
14651
15384
|
common.Module({})
|
|
14652
15385
|
], exports.BymaxAuthModule);
|
|
15386
|
+
|
|
15387
|
+
// src/server/openapi/document-security.ts
|
|
15388
|
+
var NO_SCOPES = Object.freeze([]);
|
|
15389
|
+
function requirementFor(scheme) {
|
|
15390
|
+
return Object.freeze({
|
|
15391
|
+
[scheme]: NO_SCOPES
|
|
15392
|
+
});
|
|
15393
|
+
}
|
|
15394
|
+
__name(requirementFor, "requirementFor");
|
|
15395
|
+
function authDocumentSecurity({ guard, tokenDelivery }) {
|
|
15396
|
+
if (guard === "platform") {
|
|
15397
|
+
return Object.freeze([
|
|
15398
|
+
requirementFor(AUTH_SECURITY_SCHEMES.platformBearer)
|
|
15399
|
+
]);
|
|
15400
|
+
}
|
|
15401
|
+
const delivery = tokenDelivery ?? DEFAULT_OPTIONS.tokenDelivery;
|
|
15402
|
+
const schemes = [
|
|
15403
|
+
...deliversCookie(delivery) ? [
|
|
15404
|
+
AUTH_SECURITY_SCHEMES.accessCookie
|
|
15405
|
+
] : [],
|
|
15406
|
+
...deliversBearer(delivery) ? [
|
|
15407
|
+
AUTH_SECURITY_SCHEMES.accessBearer
|
|
15408
|
+
] : []
|
|
15409
|
+
];
|
|
15410
|
+
return Object.freeze(schemes.map(requirementFor));
|
|
15411
|
+
}
|
|
15412
|
+
__name(authDocumentSecurity, "authDocumentSecurity");
|
|
15413
|
+
var AUTH_EMAIL_KINDS = [
|
|
15414
|
+
"passwordResetToken",
|
|
15415
|
+
"passwordResetOtp",
|
|
15416
|
+
"emailVerificationOtp",
|
|
15417
|
+
"passwordChanged",
|
|
15418
|
+
"emailChangeVerification",
|
|
15419
|
+
"emailChanged",
|
|
15420
|
+
"mfaEnabled",
|
|
15421
|
+
"mfaDisabled",
|
|
15422
|
+
"newSessionAlert",
|
|
15423
|
+
"invitation"
|
|
15424
|
+
];
|
|
15425
|
+
Object.freeze(AUTH_EMAIL_KINDS);
|
|
15426
|
+
var CREDENTIAL_BEARING_KINDS = /* @__PURE__ */ new Set([
|
|
15427
|
+
"passwordResetToken",
|
|
15428
|
+
"passwordResetOtp",
|
|
15429
|
+
"emailVerificationOtp",
|
|
15430
|
+
"emailChangeVerification",
|
|
15431
|
+
"invitation"
|
|
15432
|
+
]);
|
|
15433
|
+
var KNOWN_EMAIL_KINDS = new Set(AUTH_EMAIL_KINDS);
|
|
14653
15434
|
var CODE_VALIDITY_TEXT = "It expires shortly, so use it soon.";
|
|
14654
15435
|
var UNEXPECTED_CHANGE_TEXT = "If this was not you, secure your account immediately: change your password and sign out of every session.";
|
|
14655
15436
|
var DEFAULT_MESSAGES = {
|
|
@@ -14751,8 +15532,16 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
|
|
|
14751
15532
|
logger = new common.Logger(_DefaultAuthEmailProvider.name);
|
|
14752
15533
|
/** The copy in effect: the defaults, with any provided overrides layered on top. */
|
|
14753
15534
|
messages;
|
|
14754
|
-
/**
|
|
14755
|
-
|
|
15535
|
+
/**
|
|
15536
|
+
* The resolved per-message policy.
|
|
15537
|
+
*
|
|
15538
|
+
* A `Map`, not the plain object the option accepts. An object lookup walks the prototype chain,
|
|
15539
|
+
* so `policy['toString']` answers with a function rather than `undefined` — unreachable here,
|
|
15540
|
+
* because the key is a closed union of ten literals this file writes, but "the key cannot be
|
|
15541
|
+
* dangerous" is a property of today's call sites and not of the lookup. A `Map` has no prototype
|
|
15542
|
+
* chain to walk, which makes it a property of the data structure instead.
|
|
15543
|
+
*/
|
|
15544
|
+
deliveryErrorPolicy;
|
|
14756
15545
|
/**
|
|
14757
15546
|
* @param sink - The delivery channel to send through.
|
|
14758
15547
|
* @param options - Optional copy overrides and delivery-error policy.
|
|
@@ -14763,41 +15552,62 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
|
|
|
14763
15552
|
...DEFAULT_MESSAGES,
|
|
14764
15553
|
...options?.messages
|
|
14765
15554
|
};
|
|
14766
|
-
|
|
15555
|
+
const configured = options?.onDeliveryError;
|
|
15556
|
+
this.deliveryErrorPolicy = new Map(typeof configured === "string" ? AUTH_EMAIL_KINDS.map((kind) => [
|
|
15557
|
+
kind,
|
|
15558
|
+
configured
|
|
15559
|
+
]) : (
|
|
15560
|
+
// `Object.entries` yields own enumerable properties only, so an inherited `toString` is
|
|
15561
|
+
// not reachable by construction rather than by a guard someone has to remember.
|
|
15562
|
+
//
|
|
15563
|
+
// A key the catalogue does not know is dropped, and the direction of that is deliberate:
|
|
15564
|
+
// a typo leaves the message on `'swallow'`, which is the safe value. A deployment gets
|
|
15565
|
+
// less throwing than it meant, never more exposure. TypeScript rejects the typo outright;
|
|
15566
|
+
// this is what happens to a JavaScript caller.
|
|
15567
|
+
Object.entries(configured ?? {}).filter(
|
|
15568
|
+
// The KEY is checked and nothing else. Filtering `undefined` values out as well was
|
|
15569
|
+
// tried and is dead code: a `Map` holding `[key, undefined]` and a `Map` without the
|
|
15570
|
+
// key both answer `undefined`, so no test can tell them apart — which the mutation
|
|
15571
|
+
// gate said, three times over. The value type is the one `Object.entries` gives for a
|
|
15572
|
+
// `Partial<Record<…>>`, so the predicate asserts nothing the compiler has not already
|
|
15573
|
+
// concluded; what it narrows is the key, and that IS checked.
|
|
15574
|
+
(entry) => KNOWN_EMAIL_KINDS.has(entry[0])
|
|
15575
|
+
)
|
|
15576
|
+
));
|
|
14767
15577
|
}
|
|
14768
15578
|
/** @inheritdoc */
|
|
14769
15579
|
async sendPasswordResetToken(tenantId, email, token, locale) {
|
|
14770
15580
|
await this.deliver(tenantId, email, this.messages.passwordResetToken({
|
|
14771
15581
|
token,
|
|
14772
15582
|
locale
|
|
14773
|
-
}));
|
|
15583
|
+
}), "passwordResetToken");
|
|
14774
15584
|
}
|
|
14775
15585
|
/** @inheritdoc */
|
|
14776
15586
|
async sendPasswordResetOtp(tenantId, email, otp, locale) {
|
|
14777
15587
|
await this.deliver(tenantId, email, this.messages.passwordResetOtp({
|
|
14778
15588
|
otp,
|
|
14779
15589
|
locale
|
|
14780
|
-
}));
|
|
15590
|
+
}), "passwordResetOtp");
|
|
14781
15591
|
}
|
|
14782
15592
|
/** @inheritdoc */
|
|
14783
15593
|
async sendEmailVerificationOtp(tenantId, email, otp, locale) {
|
|
14784
15594
|
await this.deliver(tenantId, email, this.messages.emailVerificationOtp({
|
|
14785
15595
|
otp,
|
|
14786
15596
|
locale
|
|
14787
|
-
}));
|
|
15597
|
+
}), "emailVerificationOtp");
|
|
14788
15598
|
}
|
|
14789
15599
|
/** @inheritdoc */
|
|
14790
15600
|
async sendPasswordChangedNotification(tenantId, email, locale) {
|
|
14791
15601
|
await this.deliver(tenantId, email, this.messages.passwordChanged({
|
|
14792
15602
|
locale
|
|
14793
|
-
}));
|
|
15603
|
+
}), "passwordChanged");
|
|
14794
15604
|
}
|
|
14795
15605
|
/** @inheritdoc */
|
|
14796
15606
|
async sendEmailChangeVerification(tenantId, newEmail, token, locale) {
|
|
14797
15607
|
await this.deliver(tenantId, newEmail, this.messages.emailChangeVerification({
|
|
14798
15608
|
token,
|
|
14799
15609
|
locale
|
|
14800
|
-
}));
|
|
15610
|
+
}), "emailChangeVerification");
|
|
14801
15611
|
}
|
|
14802
15612
|
/** @inheritdoc */
|
|
14803
15613
|
async sendEmailChangedNotification(tenantId, oldEmail, newEmail, locale) {
|
|
@@ -14805,33 +15615,33 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
|
|
|
14805
15615
|
oldEmail,
|
|
14806
15616
|
newEmail,
|
|
14807
15617
|
locale
|
|
14808
|
-
}));
|
|
15618
|
+
}), "emailChanged");
|
|
14809
15619
|
}
|
|
14810
15620
|
/** @inheritdoc */
|
|
14811
15621
|
async sendMfaEnabledNotification(tenantId, email, locale) {
|
|
14812
15622
|
await this.deliver(tenantId, email, this.messages.mfaEnabled({
|
|
14813
15623
|
locale
|
|
14814
|
-
}));
|
|
15624
|
+
}), "mfaEnabled");
|
|
14815
15625
|
}
|
|
14816
15626
|
/** @inheritdoc */
|
|
14817
15627
|
async sendMfaDisabledNotification(tenantId, email, locale) {
|
|
14818
15628
|
await this.deliver(tenantId, email, this.messages.mfaDisabled({
|
|
14819
15629
|
locale
|
|
14820
|
-
}));
|
|
15630
|
+
}), "mfaDisabled");
|
|
14821
15631
|
}
|
|
14822
15632
|
/** @inheritdoc */
|
|
14823
15633
|
async sendNewSessionAlert(tenantId, email, sessionInfo, locale) {
|
|
14824
15634
|
await this.deliver(tenantId, email, this.messages.newSessionAlert({
|
|
14825
15635
|
sessionInfo,
|
|
14826
15636
|
locale
|
|
14827
|
-
}));
|
|
15637
|
+
}), "newSessionAlert");
|
|
14828
15638
|
}
|
|
14829
15639
|
/** @inheritdoc */
|
|
14830
15640
|
async sendInvitation(tenantId, email, inviteData, locale) {
|
|
14831
15641
|
await this.deliver(tenantId, email, this.messages.invitation({
|
|
14832
15642
|
invite: inviteData,
|
|
14833
15643
|
locale
|
|
14834
|
-
}));
|
|
15644
|
+
}), "invitation");
|
|
14835
15645
|
}
|
|
14836
15646
|
/**
|
|
14837
15647
|
* Renders the body to HTML (unless the message already carries its own), hands the message to the
|
|
@@ -14840,8 +15650,15 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
|
|
|
14840
15650
|
* @param tenantId - Tenant the message is attributed to.
|
|
14841
15651
|
* @param to - Recipient address.
|
|
14842
15652
|
* @param message - The rendered subject and body, and optionally its own HTML.
|
|
14843
|
-
|
|
14844
|
-
|
|
15653
|
+
* @param label - Which message this is, as a fixed name this file owns. It goes in the log line
|
|
15654
|
+
* in place of the rendered SUBJECT, and the substitution is the point: a subject comes from
|
|
15655
|
+
* the `messages` catalogue, which a consumer may override, so logging it publishes a string
|
|
15656
|
+
* this library did not write. Redacting it is not enough — a renderer that TRANSFORMS a value
|
|
15657
|
+
* defeats a substring match, and `Code 123-456` for the OTP `123456` is a reasonable-looking
|
|
15658
|
+
* thing to write. The label carries the same information for an operator, identifies the
|
|
15659
|
+
* message more stably for a log parser, and cannot carry anything at all.
|
|
15660
|
+
*/
|
|
15661
|
+
async deliver(tenantId, to, message, label) {
|
|
14845
15662
|
const subject = sanitizeSubject(message.subject);
|
|
14846
15663
|
try {
|
|
14847
15664
|
await this.sink.send({
|
|
@@ -14849,11 +15666,23 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
|
|
|
14849
15666
|
to,
|
|
14850
15667
|
subject,
|
|
14851
15668
|
html: message.html ?? toHtml(message.text),
|
|
14852
|
-
text: message.text
|
|
15669
|
+
text: message.text,
|
|
15670
|
+
kind: label,
|
|
15671
|
+
// Stated at the only moment a sink could act on it. Whether it DOES is the sink's to
|
|
15672
|
+
// answer — see the field's own documentation for why this is a statement of fact rather
|
|
15673
|
+
// than a control, and why it is a flag rather than a list of values to redact.
|
|
15674
|
+
//
|
|
15675
|
+
// OR-ed rather than taken from either side alone, and the direction matters. The kind is
|
|
15676
|
+
// the baseline a renderer cannot weaken, so an override returning `false` on
|
|
15677
|
+
// `passwordResetOtp` changes nothing. The rendering can only ADD, which is the case the
|
|
15678
|
+
// kind cannot see: `options.messages` replaces a renderer outright, so a product whose
|
|
15679
|
+
// own `mfaEnabled` copy includes recovery codes has made a notice credential-bearing
|
|
15680
|
+
// while its kind still reads `mfaEnabled`.
|
|
15681
|
+
containsCredential: CREDENTIAL_BEARING_KINDS.has(label) || message.containsCredential === true
|
|
14853
15682
|
});
|
|
14854
15683
|
} catch (error) {
|
|
14855
|
-
this.logger.error(`delivery failed
|
|
14856
|
-
if (this.
|
|
15684
|
+
this.logger.error(`delivery failed sending ${label}: ${describeChannelStatus(error)}`);
|
|
15685
|
+
if (this.deliveryErrorPolicy.get(label) === "rethrow") {
|
|
14857
15686
|
throw error;
|
|
14858
15687
|
}
|
|
14859
15688
|
}
|
|
@@ -15237,7 +16066,7 @@ exports.AuthExceptionFilter = class _AuthExceptionFilter {
|
|
|
15237
16066
|
});
|
|
15238
16067
|
return;
|
|
15239
16068
|
}
|
|
15240
|
-
this.logger.error(
|
|
16069
|
+
this.logger.error(`unhandled exception: ${describeChannelStatus(exception)}`);
|
|
15241
16070
|
res.status(common.HttpStatus.INTERNAL_SERVER_ERROR).json({
|
|
15242
16071
|
error: {
|
|
15243
16072
|
code: AUTH_ERROR_CODES.INTERNAL,
|
|
@@ -15306,16 +16135,18 @@ exports.WsAuthExceptionFilter = class _WsAuthExceptionFilter {
|
|
|
15306
16135
|
client.emit("exception", payload);
|
|
15307
16136
|
return;
|
|
15308
16137
|
}
|
|
15309
|
-
this.logger.error(
|
|
16138
|
+
this.logger.error(`refused a request on a client this filter cannot answer: ${describeChannelStatus(exception)}`);
|
|
15310
16139
|
}
|
|
15311
16140
|
};
|
|
15312
16141
|
exports.WsAuthExceptionFilter = _ts_decorate68([
|
|
15313
16142
|
common.Catch(AuthException)
|
|
15314
16143
|
], exports.WsAuthExceptionFilter);
|
|
15315
16144
|
|
|
16145
|
+
exports.AUTH_EMAIL_KINDS = AUTH_EMAIL_KINDS;
|
|
15316
16146
|
exports.AUTH_ERROR_CODES = AUTH_ERROR_CODES;
|
|
15317
16147
|
exports.AUTH_ERROR_MESSAGES = AUTH_ERROR_MESSAGES;
|
|
15318
16148
|
exports.AUTH_ERROR_STATUS = AUTH_ERROR_STATUS;
|
|
16149
|
+
exports.AUTH_SECURITY_SCHEMES = AUTH_SECURITY_SCHEMES;
|
|
15319
16150
|
exports.AUTH_THROTTLE_CONFIGS = AUTH_THROTTLE_CONFIGS;
|
|
15320
16151
|
exports.AcceptInvitationDto = AcceptInvitationDto;
|
|
15321
16152
|
exports.AuthException = AuthException;
|
|
@@ -15354,12 +16185,16 @@ exports.SkipMfa = SkipMfa;
|
|
|
15354
16185
|
exports.VerifyEmailDto = VerifyEmailDto;
|
|
15355
16186
|
exports.VerifyOtpDto = VerifyOtpDto;
|
|
15356
16187
|
exports.WS_TICKET_TTL_SECONDS = WS_TICKET_TTL_SECONDS;
|
|
16188
|
+
exports.authDocumentSecurity = authDocumentSecurity;
|
|
15357
16189
|
exports.createAuthValidationPipe = createAuthValidationPipe;
|
|
15358
16190
|
exports.decrypt = decrypt;
|
|
16191
|
+
exports.describeChannelStatus = describeChannelStatus;
|
|
16192
|
+
exports.describeError = describeError;
|
|
15359
16193
|
exports.encrypt = encrypt;
|
|
15360
16194
|
exports.generateSecureToken = generateSecureToken;
|
|
15361
16195
|
exports.hasRole = hasRole;
|
|
15362
16196
|
exports.hmacSha256 = hmacSha256;
|
|
16197
|
+
exports.redactSecrets = redactSecrets;
|
|
15363
16198
|
exports.reduceToBaseWord = reduceToBaseWord;
|
|
15364
16199
|
exports.sanitizeHeaders = sanitizeHeaders;
|
|
15365
16200
|
exports.sha256 = sha256;
|