@bymax-one/nest-auth 1.0.11 → 1.1.0
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 +381 -1
- package/README.md +269 -107
- package/dist/client/index.cjs +41 -4
- package/dist/client/index.mjs +41 -4
- package/dist/nextjs/index.cjs +152 -51
- package/dist/nextjs/index.d.cts +149 -55
- package/dist/nextjs/index.d.ts +149 -55
- package/dist/nextjs/index.mjs +152 -51
- package/dist/react/index.cjs +77 -89
- package/dist/react/index.mjs +77 -89
- package/dist/server/index.cjs +5951 -1655
- package/dist/server/index.d.cts +2818 -188
- package/dist/server/index.d.ts +2818 -188
- package/dist/server/index.mjs +5933 -1644
- package/dist/shared/index.cjs +60 -9
- package/dist/shared/index.d.cts +126 -18
- package/dist/shared/index.d.ts +126 -18
- package/dist/shared/index.mjs +60 -9
- package/package.json +122 -43
package/dist/server/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as _nestjs_common from '@nestjs/common';
|
|
2
|
-
import { ModuleMetadata, InjectionToken, OptionalFactoryDependency, Provider, DynamicModule, HttpException, CanActivate, ExecutionContext, OnModuleInit } from '@nestjs/common';
|
|
2
|
+
import { ModuleMetadata, InjectionToken, OptionalFactoryDependency, Provider, DynamicModule, HttpException, CanActivate, ExecutionContext, OnModuleInit, ExceptionFilter, ArgumentsHost, ValidationPipeOptions, ValidationPipe } from '@nestjs/common';
|
|
3
3
|
import { Request, Response } from 'express';
|
|
4
4
|
import { Reflector } from '@nestjs/core';
|
|
5
5
|
import { JwtService } from '@nestjs/jwt';
|
|
@@ -11,6 +11,8 @@ import { Redis } from 'ioredis';
|
|
|
11
11
|
* Defines the canonical shape of a dashboard/tenant user and the repository
|
|
12
12
|
* contract that must be implemented by the consuming application. The library
|
|
13
13
|
* never imports a concrete ORM model — only this interface.
|
|
14
|
+
*
|
|
15
|
+
* @layer Interface
|
|
14
16
|
*/
|
|
15
17
|
/**
|
|
16
18
|
* Represents the authenticated user record for a dashboard/tenant user.
|
|
@@ -235,6 +237,24 @@ interface IUserRepository {
|
|
|
235
237
|
* @param verified - True to mark as verified, false to revoke verification.
|
|
236
238
|
*/
|
|
237
239
|
updateEmailVerified(id: string, verified: boolean): Promise<void>;
|
|
240
|
+
/**
|
|
241
|
+
* Replaces the account's email address.
|
|
242
|
+
*
|
|
243
|
+
* Called only after the new address has been proven — a token mailed to it and nothing
|
|
244
|
+
* else has come back — so the account stays verified across the change. An implementation
|
|
245
|
+
* that also clears its own verification flag would sign the user out of a state they just
|
|
246
|
+
* proved.
|
|
247
|
+
*
|
|
248
|
+
* The uniqueness of `email` within the tenant is checked by the caller immediately before
|
|
249
|
+
* this runs, but a unique index on `(tenantId, email)` is still the right thing to have:
|
|
250
|
+
* the check and this write are not one transaction, and the index is what makes the race
|
|
251
|
+
* a failed write instead of two accounts sharing a recovery address.
|
|
252
|
+
*
|
|
253
|
+
* @param id - Internal user ID.
|
|
254
|
+
* @param email - The new address, already normalized (trimmed, lowercased).
|
|
255
|
+
* @throws Whatever the implementation throws when the address is taken.
|
|
256
|
+
*/
|
|
257
|
+
updateEmail(id: string, email: string): Promise<void>;
|
|
238
258
|
/**
|
|
239
259
|
* Finds a user by their OAuth provider and external provider user ID.
|
|
240
260
|
*
|
|
@@ -270,12 +290,23 @@ interface IUserRepository {
|
|
|
270
290
|
createWithOAuth(data: CreateWithOAuthData): Promise<AuthUser>;
|
|
271
291
|
}
|
|
272
292
|
|
|
293
|
+
/**
|
|
294
|
+
* @fileoverview Main configuration contract for {@link BymaxAuthModule}.
|
|
295
|
+
*
|
|
296
|
+
* Defines `BymaxAuthModuleOptions` and all nested option groups consumed by
|
|
297
|
+
* `resolveOptions()` at module initialisation time.
|
|
298
|
+
*
|
|
299
|
+
* @layer Interface
|
|
300
|
+
*/
|
|
301
|
+
|
|
273
302
|
/**
|
|
274
303
|
* Main configuration interface for BymaxAuthModule.
|
|
275
304
|
*
|
|
276
|
-
* Passed to `BymaxAuthModule.registerAsync()`. All groups except `jwt
|
|
277
|
-
* `roles` are optional — unconfigured features are not
|
|
278
|
-
* NestJS container (zero overhead).
|
|
305
|
+
* Passed to `BymaxAuthModule.registerAsync()`. All groups except `jwt`,
|
|
306
|
+
* `roles` and `rateLimit` are optional — unconfigured features are not
|
|
307
|
+
* registered in the NestJS container (zero overhead). `rateLimit` is required
|
|
308
|
+
* because it is on unless turned off, and while it is on the deployment has to
|
|
309
|
+
* name which address keys the limit — see {@link BymaxAuthRateLimitOptions}.
|
|
279
310
|
*
|
|
280
311
|
* @remarks
|
|
281
312
|
* Only the asynchronous registration entry point (`registerAsync`) is exposed
|
|
@@ -294,6 +325,53 @@ interface IUserRepository {
|
|
|
294
325
|
* })
|
|
295
326
|
* ```
|
|
296
327
|
*/
|
|
328
|
+
/**
|
|
329
|
+
* How the client IP that keys the per-route limit is derived.
|
|
330
|
+
*
|
|
331
|
+
* - `'peer'` — the socket peer address, read directly from the connection. Never consults
|
|
332
|
+
* `X-Forwarded-For`, so a spoofed header cannot buy an attacker a fresh budget.
|
|
333
|
+
* - `'trusted-proxy'` — Express's `req.ip`, which honours the app's `trust proxy` setting and
|
|
334
|
+
* therefore the forwarding headers it admits.
|
|
335
|
+
*/
|
|
336
|
+
type ClientIpSource = 'peer' | 'trusted-proxy';
|
|
337
|
+
/**
|
|
338
|
+
* Per-IP rate limiting, as a discriminated union on `enabled`.
|
|
339
|
+
*
|
|
340
|
+
* The limiter is on unless it is turned off, and while it is on the deployment must say which
|
|
341
|
+
* address keys it. Neither value can be the default, because each is a working limiter in one
|
|
342
|
+
* deployment and no limiter at all in the other: `'peer'` behind any proxy reads the proxy's
|
|
343
|
+
* address for every client, so all of them share one bucket and a single caller sending a
|
|
344
|
+
* handful of logins can lock out the whole user base with no credential; `'trusted-proxy'` on a
|
|
345
|
+
* directly exposed app reads whatever the caller wrote in `X-Forwarded-For`, and a limiter whose
|
|
346
|
+
* key the attacker picks enforces nothing. Both look like a working limiter at runtime, and
|
|
347
|
+
* nothing detects the mismatch.
|
|
348
|
+
*
|
|
349
|
+
* The union is what makes that a compile error rather than a startup one. `resolveOptions`
|
|
350
|
+
* still checks it — the type binds a TypeScript consumer and nobody else, and this is a
|
|
351
|
+
* published package that is also called from JavaScript and configured from JSON.
|
|
352
|
+
*/
|
|
353
|
+
type BymaxAuthRateLimitOptions = {
|
|
354
|
+
/**
|
|
355
|
+
* Whether the library enforces the per-route limits in `AUTH_THROTTLE_CONFIGS`.
|
|
356
|
+
* Default: `true`.
|
|
357
|
+
*
|
|
358
|
+
* Those numbers used to be advisory — they took effect only if the host wired
|
|
359
|
+
* `ThrottlerModule` and registered its guard, and a deployment that did not ran every auth
|
|
360
|
+
* route unlimited without being told. The library now enforces them itself, backed by the
|
|
361
|
+
* same Redis counter as the brute-force lockout, so the limit also holds across instances.
|
|
362
|
+
*/
|
|
363
|
+
readonly enabled?: true;
|
|
364
|
+
/** Required while the limiter is on. See {@link ClientIpSource}. */
|
|
365
|
+
readonly clientIpSource: ClientIpSource;
|
|
366
|
+
} | {
|
|
367
|
+
/**
|
|
368
|
+
* Set `false` when the same limits are already enforced at the edge (an API gateway, a
|
|
369
|
+
* WAF, or a host-side `ThrottlerModule`) and counting twice is not wanted.
|
|
370
|
+
*/
|
|
371
|
+
readonly enabled: false;
|
|
372
|
+
/** Never read while the limiter is off, so it need not be stated. */
|
|
373
|
+
readonly clientIpSource?: ClientIpSource;
|
|
374
|
+
};
|
|
297
375
|
interface BymaxAuthModuleOptions {
|
|
298
376
|
/**
|
|
299
377
|
* JWT signing configuration.
|
|
@@ -310,8 +388,27 @@ interface BymaxAuthModuleOptions {
|
|
|
310
388
|
*
|
|
311
389
|
* `resolveOptions()` validates this at module startup and throws if requirements are not met.
|
|
312
390
|
* The secret value is never logged — only its length and entropy are reported in error messages.
|
|
391
|
+
*
|
|
392
|
+
* @throws {Error} When the value fails validation at module initialisation.
|
|
313
393
|
*/
|
|
314
394
|
secret: string;
|
|
395
|
+
/**
|
|
396
|
+
* Secrets retired by a rotation, accepted for **verification only**. Default: none.
|
|
397
|
+
*
|
|
398
|
+
* Rotating `jwt.secret` without this signs every outstanding token out at once, and
|
|
399
|
+
* invalidates every stored recovery-code digest — those are keyed by an HMAC derived from
|
|
400
|
+
* the secret, so a rotation would lock users out of the codes they printed and filed.
|
|
401
|
+
* Listing the previous secret here keeps both readable while tokens issued under it drain,
|
|
402
|
+
* so a rotation is a rollout rather than a mass logout.
|
|
403
|
+
*
|
|
404
|
+
* Signing always uses `jwt.secret`. Entries here are only ever tried after it, and only to
|
|
405
|
+
* verify, so a rotation is one-way: nothing new is ever produced under a retired secret.
|
|
406
|
+
*
|
|
407
|
+
* Remove an entry once the longest-lived thing signed under it has expired — every entry is
|
|
408
|
+
* a key that still opens the door. Each is validated exactly like `jwt.secret`: a weak
|
|
409
|
+
* previous secret is as forgeable as a weak current one.
|
|
410
|
+
*/
|
|
411
|
+
previousSecrets?: string[];
|
|
315
412
|
/**
|
|
316
413
|
* Access token expiration expressed as a time string (e.g. `'15m'`, `'1h'`).
|
|
317
414
|
* Default: `'15m'`
|
|
@@ -327,6 +424,25 @@ interface BymaxAuthModuleOptions {
|
|
|
327
424
|
* Default: `7`
|
|
328
425
|
*/
|
|
329
426
|
refreshExpiresInDays?: number;
|
|
427
|
+
/**
|
|
428
|
+
* Hard cap on how long one login can be extended by rotation, in days.
|
|
429
|
+
* Default: `0` — no cap.
|
|
430
|
+
*
|
|
431
|
+
* `refreshExpiresInDays` bounds how long a single refresh token lives, not how long a
|
|
432
|
+
* *session* lives: a client that rotates every fifteen minutes renews that lifetime
|
|
433
|
+
* indefinitely, so a session established once can outlive the laptop it was established
|
|
434
|
+
* on. This caps the whole lineage — the family's birth time is stamped at login and
|
|
435
|
+
* carried through every rotation, and once the cap is passed the rotation is refused and
|
|
436
|
+
* the user signs in again.
|
|
437
|
+
*
|
|
438
|
+
* Left off by default because switching it on ends sessions that are already older than
|
|
439
|
+
* the cap. Pick a value the product can justify asking a user to re-authenticate at (30
|
|
440
|
+
* or 90 days are common), and set it deliberately.
|
|
441
|
+
*
|
|
442
|
+
* Sessions written before this existed carry no birth time and are not capped; they age
|
|
443
|
+
* out under `refreshExpiresInDays` like any other.
|
|
444
|
+
*/
|
|
445
|
+
absoluteSessionLifetimeDays?: number;
|
|
330
446
|
/**
|
|
331
447
|
* JWT signing algorithm. Only `'HS256'` is supported.
|
|
332
448
|
* Default: `'HS256'`
|
|
@@ -336,6 +452,28 @@ interface BymaxAuthModuleOptions {
|
|
|
336
452
|
* algorithm confusion attacks. This value is pinned in all guards via `algorithms: ['HS256']`.
|
|
337
453
|
*/
|
|
338
454
|
algorithm?: 'HS256';
|
|
455
|
+
/**
|
|
456
|
+
* The `iss` claim stamped on every token this backend mints, and required on every token
|
|
457
|
+
* it verifies.
|
|
458
|
+
*
|
|
459
|
+
* Absent by default, so an existing deployment is unchanged. When set, a token carrying a
|
|
460
|
+
* different issuer — or none at all — is rejected. That is the whole point: a verifier
|
|
461
|
+
* that accepts an unstamped token gives an attacker a way to opt out of the check.
|
|
462
|
+
*
|
|
463
|
+
* Both backends sharing a deployment must be configured with the same value, or they stop
|
|
464
|
+
* accepting each other's tokens. Turning it on invalidates the access tokens already in
|
|
465
|
+
* flight; the window is one access-token lifetime and clients recover by refreshing, since
|
|
466
|
+
* the refresh token is opaque and carries no claims.
|
|
467
|
+
*/
|
|
468
|
+
issuer?: string;
|
|
469
|
+
/**
|
|
470
|
+
* The `aud` claim, with the same semantics as {@link issuer}.
|
|
471
|
+
*
|
|
472
|
+
* Names who the token is *for*. With HS256 the verifier can also sign, so audience binding
|
|
473
|
+
* is what stops a token minted for one service being replayed at another that trusts the
|
|
474
|
+
* same secret.
|
|
475
|
+
*/
|
|
476
|
+
audience?: string;
|
|
339
477
|
/**
|
|
340
478
|
* Grace window in seconds during which the old refresh token remains valid
|
|
341
479
|
* after rotation. Prevents race conditions on concurrent requests.
|
|
@@ -350,8 +488,17 @@ interface BymaxAuthModuleOptions {
|
|
|
350
488
|
password?: {
|
|
351
489
|
/**
|
|
352
490
|
* scrypt CPU/memory cost factor (N). Must be a power of 2.
|
|
353
|
-
* Default: `
|
|
354
|
-
*
|
|
491
|
+
* Default: `131072` (2^17), the minimum OWASP recommends for scrypt alongside `r=8, p=1`.
|
|
492
|
+
* Minimum enforced by `resolveOptions()`: `16384` (2^14). Values below that are rejected at
|
|
493
|
+
* startup — do not lower this for production workloads.
|
|
494
|
+
*
|
|
495
|
+
* The default costs roughly 128 MiB and ~100 ms per hash on a modern core. That is the
|
|
496
|
+
* point: it is what makes an offline attack on a leaked hash expensive. Budget for it —
|
|
497
|
+
* every login and registration pays it once, and a host that cannot afford the memory
|
|
498
|
+
* should lower `costFactor` deliberately, having read what it is buying, rather than
|
|
499
|
+
* inherit a weaker default that never announced itself.
|
|
500
|
+
*
|
|
501
|
+
* @throws {Error} When the value fails validation at module initialisation.
|
|
355
502
|
*/
|
|
356
503
|
costFactor?: number;
|
|
357
504
|
/**
|
|
@@ -364,6 +511,21 @@ interface BymaxAuthModuleOptions {
|
|
|
364
511
|
* Default: `1`
|
|
365
512
|
*/
|
|
366
513
|
parallelization?: number;
|
|
514
|
+
/**
|
|
515
|
+
* Extra words the default password checker should refuse, on top of the ones it ships.
|
|
516
|
+
*
|
|
517
|
+
* ASVS v5 §6.2.11 asks for a "documented list of context specific words" — the deployment's
|
|
518
|
+
* own product, company, and domain names, which are exactly the words its users reach for
|
|
519
|
+
* and which no general corpus contains. Entries are reduced the same way a candidate is
|
|
520
|
+
* (lowercased, leet undone, trailing digits dropped), so listing `Acme` also refuses
|
|
521
|
+
* `Acme2024!` and `@cme123` without anyone having to think of them.
|
|
522
|
+
*
|
|
523
|
+
* Ignored when a custom `BYMAX_AUTH_BREACH_CHECKER` is supplied — that provider owns the
|
|
524
|
+
* decision entirely.
|
|
525
|
+
*
|
|
526
|
+
* Default: `[]`
|
|
527
|
+
*/
|
|
528
|
+
blocklist?: readonly string[];
|
|
367
529
|
};
|
|
368
530
|
/**
|
|
369
531
|
* Token delivery mode.
|
|
@@ -431,6 +593,8 @@ interface BymaxAuthModuleOptions {
|
|
|
431
593
|
* Must start with `/` and exactly match the directory portion of the
|
|
432
594
|
* real `/mfa/*` route path. Validated at startup.
|
|
433
595
|
*
|
|
596
|
+
* @throws {Error} When the value fails validation at module initialisation.
|
|
597
|
+
*
|
|
434
598
|
* @example
|
|
435
599
|
* ```ts
|
|
436
600
|
* // App calls `app.setGlobalPrefix('api')` and uses default routePrefix:
|
|
@@ -466,7 +630,36 @@ interface BymaxAuthModuleOptions {
|
|
|
466
630
|
* Pick this for embedded scenarios (iframes, third-party widgets).
|
|
467
631
|
*/
|
|
468
632
|
sameSite?: 'lax' | 'strict' | 'none';
|
|
633
|
+
/**
|
|
634
|
+
* Origins allowed to make state-changing requests that carry the session cookie.
|
|
635
|
+
* Default: `[]`.
|
|
636
|
+
*
|
|
637
|
+
* Each entry is a full origin — scheme, host and, when non-default, port
|
|
638
|
+
* (`'https://app.example.com'`, `'http://localhost:3000'`) — compared verbatim against the
|
|
639
|
+
* request's `Origin` header. No wildcards: an origin allowlist that matches by pattern is
|
|
640
|
+
* one typo away from allowing an attacker-controlled subdomain.
|
|
641
|
+
*
|
|
642
|
+
* This only matters with `sameSite: 'none'`. Under `'lax'` or `'strict'` the browser does
|
|
643
|
+
* not send the cookie cross-site at all, so there is nothing to authorize; the resolver
|
|
644
|
+
* warns when the two settings disagree, because a `'none'` deployment with an empty list
|
|
645
|
+
* rejects every cross-site call and one with a list but `'lax'` never uses it.
|
|
646
|
+
*
|
|
647
|
+
* @example
|
|
648
|
+
* ```ts
|
|
649
|
+
* { cookies: { sameSite: 'none', trustedOrigins: ['https://app.example.com'] } }
|
|
650
|
+
* ```
|
|
651
|
+
*/
|
|
652
|
+
trustedOrigins?: string[];
|
|
469
653
|
};
|
|
654
|
+
/**
|
|
655
|
+
* Per-IP rate limiting of the auth routes, enforced by the library itself.
|
|
656
|
+
*
|
|
657
|
+
* Required, and shaped so the compiler asks the question the module would otherwise only ask
|
|
658
|
+
* at startup: a deployment that leaves the limiter on must name the client-IP source, and one
|
|
659
|
+
* that turns it off need not. Nothing that compiles today stops compiling for a reason that
|
|
660
|
+
* would not already have refused to boot.
|
|
661
|
+
*/
|
|
662
|
+
rateLimit: BymaxAuthRateLimitOptions;
|
|
470
663
|
/**
|
|
471
664
|
* Multi-factor authentication (MFA/TOTP) configuration.
|
|
472
665
|
* When provided, `encryptionKey` and `issuer` are required.
|
|
@@ -479,8 +672,27 @@ interface BymaxAuthModuleOptions {
|
|
|
479
672
|
* Generate with: `crypto.randomBytes(32).toString('base64')` (44 chars).
|
|
480
673
|
*
|
|
481
674
|
* `resolveOptions()` validates this at startup and throws if the decoded length is wrong.
|
|
675
|
+
*
|
|
676
|
+
* @throws {Error} When the value fails validation at module initialisation.
|
|
482
677
|
*/
|
|
483
678
|
encryptionKey: string;
|
|
679
|
+
/**
|
|
680
|
+
* Keys retired by a rotation, accepted for **decryption only**. Default: none.
|
|
681
|
+
*
|
|
682
|
+
* A TOTP secret is stored encrypted under `encryptionKey` and the ciphertext records no key
|
|
683
|
+
* identifier, so changing that key without this makes every stored secret undecryptable —
|
|
684
|
+
* every enrolled user's authenticator stops matching, at once, with no way back. Listing
|
|
685
|
+
* the previous key keeps those secrets readable, and each one is re-encrypted under the
|
|
686
|
+
* current key the next time its owner passes a challenge, so the rotation drains on its own.
|
|
687
|
+
*
|
|
688
|
+
* Encryption always uses `encryptionKey`; entries here are only ever tried after it, and
|
|
689
|
+
* only to decrypt. AES-GCM authenticates, so a wrong key fails unambiguously rather than
|
|
690
|
+
* returning garbage — trying them in order is safe.
|
|
691
|
+
*
|
|
692
|
+
* Remove an entry once no stored secret is still under it. Each is validated exactly like
|
|
693
|
+
* the current key.
|
|
694
|
+
*/
|
|
695
|
+
previousEncryptionKeys?: string[];
|
|
484
696
|
/**
|
|
485
697
|
* Issuer name displayed in authenticator apps (e.g. `'My App'`, `'Acme Corp'`).
|
|
486
698
|
* **Required if MFA is configured.**
|
|
@@ -520,18 +732,6 @@ interface BymaxAuthModuleOptions {
|
|
|
520
732
|
* @returns Maximum number of concurrent sessions for this user
|
|
521
733
|
*/
|
|
522
734
|
maxSessionsResolver?: (user: AuthUser) => number | Promise<number>;
|
|
523
|
-
/**
|
|
524
|
-
* Eviction strategy when the session limit is reached.
|
|
525
|
-
* `'fifo'` removes the oldest session to make room for the new one.
|
|
526
|
-
* Default: `'fifo'`
|
|
527
|
-
*
|
|
528
|
-
* @remarks
|
|
529
|
-
* Under FIFO eviction, an attacker who establishes a new session will silently
|
|
530
|
-
* evict a legitimate user's session with no visible signal. Implement the
|
|
531
|
-
* `onSessionEvicted` hook in your `IAuthHooks` class to detect and alert on
|
|
532
|
-
* unexpected evictions, which may indicate an account takeover attempt.
|
|
533
|
-
*/
|
|
534
|
-
evictionStrategy?: 'fifo';
|
|
535
735
|
};
|
|
536
736
|
/**
|
|
537
737
|
* Brute-force login protection configuration.
|
|
@@ -540,7 +740,8 @@ interface BymaxAuthModuleOptions {
|
|
|
540
740
|
bruteForce?: {
|
|
541
741
|
/**
|
|
542
742
|
* Maximum number of failed login attempts before lockout.
|
|
543
|
-
* Default: `
|
|
743
|
+
* Default: `5` — aligned with the per-IP throttle default; raising it widens the
|
|
744
|
+
* credential brute-force window. Bounded to `1..=100` at startup.
|
|
544
745
|
*/
|
|
545
746
|
maxAttempts?: number;
|
|
546
747
|
/**
|
|
@@ -563,7 +764,8 @@ interface BymaxAuthModuleOptions {
|
|
|
563
764
|
method?: 'token' | 'otp';
|
|
564
765
|
/**
|
|
565
766
|
* TTL for reset tokens in seconds.
|
|
566
|
-
* Default: `
|
|
767
|
+
* Default: `600` (10 minutes), matching OWASP guidance for time-sensitive credential
|
|
768
|
+
* recovery. Values beyond 1800 meaningfully widen the window for stolen-email replay.
|
|
567
769
|
*/
|
|
568
770
|
tokenTtlSeconds?: number;
|
|
569
771
|
/**
|
|
@@ -577,6 +779,8 @@ interface BymaxAuthModuleOptions {
|
|
|
577
779
|
* for `crypto.randomInt`. Values outside this range are rejected by `resolveOptions()`
|
|
578
780
|
* at startup with a descriptive error.
|
|
579
781
|
* Default: `6`
|
|
782
|
+
*
|
|
783
|
+
* @throws {Error} When the value fails validation at module initialisation.
|
|
580
784
|
*/
|
|
581
785
|
otpLength?: number;
|
|
582
786
|
};
|
|
@@ -586,7 +790,8 @@ interface BymaxAuthModuleOptions {
|
|
|
586
790
|
emailVerification?: {
|
|
587
791
|
/**
|
|
588
792
|
* When `true`, users must verify their email before they can log in.
|
|
589
|
-
* Default: `
|
|
793
|
+
* Default: `true` — secure by default. A deployment that accepts unverified addresses
|
|
794
|
+
* must opt out explicitly with `emailVerification.required: false`.
|
|
590
795
|
*/
|
|
591
796
|
required?: boolean;
|
|
592
797
|
/**
|
|
@@ -607,6 +812,23 @@ interface BymaxAuthModuleOptions {
|
|
|
607
812
|
*/
|
|
608
813
|
enabled?: boolean;
|
|
609
814
|
};
|
|
815
|
+
/**
|
|
816
|
+
* Address-change configuration.
|
|
817
|
+
*
|
|
818
|
+
* The flow itself is switched on by `controllers.emailChange`; this group only tunes it, so
|
|
819
|
+
* it can be omitted entirely.
|
|
820
|
+
*/
|
|
821
|
+
emailChange?: {
|
|
822
|
+
/**
|
|
823
|
+
* TTL for the address-change verification token in seconds.
|
|
824
|
+
*
|
|
825
|
+
* Default: `3600` (1 hour). Shorter than an invitation because the recipient is a user
|
|
826
|
+
* who just asked for the change and is waiting on the message — and because the token
|
|
827
|
+
* points at the account's recovery credential, so a link sitting in a mailbox for two
|
|
828
|
+
* days is a longer window than the flow needs.
|
|
829
|
+
*/
|
|
830
|
+
tokenTtlSeconds?: number;
|
|
831
|
+
};
|
|
610
832
|
/**
|
|
611
833
|
* User invitation system configuration.
|
|
612
834
|
*/
|
|
@@ -688,6 +910,8 @@ interface BymaxAuthModuleOptions {
|
|
|
688
910
|
* In production (`NODE_ENV === 'production'`), the URL must use HTTPS or
|
|
689
911
|
* be a relative path (starts with `/`) — same posture as `callbackUrl`.
|
|
690
912
|
*
|
|
913
|
+
* @throws {Error} When the value fails validation at module initialisation.
|
|
914
|
+
*
|
|
691
915
|
* @example
|
|
692
916
|
* ```typescript
|
|
693
917
|
* successRedirectUrl: 'https://app.example.com/dashboard'
|
|
@@ -802,6 +1026,8 @@ interface BymaxAuthModuleOptions {
|
|
|
802
1026
|
* @param req - The Express request object
|
|
803
1027
|
* @returns The tenant ID string, or a Promise resolving to it
|
|
804
1028
|
*
|
|
1029
|
+
* @throws {Error} When the resolver returns an empty string or throws.
|
|
1030
|
+
*
|
|
805
1031
|
* @remarks
|
|
806
1032
|
* The resolver must return a non-empty string or throw — returning `undefined`,
|
|
807
1033
|
* `null`, or an empty string is treated as a misconfiguration and the request
|
|
@@ -847,9 +1073,15 @@ interface BymaxAuthModuleOptions {
|
|
|
847
1073
|
mfa?: boolean;
|
|
848
1074
|
/** Enables `PasswordResetController`. Default: `true` */
|
|
849
1075
|
passwordReset?: boolean;
|
|
850
|
-
/**
|
|
1076
|
+
/**
|
|
1077
|
+
* Enables `SessionController`. **Opt-in** — `Default: false`. Also requires
|
|
1078
|
+
* `sessions.enabled: true`; setting one without the other is a startup error.
|
|
1079
|
+
*/
|
|
851
1080
|
sessions?: boolean;
|
|
852
|
-
/**
|
|
1081
|
+
/**
|
|
1082
|
+
* Enables `PlatformAuthController`. **Opt-in** — `Default: false`. Also requires
|
|
1083
|
+
* `platform.enabled: true`; setting one without the other is a startup error.
|
|
1084
|
+
*/
|
|
853
1085
|
platform?: boolean;
|
|
854
1086
|
/**
|
|
855
1087
|
* Enables `OAuthController` and `OAuthService`.
|
|
@@ -860,8 +1092,19 @@ interface BymaxAuthModuleOptions {
|
|
|
860
1092
|
* Default: `false`
|
|
861
1093
|
*/
|
|
862
1094
|
oauth?: boolean;
|
|
863
|
-
/**
|
|
1095
|
+
/**
|
|
1096
|
+
* Enables `InvitationController`. **Opt-in** — `Default: false`. Also requires
|
|
1097
|
+
* `invitations.enabled: true`; setting one without the other is a startup error.
|
|
1098
|
+
*/
|
|
864
1099
|
invitations?: boolean;
|
|
1100
|
+
/**
|
|
1101
|
+
* Enables `EmailChangeController` and `EmailChangeService`. **Opt-in** — `Default: false`.
|
|
1102
|
+
*
|
|
1103
|
+
* Requires the configured {@link IEmailProvider} to implement
|
|
1104
|
+
* `sendEmailChangeVerification`: the flow cannot deliver its token without it, and the
|
|
1105
|
+
* module refuses to boot rather than mint tokens nobody receives.
|
|
1106
|
+
*/
|
|
1107
|
+
emailChange?: boolean;
|
|
865
1108
|
};
|
|
866
1109
|
/**
|
|
867
1110
|
* TTL in seconds for the user status Redis cache.
|
|
@@ -919,6 +1162,15 @@ interface AuthModuleAsyncOptions {
|
|
|
919
1162
|
controllers?: BymaxAuthModuleOptions['controllers'];
|
|
920
1163
|
}
|
|
921
1164
|
|
|
1165
|
+
/**
|
|
1166
|
+
* @fileoverview Root NestJS dynamic module for `@bymax-one/nest-auth`.
|
|
1167
|
+
*
|
|
1168
|
+
* Exposes `BymaxAuthModule.forRoot()` and `BymaxAuthModule.registerAsync()`
|
|
1169
|
+
* as the sole entry points for library configuration.
|
|
1170
|
+
*
|
|
1171
|
+
* @layer Module
|
|
1172
|
+
*/
|
|
1173
|
+
|
|
922
1174
|
/**
|
|
923
1175
|
* Root authentication module for the @bymax-one/nest-auth library.
|
|
924
1176
|
*
|
|
@@ -960,7 +1212,7 @@ interface AuthModuleAsyncOptions {
|
|
|
960
1212
|
* this is intentional for testing environments. Supply a real `BYMAX_AUTH_EMAIL_PROVIDER`
|
|
961
1213
|
* in production to ensure reset emails are delivered.
|
|
962
1214
|
* - **MFA is opt-in.** Set `controllers: { mfa: true }` **on the `registerAsync()`
|
|
963
|
-
* call** (not inside `useFactory
|
|
1215
|
+
* call** (not inside `useFactory`, which throws at startup if you do) **and** supply `mfa.encryptionKey` + `mfa.issuer`
|
|
964
1216
|
* in the factory return value. Omitting either leaves `MfaService` and
|
|
965
1217
|
* `MfaRequiredGuard` completely unregistered. Setting `controllers.mfa: true`
|
|
966
1218
|
* without the `mfa` configuration group causes a startup error.
|
|
@@ -996,6 +1248,8 @@ declare class BymaxAuthModule {
|
|
|
996
1248
|
* useClass: PrismaUserRepository,
|
|
997
1249
|
* }
|
|
998
1250
|
* ```
|
|
1251
|
+
*
|
|
1252
|
+
* @layer Constants
|
|
999
1253
|
*/
|
|
1000
1254
|
/**
|
|
1001
1255
|
* Token for the resolved `BymaxAuthModuleOptions` object.
|
|
@@ -1026,6 +1280,13 @@ declare const BYMAX_AUTH_EMAIL_PROVIDER: unique symbol;
|
|
|
1026
1280
|
* Bound to a class that implements `IAuthHooks`.
|
|
1027
1281
|
*/
|
|
1028
1282
|
declare const BYMAX_AUTH_HOOKS: unique symbol;
|
|
1283
|
+
/**
|
|
1284
|
+
* Injection token for the password breach checker (`IPasswordBreachChecker`).
|
|
1285
|
+
*
|
|
1286
|
+
* Optional. When the consumer supplies none, the module registers a checker that approves
|
|
1287
|
+
* every password, so the credential path never reaches the network unless asked to.
|
|
1288
|
+
*/
|
|
1289
|
+
declare const BYMAX_AUTH_BREACH_CHECKER: unique symbol;
|
|
1029
1290
|
/**
|
|
1030
1291
|
* Token for the `ioredis` Redis client instance.
|
|
1031
1292
|
* **Required** — must be provided by the host application.
|
|
@@ -1039,6 +1300,8 @@ declare const BYMAX_AUTH_REDIS_CLIENT: unique symbol;
|
|
|
1039
1300
|
* Called once at module startup (inside the async factory). Throws descriptive errors
|
|
1040
1301
|
* if security-critical invariants are violated so that misconfigured deployments fail
|
|
1041
1302
|
* fast rather than silently using weak settings.
|
|
1303
|
+
*
|
|
1304
|
+
* @layer Config
|
|
1042
1305
|
*/
|
|
1043
1306
|
|
|
1044
1307
|
/**
|
|
@@ -1053,8 +1316,8 @@ declare const BYMAX_AUTH_REDIS_CLIENT: unique symbol;
|
|
|
1053
1316
|
* interface-extension compatibility check with `exactOptionalPropertyTypes`,
|
|
1054
1317
|
* which rejects intersection widening of optional function properties.
|
|
1055
1318
|
*/
|
|
1056
|
-
type ResolvedOptions = Omit<BymaxAuthModuleOptions, 'jwt' | 'password' | 'tokenDelivery' | 'cookies' | 'sessions' | 'bruteForce' | 'passwordReset' | 'emailVerification' | 'platform' | 'invitations' | 'controllers' | 'blockedStatuses' | 'redisNamespace' | 'routePrefix' | 'userStatusCacheTtlSeconds' | 'secureCookies' | 'mfa'> & {
|
|
1057
|
-
jwt: Required<BymaxAuthModuleOptions['jwt']>;
|
|
1319
|
+
type ResolvedOptions = Omit<BymaxAuthModuleOptions, 'jwt' | 'password' | 'tokenDelivery' | 'cookies' | 'sessions' | 'bruteForce' | 'passwordReset' | 'emailVerification' | 'platform' | 'invitations' | 'controllers' | 'blockedStatuses' | 'redisNamespace' | 'routePrefix' | 'userStatusCacheTtlSeconds' | 'secureCookies' | 'mfa' | 'rateLimit'> & {
|
|
1320
|
+
jwt: Required<Omit<BymaxAuthModuleOptions['jwt'], 'previousSecrets' | 'issuer' | 'audience'>> & Pick<BymaxAuthModuleOptions['jwt'], 'previousSecrets' | 'issuer' | 'audience'>;
|
|
1058
1321
|
password: Required<NonNullable<BymaxAuthModuleOptions['password']>>;
|
|
1059
1322
|
tokenDelivery: NonNullable<BymaxAuthModuleOptions['tokenDelivery']>;
|
|
1060
1323
|
cookies: Required<Omit<NonNullable<BymaxAuthModuleOptions['cookies']>, 'resolveDomains'>> & Pick<NonNullable<BymaxAuthModuleOptions['cookies']>, 'resolveDomains'>;
|
|
@@ -1064,6 +1327,11 @@ type ResolvedOptions = Omit<BymaxAuthModuleOptions, 'jwt' | 'password' | 'tokenD
|
|
|
1064
1327
|
emailVerification: Required<NonNullable<BymaxAuthModuleOptions['emailVerification']>>;
|
|
1065
1328
|
platform: Required<NonNullable<BymaxAuthModuleOptions['platform']>>;
|
|
1066
1329
|
invitations: Required<NonNullable<BymaxAuthModuleOptions['invitations']>>;
|
|
1330
|
+
emailChange: Required<NonNullable<BymaxAuthModuleOptions['emailChange']>>;
|
|
1331
|
+
rateLimit: {
|
|
1332
|
+
enabled: boolean;
|
|
1333
|
+
clientIpSource: ClientIpSource;
|
|
1334
|
+
};
|
|
1067
1335
|
controllers: Required<NonNullable<BymaxAuthModuleOptions['controllers']>>;
|
|
1068
1336
|
blockedStatuses: string[];
|
|
1069
1337
|
redisNamespace: string;
|
|
@@ -1082,12 +1350,22 @@ type ResolvedOptions = Omit<BymaxAuthModuleOptions, 'jwt' | 'password' | 'tokenD
|
|
|
1082
1350
|
* cryptographically independent.
|
|
1083
1351
|
*/
|
|
1084
1352
|
hmacKey: string;
|
|
1353
|
+
/**
|
|
1354
|
+
* HMAC keys derived from `jwt.previousSecrets`, in the order given. Empty unless a rotation
|
|
1355
|
+
* is in progress.
|
|
1356
|
+
*
|
|
1357
|
+
* Read-only, like the secrets they come from: a recovery-code digest written under a retired
|
|
1358
|
+
* key still verifies, so rotating `jwt.secret` does not lock users out of the codes they
|
|
1359
|
+
* printed and filed. Nothing is ever newly written under one — a code that matches here is
|
|
1360
|
+
* consumed and the set is regenerated under the current key.
|
|
1361
|
+
*/
|
|
1362
|
+
previousHmacKeys: string[];
|
|
1085
1363
|
/** When provided, all sub-fields are resolved with defaults applied. */
|
|
1086
1364
|
mfa?: Required<NonNullable<BymaxAuthModuleOptions['mfa']>>;
|
|
1087
1365
|
};
|
|
1088
1366
|
|
|
1089
1367
|
/**
|
|
1090
|
-
* Rate limiting configurations for @bymax-one/nest-auth endpoints.
|
|
1368
|
+
* @fileoverview Rate limiting configurations for @bymax-one/nest-auth endpoints.
|
|
1091
1369
|
*
|
|
1092
1370
|
* Exported as named throttler configurations compatible with the
|
|
1093
1371
|
* `@Throttle()` decorator from `@nestjs/throttler` >= 6.0.0.
|
|
@@ -1111,6 +1389,8 @@ type ResolvedOptions = Omit<BymaxAuthModuleOptions, 'jwt' | 'password' | 'tokenD
|
|
|
1111
1389
|
* @Post('login')
|
|
1112
1390
|
* async login(@Body() dto: LoginDto) { ... }
|
|
1113
1391
|
* ```
|
|
1392
|
+
*
|
|
1393
|
+
* @layer Constants
|
|
1114
1394
|
*/
|
|
1115
1395
|
declare const AUTH_THROTTLE_CONFIGS: {
|
|
1116
1396
|
/** POST /auth/login — 5 requests per minute per IP. Protects against brute-force by IP. */
|
|
@@ -1134,6 +1414,35 @@ declare const AUTH_THROTTLE_CONFIGS: {
|
|
|
1134
1414
|
readonly ttl: 60000;
|
|
1135
1415
|
};
|
|
1136
1416
|
};
|
|
1417
|
+
/**
|
|
1418
|
+
* POST /auth/logout — 20 requests per minute per IP.
|
|
1419
|
+
*
|
|
1420
|
+
* The route is public: it has to be, or a user whose 15-minute access token expired could
|
|
1421
|
+
* not sign out and the refresh session would live out its full week on a device they had
|
|
1422
|
+
* just abandoned. Public and unlimited is a different thing, though — each call costs a
|
|
1423
|
+
* SHA-256 and several Redis round trips, and nothing about the caller is known. The ceiling
|
|
1424
|
+
* is deliberately loose: a browser with several tabs can legitimately fire a handful at
|
|
1425
|
+
* once, and being rate-limited out of signing out would be its own security problem.
|
|
1426
|
+
*/
|
|
1427
|
+
readonly logout: {
|
|
1428
|
+
readonly default: {
|
|
1429
|
+
readonly limit: 20;
|
|
1430
|
+
readonly ttl: 60000;
|
|
1431
|
+
};
|
|
1432
|
+
};
|
|
1433
|
+
/**
|
|
1434
|
+
* POST /auth/ws-ticket — 20 requests per minute per IP.
|
|
1435
|
+
*
|
|
1436
|
+
* Authenticated, but every call writes a fresh single-use ticket key to Redis, so an
|
|
1437
|
+
* authenticated caller could otherwise mint them without bound. A reconnecting client needs
|
|
1438
|
+
* only one per socket; 20 covers a flapping connection without covering a loop.
|
|
1439
|
+
*/
|
|
1440
|
+
readonly wsTicket: {
|
|
1441
|
+
readonly default: {
|
|
1442
|
+
readonly limit: 20;
|
|
1443
|
+
readonly ttl: 60000;
|
|
1444
|
+
};
|
|
1445
|
+
};
|
|
1137
1446
|
/** POST /auth/password/forgot-password — 3 requests per 5 minutes per IP. */
|
|
1138
1447
|
readonly forgotPassword: {
|
|
1139
1448
|
readonly default: {
|
|
@@ -1148,6 +1457,20 @@ declare const AUTH_THROTTLE_CONFIGS: {
|
|
|
1148
1457
|
readonly ttl: 300000;
|
|
1149
1458
|
};
|
|
1150
1459
|
};
|
|
1460
|
+
/**
|
|
1461
|
+
* POST /auth/password/change — 5 requests per minute per IP.
|
|
1462
|
+
*
|
|
1463
|
+
* Authenticated, so the caller is already known — but each call spends a scrypt verification
|
|
1464
|
+
* of the current password plus a scrypt derivation of the new one, which is the most
|
|
1465
|
+
* expensive pair of operations in the library. The ceiling is the same as `login`'s for the
|
|
1466
|
+
* same reason: it is a password-guessing surface, just one that needs a live session first.
|
|
1467
|
+
*/
|
|
1468
|
+
readonly changePassword: {
|
|
1469
|
+
readonly default: {
|
|
1470
|
+
readonly limit: 5;
|
|
1471
|
+
readonly ttl: 60000;
|
|
1472
|
+
};
|
|
1473
|
+
};
|
|
1151
1474
|
/**
|
|
1152
1475
|
* POST /auth/password/verify-otp — 3 requests per 5 minutes per IP.
|
|
1153
1476
|
* More restrictive than the internal 5-attempt-per-OTP application limit,
|
|
@@ -1236,6 +1559,32 @@ declare const AUTH_THROTTLE_CONFIGS: {
|
|
|
1236
1559
|
readonly ttl: 60000;
|
|
1237
1560
|
};
|
|
1238
1561
|
};
|
|
1562
|
+
/** POST /auth/invitations/revoke — 10 requests per hour per IP, matching the mint. */
|
|
1563
|
+
readonly invitationRevoke: {
|
|
1564
|
+
readonly default: {
|
|
1565
|
+
readonly limit: 10;
|
|
1566
|
+
readonly ttl: 3600000;
|
|
1567
|
+
};
|
|
1568
|
+
};
|
|
1569
|
+
/**
|
|
1570
|
+
* POST /auth/email/change — 3 requests per 5 minutes per IP.
|
|
1571
|
+
*
|
|
1572
|
+
* Matches the reset-email limits: the request sends mail to an address the caller supplies,
|
|
1573
|
+
* so an unbounded one is a way to make the deployment send mail on demand.
|
|
1574
|
+
*/
|
|
1575
|
+
readonly emailChangeRequest: {
|
|
1576
|
+
readonly default: {
|
|
1577
|
+
readonly limit: 3;
|
|
1578
|
+
readonly ttl: 300000;
|
|
1579
|
+
};
|
|
1580
|
+
};
|
|
1581
|
+
/** POST /auth/email/change/confirm — 5 requests per minute per IP. */
|
|
1582
|
+
readonly emailChangeConfirm: {
|
|
1583
|
+
readonly default: {
|
|
1584
|
+
readonly limit: 5;
|
|
1585
|
+
readonly ttl: 60000;
|
|
1586
|
+
};
|
|
1587
|
+
};
|
|
1239
1588
|
/** GET /auth/sessions — 30 requests per minute per IP. */
|
|
1240
1589
|
readonly listSessions: {
|
|
1241
1590
|
readonly default: {
|
|
@@ -1309,6 +1658,12 @@ declare function encrypt(plaintext: string, keyBase64: string): string;
|
|
|
1309
1658
|
*/
|
|
1310
1659
|
declare function decrypt(ciphertext: string, keyBase64: string): string;
|
|
1311
1660
|
|
|
1661
|
+
/**
|
|
1662
|
+
* @fileoverview Secure token generation, SHA-256 hashing, HMAC-SHA-256, and
|
|
1663
|
+
* timing-safe comparison utilities.
|
|
1664
|
+
*
|
|
1665
|
+
* @layer Crypto
|
|
1666
|
+
*/
|
|
1312
1667
|
/**
|
|
1313
1668
|
* Generates a cryptographically secure random token as a hex string.
|
|
1314
1669
|
*
|
|
@@ -1432,6 +1787,8 @@ declare function hmacSha256(message: string, secret: string): string;
|
|
|
1432
1787
|
* - Anti-enumeration endpoints (verify-email, forgot-password) return 200 regardless
|
|
1433
1788
|
* of whether the email exists; a code/token error is returned only when the code
|
|
1434
1789
|
* itself is submitted.
|
|
1790
|
+
*
|
|
1791
|
+
* @layer Error
|
|
1435
1792
|
*/
|
|
1436
1793
|
/**
|
|
1437
1794
|
* Canonical error codes thrown by `AuthException` throughout the module.
|
|
@@ -1465,18 +1822,31 @@ declare const AUTH_ERROR_CODES: {
|
|
|
1465
1822
|
readonly TOKEN_REVOKED: "auth.token_revoked";
|
|
1466
1823
|
/** JWT is malformed, has an invalid signature, or the referenced user does not exist. */
|
|
1467
1824
|
readonly TOKEN_INVALID: "auth.token_invalid";
|
|
1825
|
+
/**
|
|
1826
|
+
* Internal-only: the request carried no credential at all. Never reaches a client —
|
|
1827
|
+
* surfaced as {@link AUTH_ERROR_CODES.TOKEN_INVALID}, so a caller cannot tell "you sent
|
|
1828
|
+
* nothing" from "you sent something unusable". Kept for logs and for the shared error
|
|
1829
|
+
* catalog, which rust-auth holds identical.
|
|
1830
|
+
*/
|
|
1831
|
+
readonly TOKEN_MISSING: "auth.token_missing";
|
|
1468
1832
|
/** Refresh token not found in Redis — expired or revoked. */
|
|
1469
1833
|
readonly REFRESH_TOKEN_INVALID: "auth.refresh_token_invalid";
|
|
1470
|
-
/** Session associated with the refresh token no longer exists in Redis. */
|
|
1471
|
-
readonly SESSION_EXPIRED: "auth.session_expired";
|
|
1472
|
-
/** Maximum concurrent session limit reached (informational — FIFO eviction handles this automatically). */
|
|
1473
|
-
readonly SESSION_LIMIT_REACHED: "auth.session_limit_reached";
|
|
1474
1834
|
/** Attempted to revoke a session that does not exist or does not belong to the user. */
|
|
1475
1835
|
readonly SESSION_NOT_FOUND: "auth.session_not_found";
|
|
1476
1836
|
/** Attempted to register an email that already exists in the same tenant. */
|
|
1477
1837
|
readonly EMAIL_ALREADY_EXISTS: "auth.email_already_exists";
|
|
1478
1838
|
/** Login attempted when `emailVerification.required` is true and email is unverified. */
|
|
1479
1839
|
readonly EMAIL_NOT_VERIFIED: "auth.email_not_verified";
|
|
1840
|
+
/**
|
|
1841
|
+
* The address-change token is unknown, expired, already used, or no longer bound to the
|
|
1842
|
+
* password it was minted against.
|
|
1843
|
+
*
|
|
1844
|
+
* One code for all four, deliberately: the holder of a bad link learns only that it does
|
|
1845
|
+
* not work, which is all they can act on. Telling them *why* would say whether an address
|
|
1846
|
+
* change is pending for the account — and a change request that an attacker planted is
|
|
1847
|
+
* exactly the thing they would want confirmed.
|
|
1848
|
+
*/
|
|
1849
|
+
readonly EMAIL_CHANGE_TOKEN_INVALID: "auth.email_change_token_invalid";
|
|
1480
1850
|
/** Endpoint requires MFA verification but the JWT does not have `mfaVerified: true`. */
|
|
1481
1851
|
readonly MFA_REQUIRED: "auth.mfa_required";
|
|
1482
1852
|
/** Submitted TOTP 6-digit code is incorrect. */
|
|
@@ -1489,24 +1859,80 @@ declare const AUTH_ERROR_CODES: {
|
|
|
1489
1859
|
readonly MFA_SETUP_REQUIRED: "auth.mfa_setup_required";
|
|
1490
1860
|
/** MFA temporary token (5-minute JWT) is invalid or expired. */
|
|
1491
1861
|
readonly MFA_TEMP_TOKEN_INVALID: "auth.mfa_temp_token_invalid";
|
|
1492
|
-
/**
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1862
|
+
/**
|
|
1863
|
+
* Another MFA state change for the same account is already in flight.
|
|
1864
|
+
*
|
|
1865
|
+
* Every MFA transition is a read-modify-write over one repository record that carries
|
|
1866
|
+
* `mfaEnabled`, the secret and the recovery codes together, and the write replaces all three
|
|
1867
|
+
* wholesale. Interleaved, two of them silently undo each other: a challenge that read the
|
|
1868
|
+
* codes before a `regenerate` and spliced after it restores the whole old set the user had
|
|
1869
|
+
* just replaced, and a challenge that splices after a `disable` completes puts `mfaEnabled`
|
|
1870
|
+
* back with the pre-disable secret. Refusing the second caller is how the library serializes
|
|
1871
|
+
* them. Retryable — the losing caller may simply try again.
|
|
1872
|
+
*/
|
|
1873
|
+
readonly MFA_STATE_CONFLICT: "auth.mfa_state_conflict";
|
|
1874
|
+
/**
|
|
1875
|
+
* The password appears in a known-breach corpus, or on the offline common-password screen.
|
|
1876
|
+
* It may satisfy every length and complexity rule and still be one an attacker tries first,
|
|
1877
|
+
* which is why the policy checks live in the request DTO and this does not.
|
|
1878
|
+
*/
|
|
1879
|
+
readonly PASSWORD_COMPROMISED: "auth.password_compromised";
|
|
1496
1880
|
/** Password reset token not found in Redis. */
|
|
1497
1881
|
readonly PASSWORD_RESET_TOKEN_INVALID: "auth.password_reset_token_invalid";
|
|
1498
|
-
/**
|
|
1499
|
-
|
|
1500
|
-
|
|
1882
|
+
/**
|
|
1883
|
+
* An OTP verification failed. The **only** code an OTP failure ever answers with: a wrong
|
|
1884
|
+
* code, a record that is not in Redis, and an exhausted attempt ceiling are deliberately
|
|
1885
|
+
* indistinguishable, and take the same time.
|
|
1886
|
+
*
|
|
1887
|
+
* Telling them apart defeated the anti-enumeration in front of them. `forgot-password`
|
|
1888
|
+
* answers the same whether or not the address exists, but only writes an OTP record when it
|
|
1889
|
+
* does — so one wrong code afterwards used to say which it had been.
|
|
1890
|
+
*/
|
|
1501
1891
|
readonly OTP_INVALID: "auth.otp_invalid";
|
|
1502
|
-
/**
|
|
1892
|
+
/**
|
|
1893
|
+
* Internal-only: the OTP record was not in Redis. Never reaches a client — surfaced as
|
|
1894
|
+
* {@link AUTH_ERROR_CODES.OTP_INVALID}, the same treatment {@link
|
|
1895
|
+
* AUTH_ERROR_CODES.TOKEN_EXPIRED} gets. Kept for logs and for the shared error catalog,
|
|
1896
|
+
* which rust-auth holds identical.
|
|
1897
|
+
*/
|
|
1503
1898
|
readonly OTP_EXPIRED: "auth.otp_expired";
|
|
1504
|
-
/**
|
|
1899
|
+
/**
|
|
1900
|
+
* Internal-only: OTP verification hit the five-attempt ceiling. Never reaches a client —
|
|
1901
|
+
* surfaced as {@link AUTH_ERROR_CODES.OTP_INVALID}, because only a record that exists can
|
|
1902
|
+
* reach a ceiling, which is the same disclosure by a slower route.
|
|
1903
|
+
*/
|
|
1505
1904
|
readonly OTP_MAX_ATTEMPTS: "auth.otp_max_attempts";
|
|
1506
1905
|
/** User's role does not satisfy the hierarchy required by the endpoint. */
|
|
1507
1906
|
readonly INSUFFICIENT_ROLE: "auth.insufficient_role";
|
|
1508
1907
|
/** Generic access-denied fallback when no more specific code applies. */
|
|
1509
1908
|
readonly FORBIDDEN: "auth.forbidden";
|
|
1909
|
+
/**
|
|
1910
|
+
* The request body or query failed DTO validation. Per-field failures serialize into
|
|
1911
|
+
* `error.details` as `[{ field, message }]`. Raised by the module's validation pipe so a
|
|
1912
|
+
* malformed request answers in the same envelope as every other error rather than in the
|
|
1913
|
+
* framework's default shape — the same code and the same details rust-auth emits.
|
|
1914
|
+
*/
|
|
1915
|
+
readonly VALIDATION: "auth.validation";
|
|
1916
|
+
/**
|
|
1917
|
+
* The caller exceeded a per-IP rate limit on an auth route. Carries `Retry-After`.
|
|
1918
|
+
* Distinct from `ACCOUNT_LOCKED`, which is the per-identity brute-force lockout.
|
|
1919
|
+
*/
|
|
1920
|
+
readonly TOO_MANY_REQUESTS: "auth.too_many_requests";
|
|
1921
|
+
/**
|
|
1922
|
+
* A state-changing request carrying the session cookie came from an origin the deployment
|
|
1923
|
+
* does not trust. Raised by `TrustedOriginGuard` — see `cookies.trustedOrigins`.
|
|
1924
|
+
*/
|
|
1925
|
+
readonly UNTRUSTED_ORIGIN: "auth.untrusted_origin";
|
|
1926
|
+
/**
|
|
1927
|
+
* A change to how the account authenticates was attempted without a recent authentication.
|
|
1928
|
+
*
|
|
1929
|
+
* Raised when enrolling MFA on an account that has no local password to re-prove — one
|
|
1930
|
+
* provisioned purely through OAuth. Those accounts have nothing this library can verify
|
|
1931
|
+
* inline, so the proof is temporal instead: the caller must have completed a real
|
|
1932
|
+
* authentication within the last few minutes. The client should send the user back through
|
|
1933
|
+
* sign-in and retry, which is why this is its own code rather than `INVALID_CREDENTIALS`.
|
|
1934
|
+
*/
|
|
1935
|
+
readonly REAUTHENTICATION_REQUIRED: "auth.reauthentication_required";
|
|
1510
1936
|
/** Invitation token not found in Redis — invalid or expired. */
|
|
1511
1937
|
readonly INVALID_INVITATION_TOKEN: "auth.invalid_invitation_token";
|
|
1512
1938
|
/** Generic OAuth failure — provider rejected the request or returned an error. */
|
|
@@ -1515,6 +1941,15 @@ declare const AUTH_ERROR_CODES: {
|
|
|
1515
1941
|
readonly OAUTH_EMAIL_MISMATCH: "auth.oauth_email_mismatch";
|
|
1516
1942
|
/** Platform-admin endpoint accessed with a dashboard JWT instead of a platform JWT. */
|
|
1517
1943
|
readonly PLATFORM_AUTH_REQUIRED: "auth.platform_auth_required";
|
|
1944
|
+
/**
|
|
1945
|
+
* An unexpected internal failure. The cause is logged and never serialized.
|
|
1946
|
+
*
|
|
1947
|
+
* Raised only by {@link AuthExceptionFilter}, which a host registers to give unhandled
|
|
1948
|
+
* failures the same `{ error: { code, message, details } }` envelope everything else
|
|
1949
|
+
* answers with. Without the filter the framework's own 500 shape stands, which is the
|
|
1950
|
+
* behaviour this library had before it existed.
|
|
1951
|
+
*/
|
|
1952
|
+
readonly INTERNAL: "auth.internal";
|
|
1518
1953
|
};
|
|
1519
1954
|
/**
|
|
1520
1955
|
* String literal union of all valid `AuthException` error codes.
|
|
@@ -1535,6 +1970,12 @@ type AuthErrorCode = (typeof AUTH_ERROR_CODES)[keyof typeof AUTH_ERROR_CODES];
|
|
|
1535
1970
|
*/
|
|
1536
1971
|
declare const AUTH_ERROR_MESSAGES: Readonly<Record<AuthErrorCode, string>>;
|
|
1537
1972
|
|
|
1973
|
+
/**
|
|
1974
|
+
* @fileoverview Domain exception class for all authentication-layer errors.
|
|
1975
|
+
*
|
|
1976
|
+
* @layer Error
|
|
1977
|
+
*/
|
|
1978
|
+
|
|
1538
1979
|
/**
|
|
1539
1980
|
* Standardized exception class for the @bymax-one/nest-auth module.
|
|
1540
1981
|
*
|
|
@@ -1561,7 +2002,14 @@ declare const AUTH_ERROR_MESSAGES: Readonly<Record<AuthErrorCode, string>>;
|
|
|
1561
2002
|
* ```
|
|
1562
2003
|
*/
|
|
1563
2004
|
declare class AuthException extends HttpException {
|
|
1564
|
-
|
|
2005
|
+
/**
|
|
2006
|
+
* @param code - Stable machine-readable error code from `AUTH_ERROR_CODES`.
|
|
2007
|
+
* @param statusCode - HTTP status code for the response. Defaults to `401 UNAUTHORIZED`.
|
|
2008
|
+
* @param details - Optional structured payload attached to the error body under
|
|
2009
|
+
* `error.details`. An array where the failure is a list — `auth.validation` renders its
|
|
2010
|
+
* per-field failures that way, matching what rust-auth serializes for the same code.
|
|
2011
|
+
*/
|
|
2012
|
+
constructor(code: AuthErrorCode, statusCode?: number, details?: Record<string, unknown> | readonly unknown[]);
|
|
1565
2013
|
}
|
|
1566
2014
|
|
|
1567
2015
|
/**
|
|
@@ -1571,6 +2019,8 @@ declare class AuthException extends HttpException {
|
|
|
1571
2019
|
* The library never imports a concrete mailer — consumers provide their own
|
|
1572
2020
|
* adapter (e.g. Resend, SendGrid, Nodemailer) that implements `IEmailProvider`
|
|
1573
2021
|
* and inject it via the NestJS DI token.
|
|
2022
|
+
*
|
|
2023
|
+
* @layer Interface
|
|
1574
2024
|
*/
|
|
1575
2025
|
/**
|
|
1576
2026
|
* Contextual information about a new user session sent in security alerts.
|
|
@@ -1668,6 +2118,56 @@ interface IEmailProvider {
|
|
|
1668
2118
|
* @param locale - BCP 47 locale tag for email language (e.g. `'en'`, `'pt-BR'`).
|
|
1669
2119
|
*/
|
|
1670
2120
|
sendEmailVerificationOtp(email: string, otp: string, locale?: string): Promise<void>;
|
|
2121
|
+
/**
|
|
2122
|
+
* Notifies the user that the password on their account has changed.
|
|
2123
|
+
*
|
|
2124
|
+
* Called after a completed password change *and* after a completed password reset. Both are
|
|
2125
|
+
* credential-binding events, and NIST SP 800-63B §4.6 requires the subscriber to be notified
|
|
2126
|
+
* through a channel independent of the transaction that made the change. The classic
|
|
2127
|
+
* takeover starts with a compromised mailbox: the attacker triggers a reset, completes it,
|
|
2128
|
+
* and deletes the mail. This notice is what turns "the victim finds out days later, at a
|
|
2129
|
+
* failed login" into "the victim finds out now" — and it is the one credential change this
|
|
2130
|
+
* interface used to stay silent about while announcing every MFA change unprompted.
|
|
2131
|
+
*
|
|
2132
|
+
* **Optional.** Declared with `?` so an existing provider keeps compiling; the library calls
|
|
2133
|
+
* it when present and logs at debug when it is not, rather than failing a password change
|
|
2134
|
+
* over a missing notification.
|
|
2135
|
+
*
|
|
2136
|
+
* @param email - Recipient's email address.
|
|
2137
|
+
* @param locale - BCP 47 locale tag for email language (e.g. `'en'`, `'pt-BR'`).
|
|
2138
|
+
*/
|
|
2139
|
+
sendPasswordChangedNotification?(email: string, locale?: string): Promise<void>;
|
|
2140
|
+
/**
|
|
2141
|
+
* Sends the address-change verification link to the **new** address.
|
|
2142
|
+
*
|
|
2143
|
+
* The token goes here and nowhere else: receiving it is what proves the requester controls
|
|
2144
|
+
* the address before it becomes the account's. The old address gets no token — only the
|
|
2145
|
+
* notification below, and only once the change has actually happened.
|
|
2146
|
+
*
|
|
2147
|
+
* Optional on the interface so an existing consumer keeps compiling, but the flow refuses
|
|
2148
|
+
* to mint a token when it is absent rather than writing one nobody will ever receive.
|
|
2149
|
+
*
|
|
2150
|
+
* @param newEmail - The address being moved to.
|
|
2151
|
+
* @param token - The raw single-use token. The provider builds the confirmation URL.
|
|
2152
|
+
* @param locale - Optional locale for the template.
|
|
2153
|
+
*/
|
|
2154
|
+
sendEmailChangeVerification?(newEmail: string, token: string, locale?: string): Promise<void>;
|
|
2155
|
+
/**
|
|
2156
|
+
* Notifies the **old** address that the account's address has changed.
|
|
2157
|
+
*
|
|
2158
|
+
* NIST SP 800-63B §4.6 asks for notification of a credential change, and the address is the
|
|
2159
|
+
* recovery credential: someone who moves it can then drive a password reset to a mailbox
|
|
2160
|
+
* the owner does not read. This message is what puts that in front of the owner while they
|
|
2161
|
+
* still control the address it arrives at.
|
|
2162
|
+
*
|
|
2163
|
+
* Fire-and-forget — a delivery failure does not roll back a change the user asked for and
|
|
2164
|
+
* has already proven.
|
|
2165
|
+
*
|
|
2166
|
+
* @param oldEmail - The address the account is leaving.
|
|
2167
|
+
* @param newEmail - The address it moved to, so the notice can say what happened.
|
|
2168
|
+
* @param locale - Optional locale for the template.
|
|
2169
|
+
*/
|
|
2170
|
+
sendEmailChangedNotification?(oldEmail: string, newEmail: string, locale?: string): Promise<void>;
|
|
1671
2171
|
/**
|
|
1672
2172
|
* Notifies the user that multi-factor authentication (MFA) has been enabled on
|
|
1673
2173
|
* their account.
|
|
@@ -1730,6 +2230,8 @@ interface IEmailProvider {
|
|
|
1730
2230
|
* The plugin pattern allows new providers (Google, GitHub, GitLab, etc.) to be
|
|
1731
2231
|
* registered without modifying the core auth module. Each plugin is responsible
|
|
1732
2232
|
* for its own authorize URL construction, code exchange, and profile normalization.
|
|
2233
|
+
*
|
|
2234
|
+
* @layer Interface
|
|
1733
2235
|
*/
|
|
1734
2236
|
/**
|
|
1735
2237
|
* Normalized user profile returned by any OAuth provider after a successful
|
|
@@ -1749,6 +2251,20 @@ interface OAuthProfile {
|
|
|
1749
2251
|
providerId: string;
|
|
1750
2252
|
/** Primary email address returned by the provider. */
|
|
1751
2253
|
email: string;
|
|
2254
|
+
/**
|
|
2255
|
+
* Whether the provider asserts it has verified this email address.
|
|
2256
|
+
*
|
|
2257
|
+
* @remarks
|
|
2258
|
+
* A plugin MUST report what the provider actually said, not what would be convenient. The
|
|
2259
|
+
* account created from an unverified address belongs to whoever controls the OAuth account,
|
|
2260
|
+
* not to whoever controls the mailbox — and if the library marks it verified anyway, the
|
|
2261
|
+
* consumer's "this email is proven" invariant is false from the first login.
|
|
2262
|
+
*
|
|
2263
|
+
* The shipped Google plugin refuses an unverified profile outright, so it always reports
|
|
2264
|
+
* `true`. Providers that hand back unverified addresses (GitHub, among others) must report
|
|
2265
|
+
* `false` and let the consumer's own verification flow do its job.
|
|
2266
|
+
*/
|
|
2267
|
+
emailVerified: boolean;
|
|
1752
2268
|
/**
|
|
1753
2269
|
* Display name returned by the provider, if available.
|
|
1754
2270
|
*
|
|
@@ -1765,7 +2281,7 @@ interface OAuthProfile {
|
|
|
1765
2281
|
* Contract for OAuth 2.0 Authorization Code flow plugins.
|
|
1766
2282
|
*
|
|
1767
2283
|
* Implement this interface to add a new OAuth provider. The plugin is
|
|
1768
|
-
* responsible for all three
|
|
2284
|
+
* responsible for all three operations in the flow:
|
|
1769
2285
|
* 1. Constructing the provider's authorization URL (with a CSRF-protection state value).
|
|
1770
2286
|
* 2. Exchanging the authorization code for an access token.
|
|
1771
2287
|
* 3. Fetching and normalizing the user profile.
|
|
@@ -1857,6 +2373,8 @@ interface OAuthProviderPlugin {
|
|
|
1857
2373
|
* - Never access raw HTTP headers inside hooks — use `context.sanitizedHeaders`
|
|
1858
2374
|
* which has been pre-processed by the `sanitizeHeaders` utility to remove
|
|
1859
2375
|
* authorization tokens, cookies, and other sensitive values.
|
|
2376
|
+
*
|
|
2377
|
+
* @layer Interface
|
|
1860
2378
|
*/
|
|
1861
2379
|
|
|
1862
2380
|
/**
|
|
@@ -2023,6 +2541,78 @@ interface IAuthHooks {
|
|
|
2023
2541
|
* @param context - Request metadata (IP, user agent, sanitized headers).
|
|
2024
2542
|
*/
|
|
2025
2543
|
afterLogout?(userId: string, context: HookContext): Promise<void> | void;
|
|
2544
|
+
/**
|
|
2545
|
+
* Called when a login attempt is refused.
|
|
2546
|
+
*
|
|
2547
|
+
* Every other hook on this interface fires on a success path, which leaves the failure side
|
|
2548
|
+
* of authentication with no structured seam at all: the events that matter most to detection
|
|
2549
|
+
* — a burst of wrong passwords, an account tripping its lockout, a stolen refresh token being
|
|
2550
|
+
* replayed — existed only as English log lines whose wording is not a contract and whose
|
|
2551
|
+
* change is not semver-visible. ASVS v5 §16.3.1 expects authentication operations to be
|
|
2552
|
+
* logged with their outcome, and §6.1.1 expects an *adaptive* response, which needs a signal
|
|
2553
|
+
* to adapt to.
|
|
2554
|
+
*
|
|
2555
|
+
* The email is passed rather than a user id because the common case has no user: a failure
|
|
2556
|
+
* against an address that does not exist is exactly the credential-stuffing signal a consumer
|
|
2557
|
+
* wants. `userId` is present only when the account resolved and the credential did not match.
|
|
2558
|
+
*
|
|
2559
|
+
* Fire-and-forget, like every hook here: a throw is logged and swallowed, never turned into a
|
|
2560
|
+
* different answer for the caller.
|
|
2561
|
+
*
|
|
2562
|
+
* @param details - What failed, and for whom, as far as it is known.
|
|
2563
|
+
* @param context - Request metadata (IP, user agent, sanitized headers).
|
|
2564
|
+
*/
|
|
2565
|
+
onLoginFailed?(details: {
|
|
2566
|
+
/** The address the attempt was made against, as submitted. */
|
|
2567
|
+
email: string;
|
|
2568
|
+
/** The tenant the attempt was scoped to. */
|
|
2569
|
+
tenantId: string;
|
|
2570
|
+
/** Present only when the account exists and the password did not match. */
|
|
2571
|
+
userId?: string;
|
|
2572
|
+
/**
|
|
2573
|
+
* Why it was refused. `invalid_credentials` covers both an unknown address and a wrong
|
|
2574
|
+
* password — the two are deliberately indistinguishable to the *caller*, but not to the
|
|
2575
|
+
* hook, which the `userId` above tells apart.
|
|
2576
|
+
*/
|
|
2577
|
+
reason: 'invalid_credentials' | 'account_blocked' | 'email_not_verified' | 'locked_out';
|
|
2578
|
+
}, context: HookContext): Promise<void> | void;
|
|
2579
|
+
/**
|
|
2580
|
+
* Called when an identifier crosses the brute-force threshold and is locked out.
|
|
2581
|
+
*
|
|
2582
|
+
* The single highest-value moment for alerting: one account under sustained attack, or —
|
|
2583
|
+
* seen across many identifiers at once — a credential-stuffing run in progress. It is also
|
|
2584
|
+
* the moment a support queue is about to receive a call, since the lockout is indiscriminate
|
|
2585
|
+
* about who is doing the guessing.
|
|
2586
|
+
*
|
|
2587
|
+
* @param details - The locked identifier and the window it is locked for.
|
|
2588
|
+
* @param context - Request metadata (IP, user agent, sanitized headers).
|
|
2589
|
+
*/
|
|
2590
|
+
onLockout?(details: {
|
|
2591
|
+
/** The address that was locked, as submitted. */
|
|
2592
|
+
email: string;
|
|
2593
|
+
/** The tenant the lockout is scoped to. */
|
|
2594
|
+
tenantId: string;
|
|
2595
|
+
/** Seconds until the window expires and attempts are accepted again. */
|
|
2596
|
+
retryAfterSeconds: number;
|
|
2597
|
+
}, context: HookContext): Promise<void> | void;
|
|
2598
|
+
/**
|
|
2599
|
+
* Called when a consumed refresh token is replayed after its grace window — the signature of
|
|
2600
|
+
* a stolen token — and its family is revoked.
|
|
2601
|
+
*
|
|
2602
|
+
* This is the strongest evidence of compromise the library produces. It is not a guess about
|
|
2603
|
+
* risk: a token that was already exchanged has been presented again by *someone*, and one of
|
|
2604
|
+
* the two holders is not the owner. A consumer wanting to force a password reset, page an
|
|
2605
|
+
* on-call, or raise the account's risk score has nothing else to key on.
|
|
2606
|
+
*
|
|
2607
|
+
* @param details - Whose lineage was revoked.
|
|
2608
|
+
* @param context - Request metadata (IP, user agent, sanitized headers).
|
|
2609
|
+
*/
|
|
2610
|
+
onRefreshTokenReuseDetected?(details: {
|
|
2611
|
+
/** The account whose token family was revoked. */
|
|
2612
|
+
userId: string;
|
|
2613
|
+
/** The revoked lineage, for correlating with a session listing. */
|
|
2614
|
+
familyId: string;
|
|
2615
|
+
}, context: HookContext): Promise<void> | void;
|
|
2026
2616
|
/**
|
|
2027
2617
|
* Called after MFA has been successfully enabled on a user account.
|
|
2028
2618
|
*
|
|
@@ -2149,6 +2739,8 @@ declare class NoOpAuthHooks implements IAuthHooks {
|
|
|
2149
2739
|
/**
|
|
2150
2740
|
* Permits all registration attempts unconditionally.
|
|
2151
2741
|
*
|
|
2742
|
+
* @param _data - Registration payload containing `email`, `name`, and `tenantId`.
|
|
2743
|
+
* @param _context - Hook execution context carrying request metadata.
|
|
2152
2744
|
* @returns `{ allowed: true }` — never blocks registration.
|
|
2153
2745
|
*/
|
|
2154
2746
|
beforeRegister(_data: {
|
|
@@ -2162,6 +2754,7 @@ declare class NoOpAuthHooks implements IAuthHooks {
|
|
|
2162
2754
|
*
|
|
2163
2755
|
* @param profile - Normalized OAuth profile from the provider.
|
|
2164
2756
|
* @param existingUser - Existing user found by the profile email, or `null`.
|
|
2757
|
+
* @param _context - Hook execution context carrying request metadata.
|
|
2165
2758
|
* @returns An {@link OAuthLoginResult} controlling the account resolution strategy.
|
|
2166
2759
|
*/
|
|
2167
2760
|
onOAuthLogin(profile: OAuthProfile, existingUser: SafeAuthUser | null, _context: HookContext): OAuthLoginResult;
|
|
@@ -2183,6 +2776,8 @@ declare class NoOpAuthHooks implements IAuthHooks {
|
|
|
2183
2776
|
* These interfaces represent the shape of a **decoded and verified** token.
|
|
2184
2777
|
* When signing tokens, `iat` and `exp` are populated automatically by
|
|
2185
2778
|
* `@nestjs/jwt` — do not include them in the signing payload.
|
|
2779
|
+
*
|
|
2780
|
+
* @layer Interface
|
|
2186
2781
|
*/
|
|
2187
2782
|
/**
|
|
2188
2783
|
* JWT payload for dashboard (tenant) user access tokens.
|
|
@@ -2214,12 +2809,27 @@ interface DashboardJwtPayload {
|
|
|
2214
2809
|
*
|
|
2215
2810
|
* Stamped at token issuance. When `true`, the `MfaRequiredGuard` enforces that
|
|
2216
2811
|
* `mfaVerified` is also `true` before granting access to protected resources.
|
|
2217
|
-
*
|
|
2218
|
-
*
|
|
2812
|
+
*
|
|
2813
|
+
* The Redis session persists this flag, so rotation carries it across — and rotation
|
|
2814
|
+
* additionally re-stamps it from the account it re-reads whenever the two diverge. Both
|
|
2815
|
+
* matter: without the first, every rotation would silently drop a session out of MFA
|
|
2816
|
+
* enforcement; without the second, a session created while MFA was off would stay exempt
|
|
2817
|
+
* for the refresh token's whole lifetime whenever the host enables MFA through its own
|
|
2818
|
+
* admin surface rather than this library's `verifyAndEnable`.
|
|
2219
2819
|
*/
|
|
2220
2820
|
mfaEnabled: boolean;
|
|
2221
2821
|
/** Whether the user completed MFA verification before this token was issued. */
|
|
2222
2822
|
mfaVerified: boolean;
|
|
2823
|
+
/**
|
|
2824
|
+
* The user's token **epoch** at issuance — a per-user generation counter the server bumps to
|
|
2825
|
+
* invalidate every outstanding access token at once (a password reset). The guards reject a
|
|
2826
|
+
* token whose epoch is below the user's stored epoch.
|
|
2827
|
+
*
|
|
2828
|
+
* Optional: a token issued before the field existed carries none, which reads as `0` and is
|
|
2829
|
+
* never rejected while the stored epoch is also `0` — the mechanism stays inert until the
|
|
2830
|
+
* first bump.
|
|
2831
|
+
*/
|
|
2832
|
+
epoch?: number;
|
|
2223
2833
|
/** Issued-at timestamp (Unix seconds). Populated automatically by `@nestjs/jwt`. */
|
|
2224
2834
|
iat: number;
|
|
2225
2835
|
/** Expiration timestamp (Unix seconds). Populated automatically by `@nestjs/jwt`. */
|
|
@@ -2248,13 +2858,23 @@ interface PlatformJwtPayload {
|
|
|
2248
2858
|
mfaEnabled: boolean;
|
|
2249
2859
|
/** Whether the admin completed MFA verification before this token was issued. */
|
|
2250
2860
|
mfaVerified: boolean;
|
|
2861
|
+
/**
|
|
2862
|
+
* The admin's token **epoch** at issuance — a per-user generation counter the server bumps to
|
|
2863
|
+
* invalidate every outstanding access token at once (a password reset). The guards reject a
|
|
2864
|
+
* token whose epoch is below the admin's stored epoch.
|
|
2865
|
+
*
|
|
2866
|
+
* Optional: a token issued before the field existed carries none, which reads as `0` and is
|
|
2867
|
+
* never rejected while the stored epoch is also `0` — the mechanism stays inert until the
|
|
2868
|
+
* first bump.
|
|
2869
|
+
*/
|
|
2870
|
+
epoch?: number;
|
|
2251
2871
|
/** Issued-at timestamp (Unix seconds). Populated automatically by `@nestjs/jwt`. */
|
|
2252
2872
|
iat: number;
|
|
2253
2873
|
/** Expiration timestamp (Unix seconds). Populated automatically by `@nestjs/jwt`. */
|
|
2254
2874
|
exp: number;
|
|
2255
2875
|
}
|
|
2256
2876
|
/**
|
|
2257
|
-
* Short-lived JWT payload issued during an MFA challenge
|
|
2877
|
+
* Short-lived JWT payload issued during an MFA challenge.
|
|
2258
2878
|
*
|
|
2259
2879
|
* This token grants no resource access on its own. It is exchanged for a full
|
|
2260
2880
|
* {@link DashboardJwtPayload} or {@link PlatformJwtPayload} token once the user
|
|
@@ -2278,6 +2898,21 @@ interface MfaTempPayload {
|
|
|
2278
2898
|
type: 'mfa_challenge';
|
|
2279
2899
|
/** Indicates which authentication context triggered the MFA challenge. */
|
|
2280
2900
|
context: 'dashboard' | 'platform';
|
|
2901
|
+
/**
|
|
2902
|
+
* The subject's token **epoch** at issuance, in the plane named by `context`.
|
|
2903
|
+
*
|
|
2904
|
+
* The challenge token is a credential like any other — half of one, held by a caller who has
|
|
2905
|
+
* already proved the password — and it must die with the rest when the account's credentials
|
|
2906
|
+
* are rotated. Without this claim it did not: a password reset bumps the epoch and kills
|
|
2907
|
+
* every access token, but nothing touched an outstanding `mfa:` record, so a challenge token
|
|
2908
|
+
* minted before the reset stayed redeemable for its whole TTL and completing it issued a
|
|
2909
|
+
* full session under the *new* epoch. The reset is meant to end everything.
|
|
2910
|
+
*
|
|
2911
|
+
* Optional for the same reason the access-token epochs are: a token issued before the field
|
|
2912
|
+
* existed carries none, which reads as `0` and is never rejected while the stored epoch is
|
|
2913
|
+
* also `0`, so the mechanism stays inert until the first bump.
|
|
2914
|
+
*/
|
|
2915
|
+
epoch?: number;
|
|
2281
2916
|
/** Issued-at timestamp (Unix seconds). Populated automatically by `@nestjs/jwt`. */
|
|
2282
2917
|
iat: number;
|
|
2283
2918
|
/** Expiration timestamp (Unix seconds). Populated automatically by `@nestjs/jwt`. */
|
|
@@ -2291,6 +2926,8 @@ interface MfaTempPayload {
|
|
|
2291
2926
|
* successful token verification. Controllers and downstream decorators should
|
|
2292
2927
|
* use these types instead of the plain `Request` to get typed access to the
|
|
2293
2928
|
* authenticated identity.
|
|
2929
|
+
*
|
|
2930
|
+
* @layer Interface
|
|
2294
2931
|
*/
|
|
2295
2932
|
|
|
2296
2933
|
/**
|
|
@@ -2335,6 +2972,8 @@ interface PlatformAuthenticatedRequest extends Request {
|
|
|
2335
2972
|
* contract that must be implemented by the consuming application. Platform
|
|
2336
2973
|
* admins are scoped to the operator layer — above tenants — and always have
|
|
2337
2974
|
* a local password credential.
|
|
2975
|
+
*
|
|
2976
|
+
* @layer Interface
|
|
2338
2977
|
*/
|
|
2339
2978
|
/**
|
|
2340
2979
|
* Represents the authenticated record for a platform administrator.
|
|
@@ -2508,7 +3147,9 @@ interface IPlatformUserRepository {
|
|
|
2508
3147
|
*
|
|
2509
3148
|
* Describes the data structures returned by authentication operations across
|
|
2510
3149
|
* the three authentication flows: dashboard users, platform administrators,
|
|
2511
|
-
* and the MFA challenge
|
|
3150
|
+
* and the MFA challenge flow.
|
|
3151
|
+
*
|
|
3152
|
+
* @layer Interface
|
|
2512
3153
|
*/
|
|
2513
3154
|
|
|
2514
3155
|
/**
|
|
@@ -2599,6 +3240,23 @@ interface RotatedTokenResult {
|
|
|
2599
3240
|
*/
|
|
2600
3241
|
rawRefreshToken: string;
|
|
2601
3242
|
}
|
|
3243
|
+
/**
|
|
3244
|
+
* What a **dashboard** refresh returns: the rotated tokens plus the account behind them.
|
|
3245
|
+
*
|
|
3246
|
+
* Rotation itself works entirely from the Redis record, so the repository read this carries is
|
|
3247
|
+
* what lets the status gate apply on refresh at all. Without it a suspended or banned account
|
|
3248
|
+
* renews its access token for the refresh token's whole lifetime — the login door a ban closes
|
|
3249
|
+
* is one a signed-in user never needs to open again (ASVS v5 §7.4.2 requires disabling an
|
|
3250
|
+
* account to terminate its sessions). The user is returned rather than discarded so the caller
|
|
3251
|
+
* does not pay a second read to build the response body.
|
|
3252
|
+
*
|
|
3253
|
+
* The platform plane keeps the plain {@link RotatedTokenResult}: `TokenManagerService` has no
|
|
3254
|
+
* user repository by design, and this shape belongs to the service that does.
|
|
3255
|
+
*/
|
|
3256
|
+
interface DashboardRefreshResult extends RotatedTokenResult {
|
|
3257
|
+
/** The account behind the rotated session, re-read and re-checked during the rotation. */
|
|
3258
|
+
user: SafeAuthUser;
|
|
3259
|
+
}
|
|
2602
3260
|
/**
|
|
2603
3261
|
* Result returned when authentication requires MFA completion.
|
|
2604
3262
|
*
|
|
@@ -2660,8 +3318,13 @@ interface OAuthMfaChallengeResult {
|
|
|
2660
3318
|
* **Never use this provider in production.** Replace it with a concrete
|
|
2661
3319
|
* adapter (e.g. Resend, SendGrid, Nodemailer) that implements `IEmailProvider`.
|
|
2662
3320
|
*
|
|
2663
|
-
* Logged messages include
|
|
2664
|
-
* tokens, OTPs, or passwords.
|
|
3321
|
+
* Logged messages include the method name and a MASKED recipient — never the full address,
|
|
3322
|
+
* and never tokens, OTPs, or passwords.
|
|
3323
|
+
*
|
|
3324
|
+
* The mask matters because this is the DEFAULT provider: a deployment that ships without
|
|
3325
|
+
* wiring `BYMAX_AUTH_EMAIL_PROVIDER` gets it, and it would otherwise write every user's
|
|
3326
|
+
* address to stdout on every reset, verification, MFA notification and invitation — a PII
|
|
3327
|
+
* disclosure to whatever collects the logs, produced by an omission rather than a decision.
|
|
2665
3328
|
*/
|
|
2666
3329
|
declare class NoOpEmailProvider implements IEmailProvider {
|
|
2667
3330
|
private readonly logger;
|
|
@@ -2681,6 +3344,240 @@ declare class NoOpEmailProvider implements IEmailProvider {
|
|
|
2681
3344
|
sendInvitation(email: string, _inviteData: InviteData, _locale?: string): Promise<void>;
|
|
2682
3345
|
}
|
|
2683
3346
|
|
|
3347
|
+
/**
|
|
3348
|
+
* @fileoverview Contract for checking a password against a breach corpus.
|
|
3349
|
+
*
|
|
3350
|
+
* @layer Interface
|
|
3351
|
+
*/
|
|
3352
|
+
/**
|
|
3353
|
+
* Decides whether a password appears in a known-breach corpus.
|
|
3354
|
+
*
|
|
3355
|
+
* @remarks
|
|
3356
|
+
* Supply an implementation via the `BYMAX_AUTH_BREACH_CHECKER` token. The module registers
|
|
3357
|
+
* {@link AllowAllBreachChecker} when none is supplied, which approves every password — the
|
|
3358
|
+
* check is opt-in, because it is the only part of the credential path that can reach the
|
|
3359
|
+
* network and that is a decision a deployment has to make deliberately.
|
|
3360
|
+
*
|
|
3361
|
+
* A shipped implementation, `HibpBreachChecker`, queries Have I Been Pwned with the
|
|
3362
|
+
* k-anonymity range API.
|
|
3363
|
+
*
|
|
3364
|
+
* **Two rules an implementation must honor.** It must never transmit the password (the point
|
|
3365
|
+
* of a range query is that the corpus is searched with a prefix), and it must **fail open** —
|
|
3366
|
+
* a corpus that is unreachable, slow, or rate-limiting cannot be allowed to stop a user
|
|
3367
|
+
* changing their password, least of all during an incident when changing it is urgent.
|
|
3368
|
+
*
|
|
3369
|
+
* @example
|
|
3370
|
+
* ```typescript
|
|
3371
|
+
* class LocalListChecker implements IPasswordBreachChecker {
|
|
3372
|
+
* async isBreached(password: string): Promise<boolean> {
|
|
3373
|
+
* return TOP_100K.has(password)
|
|
3374
|
+
* }
|
|
3375
|
+
* }
|
|
3376
|
+
* ```
|
|
3377
|
+
*
|
|
3378
|
+
* @layer Interface
|
|
3379
|
+
*/
|
|
3380
|
+
interface IPasswordBreachChecker {
|
|
3381
|
+
/**
|
|
3382
|
+
* Whether the password is known to have been breached.
|
|
3383
|
+
*
|
|
3384
|
+
* @param password - The plaintext password the user is trying to set.
|
|
3385
|
+
* @returns `true` when the password appears in the corpus. Return `false` — never throw —
|
|
3386
|
+
* when the corpus cannot be consulted.
|
|
3387
|
+
*/
|
|
3388
|
+
isBreached(password: string): Promise<boolean>;
|
|
3389
|
+
}
|
|
3390
|
+
|
|
3391
|
+
/**
|
|
3392
|
+
* Reduces a password to the base word its author started from.
|
|
3393
|
+
*
|
|
3394
|
+
* Lowercases, strips the trailing digits and punctuation people append to satisfy a complexity
|
|
3395
|
+
* rule, maps leet substitutions back to letters, and drops what is left that is not
|
|
3396
|
+
* alphanumeric. `P@ssw0rd!`, `Password123`, and `password` all reduce to `password`, which is
|
|
3397
|
+
* why a few hundred bases stand in for a list many times longer.
|
|
3398
|
+
*
|
|
3399
|
+
* Exported for testing and for a consumer who wants to normalise their own blocklist the same
|
|
3400
|
+
* way before handing it to the checker.
|
|
3401
|
+
*
|
|
3402
|
+
* @param password - The raw candidate.
|
|
3403
|
+
* @returns The reduced base form, possibly empty.
|
|
3404
|
+
*/
|
|
3405
|
+
declare function reduceToBaseWord(password: string): string;
|
|
3406
|
+
/**
|
|
3407
|
+
* The default password checker: refuses passwords that are common, structural, or trivially
|
|
3408
|
+
* decorated versions of either — offline, with no network call.
|
|
3409
|
+
*
|
|
3410
|
+
* NIST SP 800-63B §3.1.1.2 states that a verifier **SHALL** compare a prospective secret
|
|
3411
|
+
* against a blocklist of commonly used, expected, or compromised values, and ASVS v5 §6.2.4
|
|
3412
|
+
* asks for it at Level 1 — the baseline every application needs. The library used to ship
|
|
3413
|
+
* {@link AllowAllBreachChecker} as its default, which approved everything: a deployment on
|
|
3414
|
+
* defaults accepted `password1` and `12345678`, and the brute-force machinery never fired
|
|
3415
|
+
* because a spraying campaign that guesses one password across ten thousand accounts never
|
|
3416
|
+
* crosses any single account's threshold.
|
|
3417
|
+
*
|
|
3418
|
+
* **What this is and is not.** It is a floor, not a corpus. It refuses the base words behind
|
|
3419
|
+
* the bulk of real-world weak passwords, keyboard walks, single-character repeats, sequential
|
|
3420
|
+
* runs, and any decorated form of those — but it is not the full top-3000, and it knows
|
|
3421
|
+
* nothing about breach corpora. A deployment that wants that should either extend it through
|
|
3422
|
+
* `password.blocklist` or supply {@link HibpBreachChecker}, which checks a real breach corpus
|
|
3423
|
+
* over the network. This checker being the default is what makes the *baseline* honest; the
|
|
3424
|
+
* network check remains opt-in, because a library should not start talking to a third party
|
|
3425
|
+
* because it was upgraded.
|
|
3426
|
+
*
|
|
3427
|
+
* @layer Provider
|
|
3428
|
+
*/
|
|
3429
|
+
declare class CommonPasswordChecker implements IPasswordBreachChecker {
|
|
3430
|
+
/** The shipped bases plus whatever `password.blocklist` added, all pre-normalised. */
|
|
3431
|
+
private readonly blocked;
|
|
3432
|
+
constructor(options?: ResolvedOptions);
|
|
3433
|
+
/** @inheritdoc */
|
|
3434
|
+
isBreached(password: string): Promise<boolean>;
|
|
3435
|
+
}
|
|
3436
|
+
|
|
3437
|
+
/**
|
|
3438
|
+
* Checks a password against Have I Been Pwned without ever sending it.
|
|
3439
|
+
*
|
|
3440
|
+
* @remarks
|
|
3441
|
+
* The protocol is k-anonymity: the password is SHA-1'd locally, the **first five** hex
|
|
3442
|
+
* characters of the digest are sent, and the service answers with every suffix it holds under
|
|
3443
|
+
* that prefix — some hundreds of them. The comparison happens here. The service learns a
|
|
3444
|
+
* prefix shared by thousands of distinct passwords and nothing else.
|
|
3445
|
+
*
|
|
3446
|
+
* SHA-1 is not a security choice here and is not used as one: it is the corpus's index. The
|
|
3447
|
+
* password is still hashed for storage with scrypt.
|
|
3448
|
+
*
|
|
3449
|
+
* **Fails open, deliberately.** A timeout, a network error, a rate limit or a malformed
|
|
3450
|
+
* response all approve the password. The alternative is an outage in a third-party service
|
|
3451
|
+
* blocking password changes — including the password change someone is making *because* they
|
|
3452
|
+
* were breached. A breach check is a hardening measure; it is not an authorization decision,
|
|
3453
|
+
* and it must not become a dependency of the credential path.
|
|
3454
|
+
*
|
|
3455
|
+
* @example
|
|
3456
|
+
* ```typescript
|
|
3457
|
+
* BymaxAuthModule.registerAsync({
|
|
3458
|
+
* useFactory: () => ({ ... }),
|
|
3459
|
+
* extraProviders: [{ provide: BYMAX_AUTH_BREACH_CHECKER, useClass: HibpBreachChecker }]
|
|
3460
|
+
* })
|
|
3461
|
+
* ```
|
|
3462
|
+
*
|
|
3463
|
+
* @layer Provider
|
|
3464
|
+
*/
|
|
3465
|
+
declare class HibpBreachChecker implements IPasswordBreachChecker {
|
|
3466
|
+
private readonly timeoutMs;
|
|
3467
|
+
private readonly logger;
|
|
3468
|
+
/**
|
|
3469
|
+
* @param timeoutMs - How long to wait for the range response before approving the password.
|
|
3470
|
+
* Defaults to 1500 ms — long enough for a healthy round trip, short enough that a
|
|
3471
|
+
* degraded service does not become a visible delay on every registration.
|
|
3472
|
+
*/
|
|
3473
|
+
constructor(timeoutMs?: number);
|
|
3474
|
+
/** @inheritdoc */
|
|
3475
|
+
isBreached(password: string): Promise<boolean>;
|
|
3476
|
+
/**
|
|
3477
|
+
* Fetch the suffix list for a prefix, or `null` when the service could not be consulted.
|
|
3478
|
+
*
|
|
3479
|
+
* @param prefix - The first five hex characters of the SHA-1 digest.
|
|
3480
|
+
* @returns The response body, or `null` on any failure — which approves the password.
|
|
3481
|
+
*/
|
|
3482
|
+
private fetchRange;
|
|
3483
|
+
}
|
|
3484
|
+
/**
|
|
3485
|
+
* A breach checker that approves every password.
|
|
3486
|
+
*
|
|
3487
|
+
* @remarks
|
|
3488
|
+
* **No longer the default** — `CommonPasswordChecker` is. Approving everything meant a
|
|
3489
|
+
* deployment on defaults accepted `password1` and `12345678`, which NIST SP 800-63B §3.1.1.2
|
|
3490
|
+
* states a verifier SHALL refuse and ASVS v5 §6.2.4 asks for at Level 1. It stays exported for
|
|
3491
|
+
* the deployment that has a deliberate reason to screen nothing — a migration importing legacy
|
|
3492
|
+
* accounts, a test fixture — and has to say so explicitly rather than getting it by default.
|
|
3493
|
+
*
|
|
3494
|
+
* @layer Provider
|
|
3495
|
+
*/
|
|
3496
|
+
declare class AllowAllBreachChecker implements IPasswordBreachChecker {
|
|
3497
|
+
/** @inheritdoc */
|
|
3498
|
+
isBreached(_password: string): Promise<boolean>;
|
|
3499
|
+
}
|
|
3500
|
+
|
|
3501
|
+
/**
|
|
3502
|
+
* @fileoverview The verified-identity snapshot bound to a WebSocket upgrade ticket.
|
|
3503
|
+
*
|
|
3504
|
+
* @layer Interface
|
|
3505
|
+
*/
|
|
3506
|
+
/**
|
|
3507
|
+
* Lifetime of a WebSocket upgrade ticket, in seconds.
|
|
3508
|
+
*
|
|
3509
|
+
* Short on purpose: the ticket only has to survive the round trip between the mint call and
|
|
3510
|
+
* the browser opening the socket. Anything longer widens the window in which a ticket captured
|
|
3511
|
+
* from a URL — the one place it is unavoidably visible — is still worth replaying.
|
|
3512
|
+
*
|
|
3513
|
+
* rust-auth pins the identical value (`WS_TICKET_TTL_SECONDS`), so a ticket minted by one
|
|
3514
|
+
* backend and redeemed by the other over a shared Redis has the same lifetime either way.
|
|
3515
|
+
*/
|
|
3516
|
+
declare const WS_TICKET_TTL_SECONDS = 30;
|
|
3517
|
+
/**
|
|
3518
|
+
* The identity a redeemed ticket authorizes a socket as.
|
|
3519
|
+
*
|
|
3520
|
+
* A snapshot, never a token: it is what the access JWT already proved at mint time, frozen for
|
|
3521
|
+
* the socket's lifetime. It carries no signature, no expiry of its own, and nothing that can be
|
|
3522
|
+
* presented back to the REST surface — a leaked snapshot buys an attacker a socket, not a
|
|
3523
|
+
* session.
|
|
3524
|
+
*
|
|
3525
|
+
* The field names are the wire contract shared with rust-auth
|
|
3526
|
+
* (`conformance/wire-contract.json`, `recordEncodings.wsTicket`): both backends read each
|
|
3527
|
+
* other's tickets over one Redis.
|
|
3528
|
+
*/
|
|
3529
|
+
interface WsTicketSnapshot {
|
|
3530
|
+
/** The subject — the internal user id. */
|
|
3531
|
+
sub: string;
|
|
3532
|
+
/** The tenant scope. Absent for a platform ticket. */
|
|
3533
|
+
tenantId?: string;
|
|
3534
|
+
/** The user's role at mint time. */
|
|
3535
|
+
role: string;
|
|
3536
|
+
/** The account status at mint time. */
|
|
3537
|
+
status: string;
|
|
3538
|
+
/** Whether MFA is enabled on the account. */
|
|
3539
|
+
mfaEnabled: boolean;
|
|
3540
|
+
/** Whether the originating session had already satisfied MFA. */
|
|
3541
|
+
mfaVerified: boolean;
|
|
3542
|
+
}
|
|
3543
|
+
|
|
3544
|
+
/** The rotation bundle {@link AuthRedisService.rotateRefreshSession} consumes. */
|
|
3545
|
+
interface RefreshRotationParams {
|
|
3546
|
+
/** Which identity plane is rotating; selects the whole prefix set. */
|
|
3547
|
+
kind: 'dashboard' | 'platform';
|
|
3548
|
+
/** SHA-256 of the presented (old) refresh token. */
|
|
3549
|
+
oldHash: string;
|
|
3550
|
+
/** SHA-256 of the freshly minted refresh token. */
|
|
3551
|
+
newHash: string;
|
|
3552
|
+
/** Serialized session record to store under the new hash. */
|
|
3553
|
+
newSessionJson: string;
|
|
3554
|
+
/** Family of the presented session; `''` when it belongs to no lineage. */
|
|
3555
|
+
familyId: string;
|
|
3556
|
+
/**
|
|
3557
|
+
* Owner of the session being rotated, for the per-user session index the script now
|
|
3558
|
+
* maintains itself. Taken from the record the caller pre-read, which is what makes it the
|
|
3559
|
+
* real owner: the script touches this index only on the live-rotation path, and that path
|
|
3560
|
+
* is unreachable unless that pre-read found the session.
|
|
3561
|
+
*/
|
|
3562
|
+
userId: string;
|
|
3563
|
+
/** Refresh-session lifetime in seconds. */
|
|
3564
|
+
refreshTtl: number;
|
|
3565
|
+
/** Grace-pointer lifetime in seconds; `0` writes no pointer. */
|
|
3566
|
+
graceTtl: number;
|
|
3567
|
+
}
|
|
3568
|
+
/** What {@link AuthRedisService.rotateRefreshSession} found for the presented token. */
|
|
3569
|
+
type RefreshRotationOutcome = {
|
|
3570
|
+
kind: 'rotated';
|
|
3571
|
+
sessionJson: string;
|
|
3572
|
+
} | {
|
|
3573
|
+
kind: 'grace';
|
|
3574
|
+
sessionJson: string;
|
|
3575
|
+
} | {
|
|
3576
|
+
kind: 'reused';
|
|
3577
|
+
familyId: string;
|
|
3578
|
+
} | {
|
|
3579
|
+
kind: 'invalid';
|
|
3580
|
+
};
|
|
2684
3581
|
/**
|
|
2685
3582
|
* Internal Redis service for @bymax-one/nest-auth.
|
|
2686
3583
|
*
|
|
@@ -2694,13 +3591,14 @@ declare class NoOpEmailProvider implements IEmailProvider {
|
|
|
2694
3591
|
* higher-level services (BruteForceService, TokenManagerService, etc.).
|
|
2695
3592
|
*
|
|
2696
3593
|
* The namespace is taken from `ResolvedOptions.redisNamespace` (defaults to
|
|
2697
|
-
* `'
|
|
3594
|
+
* `'auth'`). Example key with namespace `'auth'` and key `'rt:abc'`:
|
|
2698
3595
|
* → `'auth:rt:abc'`
|
|
2699
3596
|
*/
|
|
2700
3597
|
declare class AuthRedisService {
|
|
2701
|
-
private
|
|
3598
|
+
#private;
|
|
2702
3599
|
private readonly namespace;
|
|
2703
3600
|
constructor(redis: Redis, options: ResolvedOptions);
|
|
3601
|
+
/** Returns the fully-qualified Redis key by prepending the configured namespace prefix. */
|
|
2704
3602
|
private prefix;
|
|
2705
3603
|
/**
|
|
2706
3604
|
* Gets the string value for a key.
|
|
@@ -2722,7 +3620,7 @@ declare class AuthRedisService {
|
|
|
2722
3620
|
*
|
|
2723
3621
|
* @param key - Application key (namespace prefix is applied automatically).
|
|
2724
3622
|
*/
|
|
2725
|
-
del(key: string): Promise<
|
|
3623
|
+
del(key: string): Promise<boolean>;
|
|
2726
3624
|
/**
|
|
2727
3625
|
* Atomically sets a key with an expiry only if the key does not already exist.
|
|
2728
3626
|
*
|
|
@@ -2805,6 +3703,101 @@ declare class AuthRedisService {
|
|
|
2805
3703
|
* at the call site. Use a type assertion or runtime check after calling this method.
|
|
2806
3704
|
*/
|
|
2807
3705
|
eval(script: string, keys: string[], args: string[]): Promise<unknown>;
|
|
3706
|
+
/**
|
|
3707
|
+
* Atomically rotates a refresh session, plants the reuse-detection bookkeeping, and
|
|
3708
|
+
* reports what the presented token actually was.
|
|
3709
|
+
*
|
|
3710
|
+
* Byte-identical in behaviour to rust-auth's `refresh_rotate.lua`, so both backends can
|
|
3711
|
+
* drive the same Redis. In one round trip it:
|
|
3712
|
+
*
|
|
3713
|
+
* - consumes the live session (`GET` + `DEL`) and writes the new one,
|
|
3714
|
+
* - writes the rotation grace pointer, unless the grace window is zero,
|
|
3715
|
+
* - plants the consumed-family marker `cf:{oldHash}` and moves the family membership
|
|
3716
|
+
* from the old hash to the new one.
|
|
3717
|
+
*
|
|
3718
|
+
* Writes happen **before** the old key is deleted. Redis does not roll back a script's
|
|
3719
|
+
* earlier writes, so a failing write aborts the script with the old token still intact —
|
|
3720
|
+
* the old token is never consumed without the new session being persisted and the
|
|
3721
|
+
* consumed marker planted, which is what makes reuse detection crash-safe.
|
|
3722
|
+
*
|
|
3723
|
+
* @param params - The rotation bundle; see {@link RefreshRotationParams}.
|
|
3724
|
+
* @returns What the presented token was: a live session (`rotated`), a replay inside the
|
|
3725
|
+
* grace window (`grace`), a replay of a consumed token past its grace window
|
|
3726
|
+
* (`reused`, carrying the compromised family), or never-issued (`invalid`).
|
|
3727
|
+
*/
|
|
3728
|
+
rotateRefreshSession(params: RefreshRotationParams): Promise<RefreshRotationOutcome>;
|
|
3729
|
+
/**
|
|
3730
|
+
* Writes the session a grace recovery produced, atomically with the check that the account
|
|
3731
|
+
* has not been swept out from under it.
|
|
3732
|
+
*
|
|
3733
|
+
* See {@link RECOVER_GRACE_LUA} for what this closes and why the per-user session index is
|
|
3734
|
+
* the right witness.
|
|
3735
|
+
*
|
|
3736
|
+
* @param params - The same bundle a rotation takes, minus the pointer fields the grace arm
|
|
3737
|
+
* has already consumed.
|
|
3738
|
+
* @returns `true` when the session was written; `false` when a revoke-all or a family
|
|
3739
|
+
* revocation had already run, in which case the caller must refuse the rotation.
|
|
3740
|
+
*/
|
|
3741
|
+
writeRecoveredSession(params: {
|
|
3742
|
+
kind: 'dashboard' | 'platform';
|
|
3743
|
+
newHash: string;
|
|
3744
|
+
newSessionJson: string;
|
|
3745
|
+
familyId: string;
|
|
3746
|
+
userId: string;
|
|
3747
|
+
refreshTtl: number;
|
|
3748
|
+
}): Promise<boolean>;
|
|
3749
|
+
/**
|
|
3750
|
+
* Whether the lineage a recovered grace record belongs to is still alive.
|
|
3751
|
+
*
|
|
3752
|
+
* A grace pointer can outlive its own lineage: reuse detection revokes the family's live
|
|
3753
|
+
* sessions, but a pointer planted by an *earlier* rotation of that same lineage can still be
|
|
3754
|
+
* inside its (much shorter) window at that moment — detection only proves the replayed
|
|
3755
|
+
* token's own pointer expired, which says nothing about a younger sibling's. Recovering from
|
|
3756
|
+
* such a pointer would mint a fresh session carrying the revoked family id and hand the thief
|
|
3757
|
+
* back the lineage the revocation just killed.
|
|
3758
|
+
*
|
|
3759
|
+
* A record written before families existed carries none and recovers as before.
|
|
3760
|
+
*
|
|
3761
|
+
* @param sessionJson - The record the grace pointer held.
|
|
3762
|
+
* @param familyPrefix - The family-index prefix for the plane being rotated.
|
|
3763
|
+
* @returns `false` only when the record names a family whose index is gone.
|
|
3764
|
+
*/
|
|
3765
|
+
private familyIsAlive;
|
|
3766
|
+
/**
|
|
3767
|
+
* Revokes every live session in one refresh-token family, in a single transaction.
|
|
3768
|
+
*
|
|
3769
|
+
* Called on reuse detection: the whole lineage descending from the compromised login is
|
|
3770
|
+
* deleted, forcing each holder to re-authenticate. This is deliberately narrower than
|
|
3771
|
+
* {@link invalidateUserSessions} — the OWASP-recommended behaviour is to kill the stolen
|
|
3772
|
+
* token's chain, not to log the user's other legitimate devices out.
|
|
3773
|
+
*
|
|
3774
|
+
* Idempotent: an empty, unknown, or already-cleared family is a no-op.
|
|
3775
|
+
*
|
|
3776
|
+
* @param familyId - The family id carried by the consumed-token marker.
|
|
3777
|
+
* @param kind - Which identity plane the family belongs to. Defaults to `'dashboard'`.
|
|
3778
|
+
* @returns The number of members removed and the account the family belonged to. The owner
|
|
3779
|
+
* is reported because the caller cannot obtain it any other way: the presented token's own
|
|
3780
|
+
* `rt:` key was deleted when it was rotated, so at reuse-detection time the family index is
|
|
3781
|
+
* the only surviving link between the replayed token and an account. It is `''` when no
|
|
3782
|
+
* member record was readable.
|
|
3783
|
+
*/
|
|
3784
|
+
revokeFamily(familyId: string, kind?: 'dashboard' | 'platform'): Promise<{
|
|
3785
|
+
removed: number;
|
|
3786
|
+
ownerId: string;
|
|
3787
|
+
}>;
|
|
3788
|
+
/**
|
|
3789
|
+
* Resolves the id of the user a family belongs to.
|
|
3790
|
+
*
|
|
3791
|
+
* Every member of one family descends from the same login, so the first readable record
|
|
3792
|
+
* names the owner. Reading it here rather than decoding JSON inside the revocation script
|
|
3793
|
+
* keeps the script free of `cjson` and uses a real parser on the stored record.
|
|
3794
|
+
*
|
|
3795
|
+
* @param members - The family index members (bare session hashes).
|
|
3796
|
+
* @param livePrefix - The live-session prefix for the plane (`rt` or `prt`).
|
|
3797
|
+
* @returns The owner's id, or `''` when no member record is readable — every member may have
|
|
3798
|
+
* already expired, in which case there is nothing left to prune and nobody left to name.
|
|
3799
|
+
*/
|
|
3800
|
+
private readFamilyOwner;
|
|
2808
3801
|
/**
|
|
2809
3802
|
* Atomically gets a key's value and deletes it in a single operation.
|
|
2810
3803
|
*
|
|
@@ -2831,17 +3824,38 @@ declare class AuthRedisService {
|
|
|
2831
3824
|
*/
|
|
2832
3825
|
setIfAbsent(key: string, value: string, ttl: number): Promise<boolean>;
|
|
2833
3826
|
/**
|
|
2834
|
-
* Atomically deletes
|
|
3827
|
+
* Atomically deletes every refresh session belonging to one identity plane.
|
|
3828
|
+
*
|
|
3829
|
+
* The set members are full key suffixes — `rt:{hash}`/`rp:{hash}` on the dashboard plane,
|
|
3830
|
+
* `prt:{hash}`/`prp:{hash}` on the platform plane — so a member names the key to delete
|
|
3831
|
+
* outright. Grace pointers are members too, which is what lets a revoke-all also kill a
|
|
3832
|
+
* refresh token that was rotated away but is still inside its grace window.
|
|
3833
|
+
*
|
|
3834
|
+
* Only members carrying one of the two supplied prefixes are touched. That filter is the
|
|
3835
|
+
* point: a dashboard user id and a platform admin id come from different repositories and
|
|
3836
|
+
* may legitimately collide, and an unfiltered sweep would let revoking one plane log the
|
|
3837
|
+
* other out. Members that do not match are left in place, and the SET itself is deleted
|
|
3838
|
+
* only once it is empty.
|
|
3839
|
+
*
|
|
3840
|
+
* The whole sweep is one Lua transaction, closing the race where a concurrent login adds a
|
|
3841
|
+
* session between the SMEMBERS read and the delete.
|
|
3842
|
+
*
|
|
3843
|
+
* @param setKey - The un-namespaced index key (`sess:{id}` or `psess:{id}`).
|
|
3844
|
+
* @param livePrefix - Member prefix for live sessions (`rt:` or `prt:`).
|
|
3845
|
+
* @param gracePrefix - Member prefix for rotation grace pointers (`rp:` or `prp:`).
|
|
3846
|
+
* @param detailPrefix - Key prefix for the per-session detail record (`sd:` or `psd:`).
|
|
3847
|
+
*/
|
|
3848
|
+
private sweepSessionIndex;
|
|
3849
|
+
/**
|
|
3850
|
+
* Atomically deletes all refresh sessions for a user on the given identity plane.
|
|
2835
3851
|
*
|
|
2836
|
-
*
|
|
2837
|
-
*
|
|
2838
|
-
* Deletes each corresponding namespaced key and then removes the SET itself —
|
|
2839
|
-
* all in a single Lua transaction to prevent the race where a concurrent login
|
|
2840
|
-
* could add a new session between the SMEMBERS read and the final DEL.
|
|
3852
|
+
* Each plane sweeps only its own index — `sess:` for dashboard, `psess:` for platform — so
|
|
3853
|
+
* an admin and a user who happen to share an id never revoke each other's sessions.
|
|
2841
3854
|
*
|
|
2842
|
-
* @param userId - Internal user ID whose sessions will be invalidated.
|
|
3855
|
+
* @param userId - Internal user or admin ID whose sessions will be invalidated.
|
|
3856
|
+
* @param kind - Which identity plane to revoke. Defaults to `'dashboard'`.
|
|
2843
3857
|
*/
|
|
2844
|
-
invalidateUserSessions(userId: string): Promise<void>;
|
|
3858
|
+
invalidateUserSessions(userId: string, kind?: 'dashboard' | 'platform'): Promise<void>;
|
|
2845
3859
|
/**
|
|
2846
3860
|
* Atomically increments a counter and sets a fixed TTL on the **first** increment.
|
|
2847
3861
|
*
|
|
@@ -2856,6 +3870,84 @@ declare class AuthRedisService {
|
|
|
2856
3870
|
* @returns The value of the counter after incrementing.
|
|
2857
3871
|
*/
|
|
2858
3872
|
incrWithFixedTtl(key: string, ttl: number): Promise<number>;
|
|
3873
|
+
/**
|
|
3874
|
+
* Reads the user's token **epoch** — a per-user generation counter — defaulting to `0`.
|
|
3875
|
+
*
|
|
3876
|
+
* Access tokens are stateless JWTs: the server does not track their individual `jti`s and
|
|
3877
|
+
* cannot enumerate them on a bulk event such as a password reset. Instead every token is
|
|
3878
|
+
* stamped with the epoch current at issuance, and a token stamped below the stored epoch is
|
|
3879
|
+
* rejected — one write invalidates every outstanding token for that user.
|
|
3880
|
+
*
|
|
3881
|
+
* The counter replaced an `iat < cutoff` timestamp comparison, which could not separate a
|
|
3882
|
+
* token issued in the same second as the reset from one issued just before it, and depended
|
|
3883
|
+
* on the token carrying a well-formed `iat` at all.
|
|
3884
|
+
*
|
|
3885
|
+
* This is a plain read: it never creates the key, so only a user who has actually been
|
|
3886
|
+
* bumped carries one.
|
|
3887
|
+
*
|
|
3888
|
+
* @param userId - Internal user or admin ID to look up.
|
|
3889
|
+
* @param kind - Which identity plane to read. Defaults to `'dashboard'`.
|
|
3890
|
+
* @returns The stored epoch, or `0` when none is stored or the value is unreadable.
|
|
3891
|
+
*/
|
|
3892
|
+
getUserTokenEpoch(userId: string, kind?: 'dashboard' | 'platform'): Promise<number>;
|
|
3893
|
+
/**
|
|
3894
|
+
* Reads the owner recorded on a stored refresh session, or `''` when there is none.
|
|
3895
|
+
*
|
|
3896
|
+
* Logout uses this instead of the access token's `sub`: presenting the refresh token proves
|
|
3897
|
+
* possession, and the stored record proves whose session it is. An access token's claims
|
|
3898
|
+
* cannot serve that purpose when the token is allowed to be absent or expired — and taking
|
|
3899
|
+
* the owner from an unverified token would let a caller aim the revocation at someone else.
|
|
3900
|
+
*
|
|
3901
|
+
* A record that is missing, unparseable, or carries no string `userId` answers `''`: there
|
|
3902
|
+
* is nothing to attribute the logout to, which the caller treats as "no live session".
|
|
3903
|
+
*
|
|
3904
|
+
* @param key - The un-namespaced session key (`rt:{hash}` or `prt:{hash}`).
|
|
3905
|
+
* @returns The recorded user id, or `''`.
|
|
3906
|
+
*/
|
|
3907
|
+
readSessionOwner(key: string): Promise<string>;
|
|
3908
|
+
/**
|
|
3909
|
+
* Atomically advances the user's token epoch and returns the new value, invalidating every
|
|
3910
|
+
* outstanding access token for that user at once.
|
|
3911
|
+
*
|
|
3912
|
+
* The TTL is re-applied on every bump and is deliberately far longer than any access token
|
|
3913
|
+
* lives, so a bump stays in force for the whole window a pre-bump token could still be
|
|
3914
|
+
* presented. Once it lapses the counter restarts at zero, which is safe *because* the window
|
|
3915
|
+
* runs from the latest bump: by then every token stamped below it has expired anyway.
|
|
3916
|
+
*
|
|
3917
|
+
* @param userId - Internal user or admin ID whose outstanding access tokens are revoked.
|
|
3918
|
+
* @param kind - Which identity plane to bump. Defaults to `'dashboard'`.
|
|
3919
|
+
* @returns The epoch after the increment.
|
|
3920
|
+
*/
|
|
3921
|
+
bumpUserTokenEpoch(userId: string, kind?: 'dashboard' | 'platform'): Promise<number>;
|
|
3922
|
+
/**
|
|
3923
|
+
* Mints a single-use WebSocket upgrade ticket holding a verified-identity snapshot.
|
|
3924
|
+
*
|
|
3925
|
+
* The browser `WebSocket` API cannot set handshake headers, which leaves a browser client
|
|
3926
|
+
* with no way to present an `Authorization` header at the upgrade. The alternative most
|
|
3927
|
+
* codebases reach for — the access token in the query string — puts a long-lived credential
|
|
3928
|
+
* into access logs, browser history and proxy caches. This is the other answer: an opaque,
|
|
3929
|
+
* ~30-second, single-use ticket that is worthless the moment it is redeemed.
|
|
3930
|
+
*
|
|
3931
|
+
* Only `sha256(ticket)` becomes a key, so a Redis dump never yields a usable ticket, and the
|
|
3932
|
+
* access token is never echoed into the value — the snapshot carries the identity the socket
|
|
3933
|
+
* is authorized as, nothing that could be replayed against the REST surface.
|
|
3934
|
+
*
|
|
3935
|
+
* @param snapshot - The verified-identity snapshot to bind to the ticket.
|
|
3936
|
+
* @param ttlSeconds - Lifetime of the ticket in seconds.
|
|
3937
|
+
* @returns The raw ticket to hand to the client — never persisted in this form.
|
|
3938
|
+
*/
|
|
3939
|
+
mintWsTicket(snapshot: WsTicketSnapshot, ttlSeconds: number): Promise<string>;
|
|
3940
|
+
/**
|
|
3941
|
+
* Redeems a WebSocket upgrade ticket, consuming it in the same round trip.
|
|
3942
|
+
*
|
|
3943
|
+
* `GETDEL` is what makes the ticket single-use: the first redemption wins, and a second
|
|
3944
|
+
* presentation of a captured upgrade URL finds nothing. A ticket that is unknown, expired or
|
|
3945
|
+
* already redeemed is indistinguishable here by design — all three return `null`.
|
|
3946
|
+
*
|
|
3947
|
+
* @param ticket - The raw ticket presented at the handshake.
|
|
3948
|
+
* @returns The bound snapshot, or `null` when the ticket cannot be redeemed.
|
|
3949
|
+
*/
|
|
3950
|
+
redeemWsTicket(ticket: string): Promise<WsTicketSnapshot | null>;
|
|
2859
3951
|
}
|
|
2860
3952
|
|
|
2861
3953
|
/**
|
|
@@ -2906,6 +3998,8 @@ interface PlatformBearerAuthResponse {
|
|
|
2906
3998
|
*
|
|
2907
3999
|
* Cookie security: HttpOnly, Secure (production), SameSite=Strict.
|
|
2908
4000
|
* Refresh cookies use the configured `cookies.refreshCookiePath`.
|
|
4001
|
+
*
|
|
4002
|
+
* @layer Service
|
|
2909
4003
|
*/
|
|
2910
4004
|
declare class TokenDeliveryService {
|
|
2911
4005
|
private readonly options;
|
|
@@ -3003,9 +4097,13 @@ declare class TokenDeliveryService {
|
|
|
3003
4097
|
/**
|
|
3004
4098
|
* Resolves cookie domains for the current request.
|
|
3005
4099
|
*
|
|
3006
|
-
*
|
|
3007
|
-
*
|
|
3008
|
-
*
|
|
4100
|
+
* With no `cookies.resolveDomains` configured the answer is empty, and an empty answer means
|
|
4101
|
+
* **no `Domain` attribute** — a host-only cookie, which is what a session cookie should be.
|
|
4102
|
+
* A cookie that carries `Domain=app.example.com` is sent to every subdomain of that name
|
|
4103
|
+
* (RFC 6265 §5.2.3), so deriving the attribute from the request host would silently hand the
|
|
4104
|
+
* session to a marketing site, a user-content host, or a stale DNS record that someone else
|
|
4105
|
+
* now answers for. Sharing across subdomains is a deliberate deployment decision, and
|
|
4106
|
+
* `resolveDomains` is where it is made; `rust-auth` is host-only for the same reason.
|
|
3009
4107
|
*
|
|
3010
4108
|
* @param req - Incoming request (may be undefined in non-HTTP contexts).
|
|
3011
4109
|
* @returns Array of domain strings for cookie attributes. Empty array means
|
|
@@ -3024,16 +4122,13 @@ declare class TokenDeliveryService {
|
|
|
3024
4122
|
*/
|
|
3025
4123
|
extractDomain(req: Request): string | undefined;
|
|
3026
4124
|
private setAuthCookies;
|
|
3027
|
-
/**
|
|
3028
|
-
* Returns the shared cookie attributes applied to every cookie issued by
|
|
3029
|
-
* this service. `sameSite` comes from the resolved options (defaults to
|
|
3030
|
-
* `'lax'`); the `domain` is folded in only when the consumer supplies a
|
|
3031
|
-
* resolver. Other per-cookie attributes (`httpOnly`, `secure`, `path`,
|
|
3032
|
-
* `maxAge`) are spread on top of this base by the callers.
|
|
3033
|
-
*/
|
|
4125
|
+
/** Returns base Set-Cookie options for auth cookies, optionally scoped to a domain. */
|
|
3034
4126
|
private baseCookieOptions;
|
|
4127
|
+
/** Reads the value of the cookie identified by `name` from the request. */
|
|
3035
4128
|
private readCookie;
|
|
4129
|
+
/** Reads the access token from the Authorization Bearer header. */
|
|
3036
4130
|
private readBearerHeader;
|
|
4131
|
+
/** Reads the refresh token from the request body field. */
|
|
3037
4132
|
private readBodyRefresh;
|
|
3038
4133
|
}
|
|
3039
4134
|
|
|
@@ -3057,6 +4152,8 @@ declare class TokenDeliveryService {
|
|
|
3057
4152
|
* @Get('/profile')
|
|
3058
4153
|
* profile(@CurrentUser() user: DashboardJwtPayload) { ... }
|
|
3059
4154
|
* ```
|
|
4155
|
+
*
|
|
4156
|
+
* @layer Guard
|
|
3060
4157
|
*/
|
|
3061
4158
|
declare class JwtAuthGuard implements CanActivate {
|
|
3062
4159
|
protected readonly jwtService: JwtService;
|
|
@@ -3093,6 +4190,8 @@ declare class JwtAuthGuard implements CanActivate {
|
|
|
3093
4190
|
* @Get('/platform/tenants')
|
|
3094
4191
|
* listTenants(@CurrentUser() admin: PlatformJwtPayload) { ... }
|
|
3095
4192
|
* ```
|
|
4193
|
+
*
|
|
4194
|
+
* @layer Guard
|
|
3096
4195
|
*/
|
|
3097
4196
|
declare class JwtPlatformGuard implements CanActivate {
|
|
3098
4197
|
private readonly jwtService;
|
|
@@ -3142,6 +4241,8 @@ declare class JwtPlatformGuard implements CanActivate {
|
|
|
3142
4241
|
* @Post('/mfa/challenge')
|
|
3143
4242
|
* challenge(@Body() dto: MfaChallengeDto) { ... }
|
|
3144
4243
|
* ```
|
|
4244
|
+
*
|
|
4245
|
+
* @layer Guard
|
|
3145
4246
|
*/
|
|
3146
4247
|
declare class MfaRequiredGuard implements CanActivate {
|
|
3147
4248
|
private readonly reflector;
|
|
@@ -3168,6 +4269,8 @@ declare class MfaRequiredGuard implements CanActivate {
|
|
|
3168
4269
|
* @Get('/feed')
|
|
3169
4270
|
* feed(@CurrentUser() user: DashboardJwtPayload | null) { ... }
|
|
3170
4271
|
* ```
|
|
4272
|
+
*
|
|
4273
|
+
* @layer Guard
|
|
3171
4274
|
*/
|
|
3172
4275
|
declare class OptionalAuthGuard extends JwtAuthGuard {
|
|
3173
4276
|
canActivate(context: ExecutionContext): Promise<boolean>;
|
|
@@ -3201,6 +4304,8 @@ declare class OptionalAuthGuard extends JwtAuthGuard {
|
|
|
3201
4304
|
* @Delete('/platform/users/:id')
|
|
3202
4305
|
* deleteUser(@Param('id') id: string) { ... }
|
|
3203
4306
|
* ```
|
|
4307
|
+
*
|
|
4308
|
+
* @layer Guard
|
|
3204
4309
|
*/
|
|
3205
4310
|
declare class PlatformRolesGuard implements CanActivate {
|
|
3206
4311
|
private readonly reflector;
|
|
@@ -3232,6 +4337,8 @@ declare class PlatformRolesGuard implements CanActivate {
|
|
|
3232
4337
|
* @Delete('/users/:id')
|
|
3233
4338
|
* deleteUser(@Param('id') id: string) { ... }
|
|
3234
4339
|
* ```
|
|
4340
|
+
*
|
|
4341
|
+
* @layer Guard
|
|
3235
4342
|
*/
|
|
3236
4343
|
declare class RolesGuard implements CanActivate {
|
|
3237
4344
|
private readonly reflector;
|
|
@@ -3278,6 +4385,8 @@ declare class RolesGuard implements CanActivate {
|
|
|
3278
4385
|
* @Delete('/sessions/:id')
|
|
3279
4386
|
* revokeSession(@Param('id') sessionHash: string) { ... }
|
|
3280
4387
|
* ```
|
|
4388
|
+
*
|
|
4389
|
+
* @layer Guard
|
|
3281
4390
|
*/
|
|
3282
4391
|
declare class SelfOrAdminGuard implements CanActivate {
|
|
3283
4392
|
private readonly options;
|
|
@@ -3285,6 +4394,111 @@ declare class SelfOrAdminGuard implements CanActivate {
|
|
|
3285
4394
|
canActivate(context: ExecutionContext): boolean;
|
|
3286
4395
|
}
|
|
3287
4396
|
|
|
4397
|
+
declare class AuthRateLimitGuard implements CanActivate {
|
|
4398
|
+
private readonly reflector;
|
|
4399
|
+
private readonly options;
|
|
4400
|
+
private readonly redis;
|
|
4401
|
+
constructor(reflector: Reflector, options: ResolvedOptions, redis: AuthRedisService);
|
|
4402
|
+
canActivate(context: ExecutionContext): Promise<boolean>;
|
|
4403
|
+
/**
|
|
4404
|
+
* The counter key for one caller on one route.
|
|
4405
|
+
*
|
|
4406
|
+
* Scoped per route so a burst of logins cannot exhaust the budget for password resets, and
|
|
4407
|
+
* keyed by the HMAC of the IP so the keyspace holds no raw client address.
|
|
4408
|
+
*
|
|
4409
|
+
* @param request - The incoming request.
|
|
4410
|
+
* @param context - The execution context, for the handler's name.
|
|
4411
|
+
* @returns The un-namespaced Redis key.
|
|
4412
|
+
*/
|
|
4413
|
+
private counterKey;
|
|
4414
|
+
/**
|
|
4415
|
+
* The address this request is counted against.
|
|
4416
|
+
*
|
|
4417
|
+
* `'peer'` — the default — reads the socket directly, so `X-Forwarded-For` cannot influence
|
|
4418
|
+
* it. `'trusted-proxy'` uses `req.ip`, which honours the app's `trust proxy` setting and the
|
|
4419
|
+
* forwarding headers it admits.
|
|
4420
|
+
*
|
|
4421
|
+
* The default is the strict one because the two failure modes are not symmetric: keying on
|
|
4422
|
+
* the peer address behind a proxy over-counts, which is visible and recoverable, while
|
|
4423
|
+
* trusting a header the caller controls means the limiter reports success and enforces
|
|
4424
|
+
* nothing. An address that cannot be read at all falls back to a constant, so those requests
|
|
4425
|
+
* share one bucket rather than each getting an unlimited one.
|
|
4426
|
+
*
|
|
4427
|
+
* @param request - The incoming request.
|
|
4428
|
+
* @returns The address to key on.
|
|
4429
|
+
*/
|
|
4430
|
+
private clientIp;
|
|
4431
|
+
}
|
|
4432
|
+
|
|
4433
|
+
/**
|
|
4434
|
+
* Blocks a cross-site request that would otherwise be authenticated by the browser's ambient
|
|
4435
|
+
* session cookie.
|
|
4436
|
+
*
|
|
4437
|
+
* @remarks
|
|
4438
|
+
* `SameSite` carries this on its own for `lax` and `strict` — the browser simply does not send
|
|
4439
|
+
* the cookie. It does **not** carry it for `SameSite=None`, which the module allows (embedded
|
|
4440
|
+
* widgets, iframes, cross-domain SPAs) and which sends the cookie on every cross-site request.
|
|
4441
|
+
* That is the configuration this guard exists for, and it is the only one where the library has
|
|
4442
|
+
* a CSRF exposure at all.
|
|
4443
|
+
*
|
|
4444
|
+
* The decision uses only headers a page cannot forge:
|
|
4445
|
+
*
|
|
4446
|
+
* 1. A safe method changes nothing — allowed.
|
|
4447
|
+
* 2. `Sec-Fetch-Site: same-origin` / `none` proves the request is not cross-site — allowed.
|
|
4448
|
+
* 3. `Sec-Fetch-Site` present with any other value (`cross-site`, `same-site`) is the browser
|
|
4449
|
+
* stating the request came from somewhere else. Allowed only if `Origin` is listed in
|
|
4450
|
+
* `cookies.trustedOrigins`; refused otherwise, **including when the list is empty** — an
|
|
4451
|
+
* empty list means no other origin is authorized, not that every one is.
|
|
4452
|
+
* 4. `Sec-Fetch-Site` absent and `Origin` present: allowed if listed. Otherwise refused when a
|
|
4453
|
+
* list is configured, and allowed when it is empty — see the ambiguity below.
|
|
4454
|
+
* 5. Neither header at all — a non-browser client (curl, a server-to-server call). Allowed:
|
|
4455
|
+
* an attacker's page cannot make a browser *omit* `Origin` on a cross-site request, so the
|
|
4456
|
+
* absence is evidence there is no browser involved, not a way around the check.
|
|
4457
|
+
*
|
|
4458
|
+
* **The check does not depend on the request already being authenticated.** It used to: a
|
|
4459
|
+
* request carrying none of the module's cookies skipped straight to allowed, on the reasoning
|
|
4460
|
+
* that there was no ambient credential to abuse. The reasoning missed the requests that MINT
|
|
4461
|
+
* one. `POST /auth/login` and `/auth/register` carry no cookie and answer with a session, so an
|
|
4462
|
+
* attacker's page could log a victim's browser into the ATTACKER's account and then read
|
|
4463
|
+
* whatever the victim did there believing it was theirs.
|
|
4464
|
+
*
|
|
4465
|
+
* **Nor does it depend on the allowlist being populated.** It did, and that was the same bug
|
|
4466
|
+
* one level up. An empty list short-circuited to allowed on the reasoning that `SameSite`
|
|
4467
|
+
* withholds the cookie cross-site anyway — true, and irrelevant to a login CSRF, where the
|
|
4468
|
+
* credentials are in the attacker's own request body and no cookie needs to be sent at all. The
|
|
4469
|
+
* response's `Set-Cookie` lands first-party because a form POST is a top-level navigation, so
|
|
4470
|
+
* third-party cookie policy does not help either. Since the default configuration ships an
|
|
4471
|
+
* empty list, that short-circuit meant the guard was inert in the deployment shape most
|
|
4472
|
+
* consumers run, while its own documentation claimed the class was closed.
|
|
4473
|
+
*
|
|
4474
|
+
* **The one case that stays permissive, and why.** A same-origin POST from a browser that sends
|
|
4475
|
+
* `Origin` and omits `Sec-Fetch-Site` is indistinguishable from a cross-site one: this module
|
|
4476
|
+
* never learns its own origin (reconstructing it from `Host` or `X-Forwarded-Proto` would trust
|
|
4477
|
+
* a client-controlled header, and a check that trusts them is not a check). `Sec-Fetch-Site`
|
|
4478
|
+
* resolves that ambiguity whenever it is present — Chrome 76, Firefox 90 and Safari 16.4 all
|
|
4479
|
+
* send it — so the residual gap is a browser old enough to send `Origin` without it. A
|
|
4480
|
+
* deployment that wants that gap closed too lists its own origin in `cookies.trustedOrigins`,
|
|
4481
|
+
* which is accepted under every `sameSite` value for exactly this reason.
|
|
4482
|
+
*
|
|
4483
|
+
* @example
|
|
4484
|
+
* ```typescript
|
|
4485
|
+
* // Cross-domain SPA: the API is on api.example.com, the app on app.example.com.
|
|
4486
|
+
* BymaxAuthModule.registerAsync({
|
|
4487
|
+
* useFactory: () => ({
|
|
4488
|
+
* cookies: { sameSite: 'none', trustedOrigins: ['https://app.example.com'] },
|
|
4489
|
+
* secureCookies: true
|
|
4490
|
+
* })
|
|
4491
|
+
* })
|
|
4492
|
+
* ```
|
|
4493
|
+
*
|
|
4494
|
+
* @layer Guard
|
|
4495
|
+
*/
|
|
4496
|
+
declare class TrustedOriginGuard implements CanActivate {
|
|
4497
|
+
private readonly options;
|
|
4498
|
+
constructor(options: ResolvedOptions);
|
|
4499
|
+
canActivate(context: ExecutionContext): boolean;
|
|
4500
|
+
}
|
|
4501
|
+
|
|
3288
4502
|
/**
|
|
3289
4503
|
* Verifies that the authenticated user's account status is not blocked.
|
|
3290
4504
|
*
|
|
@@ -3308,6 +4522,8 @@ declare class SelfOrAdminGuard implements CanActivate {
|
|
|
3308
4522
|
* @Get('/dashboard')
|
|
3309
4523
|
* dashboard() { ... }
|
|
3310
4524
|
* ```
|
|
4525
|
+
*
|
|
4526
|
+
* @layer Guard
|
|
3311
4527
|
*/
|
|
3312
4528
|
declare class UserStatusGuard implements CanActivate {
|
|
3313
4529
|
private readonly redis;
|
|
@@ -3317,6 +4533,55 @@ declare class UserStatusGuard implements CanActivate {
|
|
|
3317
4533
|
canActivate(context: ExecutionContext): Promise<boolean>;
|
|
3318
4534
|
}
|
|
3319
4535
|
|
|
4536
|
+
/**
|
|
4537
|
+
* @fileoverview Single-use WebSocket upgrade tickets.
|
|
4538
|
+
*
|
|
4539
|
+
* The browser `WebSocket` API cannot set handshake headers, so a browser client has no way to
|
|
4540
|
+
* present `Authorization: Bearer <token>` at the upgrade. The usual workaround — the access
|
|
4541
|
+
* token in the query string — writes a long-lived credential into access logs, browser history
|
|
4542
|
+
* and proxy caches. {@link WsJwtGuard} refuses it for exactly that reason, which left browser
|
|
4543
|
+
* clients with no supported path at all.
|
|
4544
|
+
*
|
|
4545
|
+
* A ticket is the other answer: opaque, single-use, ~30 seconds, and worth nothing once
|
|
4546
|
+
* redeemed. It is minted only from a session that is already authenticated, in good standing
|
|
4547
|
+
* and MFA-satisfied, so the ticket can never carry more authority than the session that asked
|
|
4548
|
+
* for it.
|
|
4549
|
+
*
|
|
4550
|
+
* @layer Service
|
|
4551
|
+
*/
|
|
4552
|
+
|
|
4553
|
+
declare class WsTicketService {
|
|
4554
|
+
private readonly redis;
|
|
4555
|
+
private readonly options;
|
|
4556
|
+
private readonly userRepo;
|
|
4557
|
+
private readonly logger;
|
|
4558
|
+
constructor(redis: AuthRedisService, options: ResolvedOptions, userRepo: IUserRepository);
|
|
4559
|
+
/**
|
|
4560
|
+
* Mints a ticket from an already-verified access-token payload.
|
|
4561
|
+
*
|
|
4562
|
+
* The caller is responsible for having run the authentication, status and MFA guards — the
|
|
4563
|
+
* payload reaching here is what those guards admitted. Nothing from the token itself is
|
|
4564
|
+
* copied into the ticket beyond the identity it proved: no `jti`, no expiry, nothing that
|
|
4565
|
+
* could be replayed against the REST surface.
|
|
4566
|
+
*
|
|
4567
|
+
* @param payload - The verified dashboard access-token payload.
|
|
4568
|
+
* @returns The raw ticket and how long it is valid for.
|
|
4569
|
+
*/
|
|
4570
|
+
issue(payload: DashboardJwtPayload): Promise<{
|
|
4571
|
+
ticket: string;
|
|
4572
|
+
expiresIn: number;
|
|
4573
|
+
}>;
|
|
4574
|
+
/**
|
|
4575
|
+
* Redeems a ticket at the handshake, consuming it.
|
|
4576
|
+
*
|
|
4577
|
+
* @param ticket - The raw ticket from the upgrade request.
|
|
4578
|
+
* @returns The identity the socket is authorized as.
|
|
4579
|
+
* @throws {@link AuthException} `auth.token_invalid` when the ticket is unknown, expired or
|
|
4580
|
+
* already redeemed — the three are deliberately indistinguishable to the caller.
|
|
4581
|
+
*/
|
|
4582
|
+
redeem(ticket: string): Promise<WsTicketSnapshot>;
|
|
4583
|
+
}
|
|
4584
|
+
|
|
3320
4585
|
/**
|
|
3321
4586
|
* WebSocket authentication guard — the WS twin of {@link JwtAuthGuard}.
|
|
3322
4587
|
*
|
|
@@ -3325,11 +4590,22 @@ declare class UserStatusGuard implements CanActivate {
|
|
|
3325
4590
|
* Redis revocation checks mirror the HTTP guard exactly.
|
|
3326
4591
|
*
|
|
3327
4592
|
* @remarks
|
|
3328
|
-
* **
|
|
3329
|
-
*
|
|
3330
|
-
*
|
|
3331
|
-
*
|
|
3332
|
-
*
|
|
4593
|
+
* **Two credential channels, and only two** — the handshake
|
|
4594
|
+
* `Authorization: Bearer <token>` header, or a single-use ticket in the upgrade
|
|
4595
|
+
* query string.
|
|
4596
|
+
*
|
|
4597
|
+
* An access **token** in the query string stays unsupported, and for the original
|
|
4598
|
+
* reason: it is trivially captured in access logs, browser history and proxy
|
|
4599
|
+
* caches, which makes it equivalent to sending the credential in plaintext. But
|
|
4600
|
+
* the browser `WebSocket` API cannot set handshake headers, so header-only left
|
|
4601
|
+
* browser clients with no supported path at all — and a library that offers none
|
|
4602
|
+
* gets the query-string token anyway, written by the consumer.
|
|
4603
|
+
*
|
|
4604
|
+
* A ticket is the answer to that: minted by `POST {prefix}/ws-ticket` from a
|
|
4605
|
+
* session that is already authenticated, in good standing and MFA-satisfied;
|
|
4606
|
+
* opaque; ~30 seconds; and consumed by the first redemption, so a captured
|
|
4607
|
+
* upgrade URL is worthless by the time it reaches a log. rust-auth authenticates
|
|
4608
|
+
* its upgrades the same way.
|
|
3333
4609
|
*
|
|
3334
4610
|
* **Algorithm pinning** — `algorithms: [this.options.jwt.algorithm]` is forwarded
|
|
3335
4611
|
* to `JwtService.verify()` to prevent algorithm-confusion attacks (CVE-2015-9235).
|
|
@@ -3352,16 +4628,86 @@ declare class UserStatusGuard implements CanActivate {
|
|
|
3352
4628
|
* @SubscribeMessage('message')
|
|
3353
4629
|
* handleMessage(@ConnectedSocket() client: Socket) { ... }
|
|
3354
4630
|
* ```
|
|
4631
|
+
*
|
|
4632
|
+
* @layer Guard
|
|
3355
4633
|
*/
|
|
3356
4634
|
declare class WsJwtGuard implements CanActivate, OnModuleInit {
|
|
3357
4635
|
private readonly jwtService;
|
|
3358
4636
|
private readonly redis;
|
|
4637
|
+
private readonly wsTickets;
|
|
3359
4638
|
private readonly options;
|
|
3360
|
-
constructor(jwtService: JwtService, redis: AuthRedisService, options: ResolvedOptions);
|
|
4639
|
+
constructor(jwtService: JwtService, redis: AuthRedisService, wsTickets: WsTicketService, options: ResolvedOptions);
|
|
4640
|
+
/**
|
|
4641
|
+
* Verifies that `@nestjs/websockets` is installed and throws a descriptive
|
|
4642
|
+
* error at application startup if the package is absent.
|
|
4643
|
+
*/
|
|
3361
4644
|
onModuleInit(): Promise<void>;
|
|
3362
4645
|
canActivate(context: ExecutionContext): Promise<boolean>;
|
|
3363
4646
|
}
|
|
3364
4647
|
|
|
4648
|
+
/**
|
|
4649
|
+
* Gives every failure the same `{ error: { code, message, details } }` body.
|
|
4650
|
+
*
|
|
4651
|
+
* Optional, and off unless a host registers it — a library does not get to decide how an
|
|
4652
|
+
* application answers failures it did not raise. What it fixes when registered is that a
|
|
4653
|
+
* client parsing `error.code` needed a second parser for exactly the responses it can do least
|
|
4654
|
+
* about: an unhandled failure answers in the framework's `{ statusCode, message, error }`
|
|
4655
|
+
* shape, and so does any `HttpException` the surrounding application throws. rust-auth answers
|
|
4656
|
+
* `auth.internal` in its own envelope for the same case, so a deployment fronting both saw two
|
|
4657
|
+
* shapes for one condition.
|
|
4658
|
+
*
|
|
4659
|
+
* The cause is logged and never serialized: an internal failure's message is the one place a
|
|
4660
|
+
* stack detail or a connection string reaches a response body, so the answer carries the
|
|
4661
|
+
* generic code and nothing else.
|
|
4662
|
+
*
|
|
4663
|
+
* @example
|
|
4664
|
+
* ```typescript
|
|
4665
|
+
* app.useGlobalFilters(new AuthExceptionFilter())
|
|
4666
|
+
* ```
|
|
4667
|
+
*
|
|
4668
|
+
* @layer Filter
|
|
4669
|
+
*/
|
|
4670
|
+
declare class AuthExceptionFilter implements ExceptionFilter {
|
|
4671
|
+
private readonly logger;
|
|
4672
|
+
/**
|
|
4673
|
+
* Writes `exception` to the response in the library envelope.
|
|
4674
|
+
*
|
|
4675
|
+
* @param exception - Whatever was thrown.
|
|
4676
|
+
* @param host - The arguments host, used to reach the HTTP response.
|
|
4677
|
+
*/
|
|
4678
|
+
catch(exception: unknown, host: ArgumentsHost): void;
|
|
4679
|
+
}
|
|
4680
|
+
|
|
4681
|
+
/**
|
|
4682
|
+
* @fileoverview The validation pipe every auth controller mounts.
|
|
4683
|
+
*
|
|
4684
|
+
* @layer Pipe
|
|
4685
|
+
*/
|
|
4686
|
+
|
|
4687
|
+
/** One rejected request field, as it serializes under `error.details`. */
|
|
4688
|
+
interface AuthFieldError {
|
|
4689
|
+
/** The offending field. Dotted path for nested objects (`address.zip`). */
|
|
4690
|
+
field: string;
|
|
4691
|
+
/** Human-readable reason the field was rejected. */
|
|
4692
|
+
message: string;
|
|
4693
|
+
}
|
|
4694
|
+
/**
|
|
4695
|
+
* Builds the `ValidationPipe` the auth controllers mount.
|
|
4696
|
+
*
|
|
4697
|
+
* The pipe exists for one reason beyond the usual whitelisting: its `exceptionFactory`. Nest's
|
|
4698
|
+
* default answers a malformed body with the framework's own shape — `{ statusCode, message,
|
|
4699
|
+
* error }` — while every other failure in this library answers with `{ error: { code, message,
|
|
4700
|
+
* details } }`. A client parsing auth errors therefore needed two parsers, and the one shape it
|
|
4701
|
+
* could not read by `error.code` was the one that says which field to fix. Validation failures
|
|
4702
|
+
* now carry `auth.validation` with the per-field list under `error.details`, which is the same
|
|
4703
|
+
* code and the same details rust-auth emits for the same failure.
|
|
4704
|
+
*
|
|
4705
|
+
* @param options - Extra `ValidationPipe` options, merged over the defaults
|
|
4706
|
+
* (`whitelist`, `forbidNonWhitelisted`). Pass `forbidUnknownValues` where a route needs it.
|
|
4707
|
+
* @returns A configured pipe instance, ready for `@UsePipes()`.
|
|
4708
|
+
*/
|
|
4709
|
+
declare function createAuthValidationPipe(options?: ValidationPipeOptions): ValidationPipe;
|
|
4710
|
+
|
|
3365
4711
|
/**
|
|
3366
4712
|
* Extracts the authenticated user payload from the request, or a specific
|
|
3367
4713
|
* field from that payload.
|
|
@@ -3384,6 +4730,7 @@ declare class WsJwtGuard implements CanActivate, OnModuleInit {
|
|
|
3384
4730
|
*
|
|
3385
4731
|
* @param property - Optional key to extract from the payload. When omitted the
|
|
3386
4732
|
* entire payload object is returned.
|
|
4733
|
+
* @returns The full {@link DashboardJwtPayload} when `property` is omitted, or the value of the requested field.
|
|
3387
4734
|
*/
|
|
3388
4735
|
declare const CurrentUser: (...dataOrPipes: (keyof DashboardJwtPayload | _nestjs_common.PipeTransform<any, any> | _nestjs_common.Type<_nestjs_common.PipeTransform<any, any>> | undefined)[]) => ParameterDecorator;
|
|
3389
4736
|
|
|
@@ -3414,12 +4761,49 @@ declare const PLATFORM_ROLES_KEY: unique symbol;
|
|
|
3414
4761
|
*/
|
|
3415
4762
|
declare const PlatformRoles: (...roles: string[]) => MethodDecorator & ClassDecorator;
|
|
3416
4763
|
|
|
4764
|
+
/**
|
|
4765
|
+
* Marks a single handler as requiring authentication, overriding a class-level
|
|
4766
|
+
* {@link Public} on the controller it belongs to.
|
|
4767
|
+
*
|
|
4768
|
+
* `@Public()` sets its metadata to `true`, and the guards resolve it with
|
|
4769
|
+
* `getAllAndOverride([handler, class])` — handler first. Without a decorator that writes
|
|
4770
|
+
* `false`, a controller marked public at the class level could never carry an authenticated
|
|
4771
|
+
* route: adding `@UseGuards(JwtAuthGuard)` to the method changes nothing, because the guard
|
|
4772
|
+
* reads the public flag and returns before it looks at anything else. That is a silent
|
|
4773
|
+
* failure — the route mounts, the guard runs, and it lets everyone through.
|
|
4774
|
+
*
|
|
4775
|
+
* Pair it with the guards the route actually needs; this decorator only undoes the exemption.
|
|
4776
|
+
*
|
|
4777
|
+
* @example
|
|
4778
|
+
* ```typescript
|
|
4779
|
+
* \@Public()
|
|
4780
|
+
* \@Controller('password')
|
|
4781
|
+
* export class PasswordResetController {
|
|
4782
|
+
* // …the public recovery endpoints…
|
|
4783
|
+
*
|
|
4784
|
+
* \@Authenticated()
|
|
4785
|
+
* \@UseGuards(JwtAuthGuard, UserStatusGuard)
|
|
4786
|
+
* \@Post('change')
|
|
4787
|
+
* async changePassword() {}
|
|
4788
|
+
* }
|
|
4789
|
+
* ```
|
|
4790
|
+
*/
|
|
4791
|
+
declare const Authenticated: () => MethodDecorator & ClassDecorator;
|
|
4792
|
+
|
|
3417
4793
|
/**
|
|
3418
4794
|
* Metadata key used by {@link JwtAuthGuard} to identify public (unauthenticated) routes.
|
|
3419
4795
|
*
|
|
3420
4796
|
* Read via `Reflector.getAllAndOverride(IS_PUBLIC_KEY, [handler, class])`.
|
|
4797
|
+
*
|
|
4798
|
+
* A `Symbol` rather than the string `'isPublic'`, matching `SKIP_MFA_KEY` and the project's
|
|
4799
|
+
* injection-token rule. The literal is the one the canonical NestJS documentation uses in its
|
|
4800
|
+
* `@Public()` example, so a host that writes its own following those docs wrote the SAME
|
|
4801
|
+
* metadata key — and every route it marked public for its own guard was then also public to
|
|
4802
|
+
* `JwtAuthGuard` wherever the host mounts it. Both decorators mean "skip auth", so the
|
|
4803
|
+
* collision did not invert anyone's intent, but a key that gates authentication should not be
|
|
4804
|
+
* a value the ecosystem hands out by convention.
|
|
3421
4805
|
*/
|
|
3422
|
-
declare const IS_PUBLIC_KEY
|
|
4806
|
+
declare const IS_PUBLIC_KEY: unique symbol;
|
|
3423
4807
|
/**
|
|
3424
4808
|
* Marks a route as public — JwtAuthGuard skips token validation entirely.
|
|
3425
4809
|
*
|
|
@@ -3507,6 +4891,8 @@ declare const SkipMfa: () => MethodDecorator & ClassDecorator;
|
|
|
3507
4891
|
* Data Transfer Object for the accept invitation endpoint.
|
|
3508
4892
|
*
|
|
3509
4893
|
* Validated via NestJS `ValidationPipe` before reaching the service layer.
|
|
4894
|
+
*
|
|
4895
|
+
* @layer DTO
|
|
3510
4896
|
*/
|
|
3511
4897
|
declare class AcceptInvitationDto {
|
|
3512
4898
|
/**
|
|
@@ -3550,6 +4936,8 @@ declare class AcceptInvitationDto {
|
|
|
3550
4936
|
* Role validation against the configured hierarchy is performed in
|
|
3551
4937
|
* `InvitationService.invite()` — not here — because `class-validator`
|
|
3552
4938
|
* decorators have no access to the NestJS DI container at validation time.
|
|
4939
|
+
*
|
|
4940
|
+
* @layer DTO
|
|
3553
4941
|
*/
|
|
3554
4942
|
declare class CreateInvitationDto {
|
|
3555
4943
|
/**
|
|
@@ -3585,6 +4973,8 @@ declare class CreateInvitationDto {
|
|
|
3585
4973
|
* Initiates the password reset flow by sending a token or OTP to the user's
|
|
3586
4974
|
* email. Always returns success regardless of whether the email exists to
|
|
3587
4975
|
* prevent user enumeration.
|
|
4976
|
+
*
|
|
4977
|
+
* @layer DTO
|
|
3588
4978
|
*/
|
|
3589
4979
|
declare class ForgotPasswordDto {
|
|
3590
4980
|
/**
|
|
@@ -3603,6 +4993,8 @@ declare class ForgotPasswordDto {
|
|
|
3603
4993
|
* Data Transfer Object for the user login endpoint.
|
|
3604
4994
|
*
|
|
3605
4995
|
* Validated via NestJS `ValidationPipe` before reaching the service layer.
|
|
4996
|
+
*
|
|
4997
|
+
* @layer DTO
|
|
3606
4998
|
*/
|
|
3607
4999
|
declare class LoginDto {
|
|
3608
5000
|
/**
|
|
@@ -3610,6 +5002,12 @@ declare class LoginDto {
|
|
|
3610
5002
|
* Bounded to 255 characters — the RFC-recommended practical maximum for
|
|
3611
5003
|
* addr-spec — so that an unbounded string cannot inflate downstream hashing,
|
|
3612
5004
|
* Redis keys, or error logs.
|
|
5005
|
+
*
|
|
5006
|
+
* Normalized to lowercase and trimmed BEFORE it reaches the service, so the
|
|
5007
|
+
* brute-force lockout identifier (`hmac(tenantId + ":" + email)`) is derived
|
|
5008
|
+
* from the same canonical value that the case-insensitive user lookup resolves.
|
|
5009
|
+
* Without this, an attacker defeats the lockout by rotating the e-mail letter-
|
|
5010
|
+
* case: each casing is a distinct lockout bucket yet resolves the same account.
|
|
3613
5011
|
*/
|
|
3614
5012
|
email: string;
|
|
3615
5013
|
/**
|
|
@@ -3641,6 +5039,8 @@ declare class LoginDto {
|
|
|
3641
5039
|
* Submitted during the login flow when the user has MFA enabled.
|
|
3642
5040
|
* Contains the short-lived MFA temp token issued at login alongside
|
|
3643
5041
|
* either a 6-digit TOTP code or a recovery code.
|
|
5042
|
+
*
|
|
5043
|
+
* @layer DTO
|
|
3644
5044
|
*/
|
|
3645
5045
|
declare class MfaChallengeDto {
|
|
3646
5046
|
/**
|
|
@@ -3689,6 +5089,8 @@ declare class MfaChallengeDto {
|
|
|
3689
5089
|
* should not be able to silently disable MFA (which would leave the account
|
|
3690
5090
|
* unprotected). Recovery without a TOTP device requires administrative
|
|
3691
5091
|
* intervention via a support channel.
|
|
5092
|
+
*
|
|
5093
|
+
* @layer DTO
|
|
3692
5094
|
*/
|
|
3693
5095
|
declare class MfaDisableDto {
|
|
3694
5096
|
/**
|
|
@@ -3717,6 +5119,8 @@ declare class MfaDisableDto {
|
|
|
3717
5119
|
* re-enrol (which forces a fresh secret AND a fresh recovery code set),
|
|
3718
5120
|
* not to silently rotate recovery codes using one of the codes the user
|
|
3719
5121
|
* may already have leaked.
|
|
5122
|
+
*
|
|
5123
|
+
* @layer DTO
|
|
3720
5124
|
*/
|
|
3721
5125
|
declare class MfaRegenerateRecoveryCodesDto {
|
|
3722
5126
|
/**
|
|
@@ -3730,10 +5134,12 @@ declare class MfaRegenerateRecoveryCodesDto {
|
|
|
3730
5134
|
}
|
|
3731
5135
|
|
|
3732
5136
|
/**
|
|
3733
|
-
* Data Transfer Object for the MFA TOTP verification
|
|
5137
|
+
* Data Transfer Object for the MFA TOTP verification during setup.
|
|
3734
5138
|
*
|
|
3735
5139
|
* Submitted after `POST /mfa/setup` to confirm that the user has successfully
|
|
3736
5140
|
* enrolled their authenticator app by providing a valid code.
|
|
5141
|
+
*
|
|
5142
|
+
* @layer DTO
|
|
3737
5143
|
*/
|
|
3738
5144
|
declare class MfaVerifyDto {
|
|
3739
5145
|
/**
|
|
@@ -3750,6 +5156,8 @@ declare class MfaVerifyDto {
|
|
|
3750
5156
|
*
|
|
3751
5157
|
* Platform users are not tenant-scoped, so no `tenantId` field is required.
|
|
3752
5158
|
* Validated via NestJS `ValidationPipe` before reaching the service layer.
|
|
5159
|
+
*
|
|
5160
|
+
* @layer DTO
|
|
3753
5161
|
*/
|
|
3754
5162
|
declare class PlatformLoginDto {
|
|
3755
5163
|
/**
|
|
@@ -3762,8 +5170,14 @@ declare class PlatformLoginDto {
|
|
|
3762
5170
|
* Plaintext password supplied by the platform admin.
|
|
3763
5171
|
*
|
|
3764
5172
|
* @remarks
|
|
3765
|
-
*
|
|
3766
|
-
*
|
|
5173
|
+
* The floor is 1, not the deployment's policy length. This is a *login*: the password may
|
|
5174
|
+
* predate whatever the policy says today, and refusing it here locks an operator out of the
|
|
5175
|
+
* console with a validation error rather than an authentication one — while telling an
|
|
5176
|
+
* unauthenticated caller what the policy is, before any key derivation runs. The policy
|
|
5177
|
+
* belongs on the paths that SET a password. `@Matches(/\S/)` still rejects a blank value, so
|
|
5178
|
+
* nobody buys a KDF derivation for free, and `@MaxLength` bounds the payload.
|
|
5179
|
+
*
|
|
5180
|
+
* rust-auth bounds this field the same way, and the dashboard login always has.
|
|
3767
5181
|
* Credentials are provisioned externally — the consuming application
|
|
3768
5182
|
* may add stricter validation at the provisioning layer.
|
|
3769
5183
|
*/
|
|
@@ -3775,6 +5189,8 @@ declare class PlatformLoginDto {
|
|
|
3775
5189
|
*
|
|
3776
5190
|
* Validated via NestJS `ValidationPipe` before reaching the service layer.
|
|
3777
5191
|
* All validation rules are enforced at the HTTP boundary.
|
|
5192
|
+
*
|
|
5193
|
+
* @layer DTO
|
|
3778
5194
|
*/
|
|
3779
5195
|
declare class RegisterDto {
|
|
3780
5196
|
/**
|
|
@@ -3782,6 +5198,10 @@ declare class RegisterDto {
|
|
|
3782
5198
|
* Must be a valid RFC 5321 email format. Bounded to 255 characters — the
|
|
3783
5199
|
* RFC-recommended practical maximum for addr-spec — matching the limit on
|
|
3784
5200
|
* every other email-accepting DTO in the library.
|
|
5201
|
+
*
|
|
5202
|
+
* Normalized to lowercase and trimmed so the stored identity matches the
|
|
5203
|
+
* canonical form used by the case-insensitive login lookup and every other
|
|
5204
|
+
* e-mail-keyed control (brute-force counter, reset tokens, verification OTP).
|
|
3785
5205
|
*/
|
|
3786
5206
|
email: string;
|
|
3787
5207
|
/**
|
|
@@ -3813,6 +5233,8 @@ declare class RegisterDto {
|
|
|
3813
5233
|
* Subject to a 60-second atomic cooldown enforced via a Redis NX key to
|
|
3814
5234
|
* prevent OTP flooding. Always returns success regardless of user existence
|
|
3815
5235
|
* to prevent enumeration.
|
|
5236
|
+
*
|
|
5237
|
+
* @layer DTO
|
|
3816
5238
|
*/
|
|
3817
5239
|
declare class ResendOtpDto {
|
|
3818
5240
|
/**
|
|
@@ -3832,6 +5254,8 @@ declare class ResendOtpDto {
|
|
|
3832
5254
|
* Requests a new email verification OTP to be sent to the user's address.
|
|
3833
5255
|
* Subject to IP-level throttling configured in `AUTH_THROTTLE_CONFIGS.resendVerification`.
|
|
3834
5256
|
* Always returns success regardless of user existence to prevent enumeration.
|
|
5257
|
+
*
|
|
5258
|
+
* @layer DTO
|
|
3835
5259
|
*/
|
|
3836
5260
|
declare class ResendVerificationDto {
|
|
3837
5261
|
/**
|
|
@@ -3846,10 +5270,43 @@ declare class ResendVerificationDto {
|
|
|
3846
5270
|
}
|
|
3847
5271
|
|
|
3848
5272
|
/**
|
|
3849
|
-
* Data Transfer Object for the
|
|
5273
|
+
* Data Transfer Object for changing the password of an already-authenticated account.
|
|
3850
5274
|
*
|
|
3851
|
-
*
|
|
3852
|
-
*
|
|
5275
|
+
* Submitted to `POST {prefix}/password/change`. Distinct from {@link ResetPasswordDto}, which
|
|
5276
|
+
* serves the *unauthenticated* recovery flow and proves identity with an emailed token or OTP:
|
|
5277
|
+
* here the proof is the current password, which is the only thing a stolen session does not
|
|
5278
|
+
* carry.
|
|
5279
|
+
*
|
|
5280
|
+
* @layer DTO
|
|
5281
|
+
*/
|
|
5282
|
+
declare class ChangePasswordDto {
|
|
5283
|
+
/**
|
|
5284
|
+
* The account's current password, re-proving who is asking.
|
|
5285
|
+
*
|
|
5286
|
+
* ASVS v5 §6.2.3 requires a password change to take both the current and the new password,
|
|
5287
|
+
* and the reason is exactly the session-theft case: an access token lifted by XSS or from a
|
|
5288
|
+
* shared machine would otherwise be enough to rotate the credential, lock the real owner
|
|
5289
|
+
* out of their own account, and keep the attacker in.
|
|
5290
|
+
*
|
|
5291
|
+
* `@MinLength(1)` is the only floor, matching `LoginDto`: rejecting the empty string keeps a
|
|
5292
|
+
* caller from spending a scrypt derivation for free, while enforcing the deployment's real
|
|
5293
|
+
* policy length here would leak it as a pre-KDF timing signal — and the value is a *current*
|
|
5294
|
+
* password, which may predate whatever the policy says today.
|
|
5295
|
+
*/
|
|
5296
|
+
currentPassword: string;
|
|
5297
|
+
/**
|
|
5298
|
+
* New plaintext password chosen by the user.
|
|
5299
|
+
* Minimum 8 characters for usability; maximum 128 characters as a practical bound.
|
|
5300
|
+
* Hashed immediately by the service layer — never persisted in plaintext.
|
|
5301
|
+
*/
|
|
5302
|
+
newPassword: string;
|
|
5303
|
+
}
|
|
5304
|
+
|
|
5305
|
+
/**
|
|
5306
|
+
* Data Transfer Object for the reset-password endpoint.
|
|
5307
|
+
*
|
|
5308
|
+
* Exactly one of `token`, `otp`, or `verifiedToken` must be present.
|
|
5309
|
+
* The service layer validates this mutual exclusivity after DTO validation passes.
|
|
3853
5310
|
*
|
|
3854
5311
|
* @remarks
|
|
3855
5312
|
* Optional fields enforce non-empty constraints so that if a value is submitted it
|
|
@@ -3857,6 +5314,8 @@ declare class ResendVerificationDto {
|
|
|
3857
5314
|
* `verifiedToken` uses `@Length(64, 64)`. Without these guards, an empty string would
|
|
3858
5315
|
* pass `@IsOptional()` and produce a valid (but incorrect) `sha256("")` key in Redis,
|
|
3859
5316
|
* potentially allowing a crafted request to bypass token validation.
|
|
5317
|
+
*
|
|
5318
|
+
* @layer DTO
|
|
3860
5319
|
*/
|
|
3861
5320
|
declare class ResetPasswordDto {
|
|
3862
5321
|
/**
|
|
@@ -3900,6 +5359,8 @@ declare class ResetPasswordDto {
|
|
|
3900
5359
|
*
|
|
3901
5360
|
* Verifies the user's email address by submitting the OTP that was sent
|
|
3902
5361
|
* after registration (when `emailVerification.required` is enabled).
|
|
5362
|
+
*
|
|
5363
|
+
* @layer DTO
|
|
3903
5364
|
*/
|
|
3904
5365
|
declare class VerifyEmailDto {
|
|
3905
5366
|
/**
|
|
@@ -3925,6 +5386,8 @@ declare class VerifyEmailDto {
|
|
|
3925
5386
|
* Validates a password-reset OTP and exchanges it for a short-lived
|
|
3926
5387
|
* `verifiedToken` (5-minute TTL) that can then be used with `ResetPasswordDto`
|
|
3927
5388
|
* to complete the reset without re-submitting the OTP.
|
|
5389
|
+
*
|
|
5390
|
+
* @layer DTO
|
|
3928
5391
|
*/
|
|
3929
5392
|
declare class VerifyOtpDto {
|
|
3930
5393
|
/**
|
|
@@ -3964,6 +5427,8 @@ declare class VerifyOtpDto {
|
|
|
3964
5427
|
*
|
|
3965
5428
|
* **Lockout check order:** Always call `isLockedOut` before `recordFailure` to
|
|
3966
5429
|
* prevent an extra increment on an already-locked account.
|
|
5430
|
+
*
|
|
5431
|
+
* @layer Service
|
|
3967
5432
|
*/
|
|
3968
5433
|
declare class BruteForceService {
|
|
3969
5434
|
private readonly redis;
|
|
@@ -4040,6 +5505,8 @@ declare class BruteForceService {
|
|
|
4040
5505
|
* when the buffer sizes differ. This short-circuit does NOT leak timing
|
|
4041
5506
|
* information about the correct code length beyond what the OTP digit count
|
|
4042
5507
|
* already implies.
|
|
5508
|
+
*
|
|
5509
|
+
* @layer Service
|
|
4043
5510
|
*/
|
|
4044
5511
|
declare class OtpService {
|
|
4045
5512
|
private readonly redis;
|
|
@@ -4073,55 +5540,21 @@ declare class OtpService {
|
|
|
4073
5540
|
* @param purpose - Logical purpose matching the one used in {@link store}.
|
|
4074
5541
|
* @param identifier - User-scoped identifier matching the one used in {@link store}.
|
|
4075
5542
|
* @param code - The OTP code supplied by the user.
|
|
4076
|
-
* @throws {@link AuthException} with `
|
|
4077
|
-
*
|
|
4078
|
-
*
|
|
5543
|
+
* @throws {@link AuthException} with `OTP_INVALID` — for a missing record, an exhausted
|
|
5544
|
+
* attempt ceiling, and a wrong code alike. The three are deliberately indistinguishable:
|
|
5545
|
+
* see the note in the body.
|
|
4079
5546
|
*/
|
|
4080
5547
|
verify(purpose: string, identifier: string, code: string): Promise<void>;
|
|
4081
|
-
/**
|
|
4082
|
-
* Increments the attempt counter for an existing OTP record atomically.
|
|
4083
|
-
*
|
|
4084
|
-
* Uses a Lua script to read the TTL and update the record in a single round-trip,
|
|
4085
|
-
* preserving the expiry and avoiding a GET + TTL + SET sequence.
|
|
4086
|
-
* If the key has no TTL or is gone the update is silently skipped.
|
|
4087
|
-
*
|
|
4088
|
-
* @param purpose - Purpose segment of the key.
|
|
4089
|
-
* @param identifier - Identifier segment of the key.
|
|
4090
|
-
* @param currentRecord - The already-parsed OTP record (avoids a redundant GET).
|
|
4091
|
-
*/
|
|
4092
|
-
private incrementAttempts;
|
|
4093
5548
|
}
|
|
4094
5549
|
|
|
4095
|
-
/**
|
|
4096
|
-
* Password hashing and verification service using `node:crypto` scrypt.
|
|
4097
|
-
*
|
|
4098
|
-
* Uses scrypt (RFC 7914) — a memory-hard key derivation function designed to
|
|
4099
|
-
* resist brute-force and GPU/ASIC attacks. **Never use SHA-256, MD5, or
|
|
4100
|
-
* unsalted hashes for passwords.**
|
|
4101
|
-
*
|
|
4102
|
-
* Wire format: `scrypt:{salt_hex}:{derived_hex}`
|
|
4103
|
-
* - `salt_hex` — 32-char hex string (16 random bytes)
|
|
4104
|
-
* - `derived_hex` — 128-char hex string (64 derived bytes)
|
|
4105
|
-
*
|
|
4106
|
-
* @remarks
|
|
4107
|
-
* **Cost parameters:** Taken from `options.password` at construction time.
|
|
4108
|
-
* Defaults are `costFactor = 32768 (2^15)`, `blockSize = 8`, `parallelization = 1`.
|
|
4109
|
-
* Override in `BymaxAuthModule.forRoot({ password: { costFactor: 65536 } })`.
|
|
4110
|
-
* Validated at startup by `resolveOptions()` — values below `16384 (2^14)` are rejected.
|
|
4111
|
-
*
|
|
4112
|
-
* **Security:** Comparison uses `crypto.timingSafeEqual` to prevent timing
|
|
4113
|
-
* attacks. All comparison failures return `false` — never throw on bad input.
|
|
4114
|
-
*
|
|
4115
|
-
* **Thread safety:** scrypt is CPU-intensive. In production, calls will block
|
|
4116
|
-
* the Node.js event loop for ~100–200 ms. Consider running behind a worker
|
|
4117
|
-
* thread or rate-limiting authentication endpoints.
|
|
4118
|
-
*/
|
|
4119
5550
|
declare class PasswordService {
|
|
5551
|
+
private readonly breachChecker;
|
|
5552
|
+
private readonly logger;
|
|
4120
5553
|
private readonly N;
|
|
4121
5554
|
private readonly r;
|
|
4122
5555
|
private readonly p;
|
|
4123
5556
|
private readonly maxmem;
|
|
4124
|
-
constructor(options: ResolvedOptions);
|
|
5557
|
+
constructor(options: ResolvedOptions, breachChecker: IPasswordBreachChecker);
|
|
4125
5558
|
/**
|
|
4126
5559
|
* Hashes a plaintext password using scrypt with a random salt.
|
|
4127
5560
|
*
|
|
@@ -4134,7 +5567,43 @@ declare class PasswordService {
|
|
|
4134
5567
|
* // 'scrypt:4a3b...:{128 hex chars}'
|
|
4135
5568
|
* ```
|
|
4136
5569
|
*/
|
|
5570
|
+
/**
|
|
5571
|
+
* Rejects a password that appears in a known-breach corpus.
|
|
5572
|
+
*
|
|
5573
|
+
* Called wherever a password is being *set* — registration, reset, invitation acceptance —
|
|
5574
|
+
* and never on login: refusing a breached password someone already has would lock them out
|
|
5575
|
+
* of the account they need to get into to change it.
|
|
5576
|
+
*
|
|
5577
|
+
* The checker fails open by contract — {@link IPasswordBreachChecker.isBreached} is
|
|
5578
|
+
* documented to answer `false`, never throw, when the corpus cannot be consulted — so an
|
|
5579
|
+
* unreachable corpus admits the password rather than blocking the credential path.
|
|
5580
|
+
*
|
|
5581
|
+
* That contract is enforced here rather than assumed. The implementation is the consumer's:
|
|
5582
|
+
* a `fetch` that rejects outside their own `try`, a client library that throws on a DNS
|
|
5583
|
+
* failure, or an ordinary bug is enough to break it, and the exception would propagate out of
|
|
5584
|
+
* every path that *sets* a password. Registration, reset and invitation acceptance would all
|
|
5585
|
+
* start failing because an advisory corpus was unreachable — the exact inversion of the
|
|
5586
|
+
* documented behaviour, and worst during an incident, when changing the password is the
|
|
5587
|
+
* urgent thing. A refusal to answer is not evidence against the password.
|
|
5588
|
+
*
|
|
5589
|
+
* The plaintext is never passed to the logger; only the checker's own error is.
|
|
5590
|
+
*
|
|
5591
|
+
* @param plain - The plaintext password the user is trying to set.
|
|
5592
|
+
* @throws {@link AuthException} with `PASSWORD_COMPROMISED` when the corpus knows it.
|
|
5593
|
+
*/
|
|
5594
|
+
assertNotCompromised(plain: string): Promise<void>;
|
|
4137
5595
|
hash(plain: string): Promise<string>;
|
|
5596
|
+
/**
|
|
5597
|
+
* Whether a stored hash was written under weaker parameters than the ones configured now.
|
|
5598
|
+
*
|
|
5599
|
+
* A `true` here is what drives the transparent upgrade on the login path: the password has
|
|
5600
|
+
* just been proven, so it can be re-derived at the current cost and the stronger hash stored,
|
|
5601
|
+
* without the user doing anything.
|
|
5602
|
+
*
|
|
5603
|
+
* @param hash - The stored hash.
|
|
5604
|
+
* @returns `true` when the hash should be rewritten at the current parameters.
|
|
5605
|
+
*/
|
|
5606
|
+
needsRehash(hash: string): boolean;
|
|
4138
5607
|
/**
|
|
4139
5608
|
* Verifies a plaintext password against a stored scrypt hash.
|
|
4140
5609
|
*
|
|
@@ -4149,6 +5618,25 @@ declare class PasswordService {
|
|
|
4149
5618
|
* without revealing the reason (invalid hash vs. wrong password).
|
|
4150
5619
|
*/
|
|
4151
5620
|
compare(plain: string, hash: string): Promise<boolean>;
|
|
5621
|
+
/**
|
|
5622
|
+
* Runs a full scrypt derivation against a fixed decoy hash and always returns
|
|
5623
|
+
* `false`.
|
|
5624
|
+
*
|
|
5625
|
+
* @returns Always `false`.
|
|
5626
|
+
*
|
|
5627
|
+
* @remarks
|
|
5628
|
+
* Call this on the login "user not found" (or "no local password") branch,
|
|
5629
|
+
* where there is no stored hash to compare against, so the request spends the
|
|
5630
|
+
* same CPU time as a real wrong-password comparison before failing. Without it,
|
|
5631
|
+
* an unknown e-mail returns before any hashing (~single-digit ms) while a known
|
|
5632
|
+
* e-mail runs scrypt (~tens of ms) — a reliable timing oracle an attacker uses
|
|
5633
|
+
* to enumerate which accounts exist despite an identical error message.
|
|
5634
|
+
*
|
|
5635
|
+
* The cost is bounded to a single scrypt derivation (identical to a normal
|
|
5636
|
+
* failed login), so it adds no amplification beyond what a valid-e-mail wrong-
|
|
5637
|
+
* password request already costs; pair it with route-level rate limiting.
|
|
5638
|
+
*/
|
|
5639
|
+
compareDummy(plain: string): Promise<boolean>;
|
|
4152
5640
|
}
|
|
4153
5641
|
|
|
4154
5642
|
/**
|
|
@@ -4189,6 +5677,8 @@ interface SessionInfo {
|
|
|
4189
5677
|
* This service is responsible only for session creation and enforcement.
|
|
4190
5678
|
* Session listing, individual revocation, and bulk-revocation are handled
|
|
4191
5679
|
* by dedicated session-management services.
|
|
5680
|
+
*
|
|
5681
|
+
* @layer Service
|
|
4192
5682
|
*/
|
|
4193
5683
|
declare class SessionService {
|
|
4194
5684
|
private readonly options;
|
|
@@ -4251,6 +5741,31 @@ declare class SessionService {
|
|
|
4251
5741
|
* @throws {@link AuthException} `SESSION_NOT_FOUND` when the session is not owned by the user.
|
|
4252
5742
|
*/
|
|
4253
5743
|
revokeSession(userId: string, sessionHash: string): Promise<void>;
|
|
5744
|
+
/**
|
|
5745
|
+
* Revokes one named session **other than the caller's own**, and cuts the access tokens with
|
|
5746
|
+
* it.
|
|
5747
|
+
*
|
|
5748
|
+
* Distinct from {@link revokeSession}, which is the primitive: deleting the refresh session
|
|
5749
|
+
* stops rotation but says nothing about the stateless access token that session's holder is
|
|
5750
|
+
* already carrying, and that token keeps working until it expires. Someone who opens their
|
|
5751
|
+
* session list and revokes a device does so because they think it is compromised — a decision
|
|
5752
|
+
* about *right now*, not about the next fifteen minutes. The same argument
|
|
5753
|
+
* {@link revokeAllExceptCurrent} makes in its own JSDoc applies to revoking one.
|
|
5754
|
+
*
|
|
5755
|
+
* The epoch is the only lever available: a session hash does not name the `jti` of any access
|
|
5756
|
+
* token, so there is nothing to blacklist individually. Bumping it ends every access token
|
|
5757
|
+
* the account holds, and the user's *other* devices silently re-mint one on their next
|
|
5758
|
+
* rotation — they still hold live refresh sessions. The revoked device cannot, which is the
|
|
5759
|
+
* point.
|
|
5760
|
+
*
|
|
5761
|
+
* `logout` deliberately keeps using the primitive: it blacklists its own `jti` by name, and
|
|
5762
|
+
* ending one session must not sign the account out of every other device's access token.
|
|
5763
|
+
*
|
|
5764
|
+
* @param userId - Internal user ID who owns the session.
|
|
5765
|
+
* @param sessionHash - SHA-256 hash of the refresh token identifying the session.
|
|
5766
|
+
* @throws {@link AuthException} `SESSION_NOT_FOUND` when the session is not owned by the user.
|
|
5767
|
+
*/
|
|
5768
|
+
revokeOtherSession(userId: string, sessionHash: string): Promise<void>;
|
|
4254
5769
|
/**
|
|
4255
5770
|
* Revokes all sessions for a user except the caller's current session.
|
|
4256
5771
|
*
|
|
@@ -4258,8 +5773,25 @@ declare class SessionService {
|
|
|
4258
5773
|
* {@link revokeSession} for each session whose hash differs from
|
|
4259
5774
|
* `currentSessionHash`. The current session is always preserved.
|
|
4260
5775
|
*
|
|
5776
|
+
* The user's token epoch is advanced as part of this, which is what makes the revocation
|
|
5777
|
+
* take effect *now* rather than whenever each device's access token happens to expire.
|
|
5778
|
+
* Deleting a refresh session stops that device rotating, but its already-issued access token
|
|
5779
|
+
* is stateless and keeps verifying for the rest of its lifetime — up to `jwt.accessExpiresIn`
|
|
5780
|
+
* of continued access on a device the user just told the system to sign out. Someone who
|
|
5781
|
+
* clicks "sign out my other devices" because they think one is compromised is making a
|
|
5782
|
+
* statement about right now.
|
|
5783
|
+
*
|
|
5784
|
+
* The caller's own access token is invalidated too — the epoch is per user, not per session —
|
|
5785
|
+
* but the caller is the one party who can recover instantly: their refresh session is
|
|
5786
|
+
* deliberately preserved, so the next request refreshes and continues. The revoked devices
|
|
5787
|
+
* cannot, having lost the refresh token that would let them. Clients using the library's
|
|
5788
|
+
* silent-refresh flow absorb this without the user noticing; a client that does not will see
|
|
5789
|
+
* one 401 and must refresh.
|
|
5790
|
+
*
|
|
4261
5791
|
* @param userId - Internal user ID whose other sessions are being revoked.
|
|
4262
5792
|
* @param currentSessionHash - SHA-256 hash of the session to preserve.
|
|
5793
|
+
* @throws {unknown} Propagates any error thrown by `revokeSession` — including
|
|
5794
|
+
* {@link AuthException} with various codes, Redis errors, or other runtime errors.
|
|
4263
5795
|
*/
|
|
4264
5796
|
revokeAllExceptCurrent(userId: string, currentSessionHash: string): Promise<void>;
|
|
4265
5797
|
/**
|
|
@@ -4330,7 +5862,16 @@ declare class SessionService {
|
|
|
4330
5862
|
*
|
|
4331
5863
|
* When `options.sessions.maxSessionsResolver` is configured, it is called with
|
|
4332
5864
|
* the full user record. Falls back to `options.sessions.defaultMaxSessions` if
|
|
4333
|
-
* the resolver is absent, the user cannot be found,
|
|
5865
|
+
* the resolver is absent, the user cannot be found, the resolver throws, or it answers
|
|
5866
|
+
* with something that is not a usable limit.
|
|
5867
|
+
*
|
|
5868
|
+
* That last case is the one that mattered. The resolver is the host's code and its return
|
|
5869
|
+
* value went straight into the eviction arithmetic, where `NaN` — the result of, say,
|
|
5870
|
+
* `Number(user.plan.maxSessions)` against a column that is missing — quietly disabled the cap
|
|
5871
|
+
* altogether: `length <= NaN` is `false`, so eviction was entered, `length - NaN` is `NaN`,
|
|
5872
|
+
* and `slice(0, NaN)` is empty, so nothing was evicted and every call path still reported
|
|
5873
|
+
* success. A negative value evicted every other session on each login instead. Only a
|
|
5874
|
+
* *thrown* resolver was ever caught.
|
|
4334
5875
|
*
|
|
4335
5876
|
* @param userId - Internal user ID to resolve the limit for.
|
|
4336
5877
|
* @returns Maximum allowed concurrent sessions for the given user.
|
|
@@ -4346,17 +5887,20 @@ declare class SessionService {
|
|
|
4346
5887
|
* - Access tokens: short-lived JWTs signed with HS256
|
|
4347
5888
|
* - Refresh tokens: opaque UUID v4 stored as `rt:{sha256(token)}` in Redis
|
|
4348
5889
|
* - Rotation: atomic Lua script prevents race conditions during token reuse
|
|
4349
|
-
* - MFA temp tokens: short-lived JWTs for the MFA challenge
|
|
5890
|
+
* - MFA temp tokens: short-lived JWTs for the MFA challenge flow, consumed on use
|
|
4350
5891
|
*
|
|
4351
5892
|
* All Redis keys are prefixed by {@link AuthRedisService} — this service uses
|
|
4352
5893
|
* application-level key names without the namespace prefix.
|
|
5894
|
+
*
|
|
5895
|
+
* @layer Service
|
|
4353
5896
|
*/
|
|
4354
5897
|
declare class TokenManagerService {
|
|
4355
5898
|
private readonly jwtService;
|
|
4356
5899
|
private readonly options;
|
|
4357
5900
|
private readonly redis;
|
|
5901
|
+
private readonly hooks;
|
|
4358
5902
|
private readonly logger;
|
|
4359
|
-
constructor(jwtService: JwtService, options: ResolvedOptions, redis: AuthRedisService);
|
|
5903
|
+
constructor(jwtService: JwtService, options: ResolvedOptions, redis: AuthRedisService, hooks: IAuthHooks | null);
|
|
4360
5904
|
/**
|
|
4361
5905
|
* Issues a signed JWT access token for a dashboard user.
|
|
4362
5906
|
*
|
|
@@ -4382,6 +5926,20 @@ declare class TokenManagerService {
|
|
|
4382
5926
|
* At runtime the value is always a valid `ms` string — the cast is safe.
|
|
4383
5927
|
*/
|
|
4384
5928
|
private accessSignOptions;
|
|
5929
|
+
/**
|
|
5930
|
+
* The `iss`/`aud` pair to stamp and to require, or nothing when the deployment configured
|
|
5931
|
+
* neither.
|
|
5932
|
+
*
|
|
5933
|
+
* Spread into both the sign and the verify options so the two can never disagree — a token
|
|
5934
|
+
* stamped with an issuer the verifier does not require, or required where none is stamped,
|
|
5935
|
+
* is a deployment that rejects its own tokens.
|
|
5936
|
+
*
|
|
5937
|
+
* Absent by default. With HS256 the verifier can also sign, so audience binding is what
|
|
5938
|
+
* stops a token minted for one service being replayed at another that trusts the same
|
|
5939
|
+
* secret; it is opt-in because enabling it on one backend of a shared deployment and not the
|
|
5940
|
+
* other splits them apart.
|
|
5941
|
+
*/
|
|
5942
|
+
private issuerAudience;
|
|
4385
5943
|
/**
|
|
4386
5944
|
* Issues access + refresh tokens for a successfully authenticated dashboard user.
|
|
4387
5945
|
*
|
|
@@ -4414,17 +5972,41 @@ declare class TokenManagerService {
|
|
|
4414
5972
|
mfaVerified?: boolean;
|
|
4415
5973
|
}): Promise<PlatformAuthResult>;
|
|
4416
5974
|
/**
|
|
4417
|
-
*
|
|
5975
|
+
* Writes the per-session detail record for a platform session under `psd:{hash}`.
|
|
5976
|
+
*
|
|
5977
|
+
* The dashboard plane gets the equivalent `sd:{hash}` record from {@link SessionService},
|
|
5978
|
+
* but platform sessions never had one, so a session listing had nothing to describe them
|
|
5979
|
+
* with. The field set and the Unix-millisecond timestamps mirror the dashboard record
|
|
5980
|
+
* exactly, so either backend sharing this Redis reads the same shape.
|
|
5981
|
+
*
|
|
5982
|
+
* @param tokenHash - SHA-256 of the raw refresh token; the key's `{hash}` segment.
|
|
5983
|
+
* @param ip - Client IP, truncated before storage against oversized forwarded values.
|
|
5984
|
+
* @param userAgent - Raw User-Agent, stored as the device description.
|
|
5985
|
+
* @param ttl - Record lifetime in seconds; matches the refresh session it describes.
|
|
5986
|
+
*/
|
|
5987
|
+
private writePlatformSessionDetail;
|
|
5988
|
+
/**
|
|
5989
|
+
* Atomically rotates a dashboard refresh token, detecting reuse of a consumed one.
|
|
4418
5990
|
*
|
|
4419
|
-
*
|
|
4420
|
-
* the
|
|
4421
|
-
*
|
|
5991
|
+
* One Lua script consumes the live session, writes the new one and the grace pointer, and
|
|
5992
|
+
* moves the family bookkeeping — so a crash can never leave a token consumed without its
|
|
5993
|
+
* successor and its reuse marker in place. The script reports which of four things the
|
|
5994
|
+
* presented token was:
|
|
4422
5995
|
*
|
|
4423
|
-
*
|
|
4424
|
-
*
|
|
4425
|
-
*
|
|
4426
|
-
*
|
|
4427
|
-
*
|
|
5996
|
+
* - **live** — the normal rotation;
|
|
5997
|
+
* - **inside the grace window** — a concurrent retry of a token that was just rotated away,
|
|
5998
|
+
* served with a fresh session and no new grace pointer;
|
|
5999
|
+
* - **consumed, past its grace window** — the RFC 6819 theft signal. The whole family (every
|
|
6000
|
+
* live descendant of that login) is revoked and the request is rejected. Deliberately
|
|
6001
|
+
* narrower than the old "revoke every session the user has": a theft no longer logs the
|
|
6002
|
+
* user's other legitimate devices out (the OWASP-recommended behaviour, and what
|
|
6003
|
+
* rust-auth does);
|
|
6004
|
+
* - **never issued** — a plain invalid string; nothing is revoked.
|
|
6005
|
+
*
|
|
6006
|
+
* The live record is read once before the script so the new record can inherit its family
|
|
6007
|
+
* (the script needs the family id to plant `cf:`/`fam:`). That read is non-destructive and
|
|
6008
|
+
* cannot double-spend: the script re-reads and deletes the old key itself, so a concurrent
|
|
6009
|
+
* rotation still finds the key gone and falls to the grace path.
|
|
4428
6010
|
*
|
|
4429
6011
|
* @param oldRefresh - The raw refresh token being exchanged.
|
|
4430
6012
|
* @param ip - Client IP address for session audit.
|
|
@@ -4436,18 +6018,62 @@ declare class TokenManagerService {
|
|
|
4436
6018
|
*/
|
|
4437
6019
|
reissueTokens(oldRefresh: string, ip: string, userAgent: string): Promise<RotatedTokenResult>;
|
|
4438
6020
|
/**
|
|
4439
|
-
*
|
|
6021
|
+
* Refuses a rotation once the login it descends from has outlived the absolute cap.
|
|
4440
6022
|
*
|
|
4441
|
-
*
|
|
4442
|
-
*
|
|
4443
|
-
* the
|
|
6023
|
+
* `refreshExpiresInDays` bounds a single refresh token, not a session: a client rotating
|
|
6024
|
+
* every fifteen minutes renews that lifetime forever, so without this a session established
|
|
6025
|
+
* once never has to be established again. The cap measures from the **family's** birth, which
|
|
6026
|
+
* is carried unchanged through the lineage.
|
|
6027
|
+
*
|
|
6028
|
+
* A session with no birth time predates the field and is not capped — it ages out under the
|
|
6029
|
+
* refresh lifetime like any other. A cap of `0` disables the check entirely.
|
|
6030
|
+
*
|
|
6031
|
+
* @param session - The presented session, or the placeholder when the token is not live.
|
|
6032
|
+
* @throws {@link AuthException} with `REFRESH_TOKEN_INVALID` once the cap is passed. The
|
|
6033
|
+
* caller cannot distinguish this from any other invalid refresh, which is deliberate: the
|
|
6034
|
+
* remedy is the same (sign in again) and the difference would only tell a holder of a
|
|
6035
|
+
* stolen token how old the account's session is.
|
|
6036
|
+
*/
|
|
6037
|
+
/**
|
|
6038
|
+
* Emits {@link IAuthHooks.onRefreshTokenReuseDetected}, fire-and-forget.
|
|
6039
|
+
*
|
|
6040
|
+
* The owner is read from the stored session where it can be — a replay of a token whose live
|
|
6041
|
+
* key is already gone leaves nothing to read, and the hook is skipped rather than fired with
|
|
6042
|
+
* an empty identity that a consumer would have to guess about.
|
|
6043
|
+
*/
|
|
6044
|
+
private emitReuseDetected;
|
|
6045
|
+
private assertWithinAbsoluteLifetime;
|
|
6046
|
+
/**
|
|
6047
|
+
* Reads the presented token's live record to seed the rotated one.
|
|
6048
|
+
*
|
|
6049
|
+
* The rotation script plants the family bookkeeping in the same step that consumes the old
|
|
6050
|
+
* token, so it needs the family id up front — which lives in the old record. When the live
|
|
6051
|
+
* key is already gone the rotation can only end in grace/reuse/invalid, none of which store
|
|
6052
|
+
* the record being built here, so an empty placeholder is returned rather than failing early.
|
|
6053
|
+
*
|
|
6054
|
+
* @param sessionKey - The `rt:`/`prt:` key of the presented token.
|
|
6055
|
+
* @param ip - Client IP, carried into the placeholder so its every field is the real one.
|
|
6056
|
+
* @param userAgent - User-Agent, carried into the placeholder for the same reason.
|
|
6057
|
+
* @returns The parsed live record, or an empty-identity placeholder when the key is gone.
|
|
6058
|
+
*/
|
|
6059
|
+
private readSeedSession;
|
|
6060
|
+
/**
|
|
6061
|
+
* Handles the primary rotation path: the presented token was live and is now consumed.
|
|
6062
|
+
*
|
|
6063
|
+
* The rotation script wrote `rt:{new}`, the grace pointer, the family bookkeeping **and**
|
|
6064
|
+
* the per-user session index. The index moved inside the script because doing it here left
|
|
6065
|
+
* a window between the consume and the SADD in which "log out everywhere" could sweep the
|
|
6066
|
+
* index without seeing the session this rotation had just minted — leaving it alive, and
|
|
6067
|
+
* rotating, after a revocation the user was told had happened.
|
|
6068
|
+
*
|
|
6069
|
+
* What is left here is issuing the token pair.
|
|
4444
6070
|
*/
|
|
4445
6071
|
private rotateFromPrimary;
|
|
4446
6072
|
/**
|
|
4447
6073
|
* Handles the grace-window rotation path: old session gone but grace pointer found.
|
|
4448
6074
|
*
|
|
4449
6075
|
* Issues a new session but **does NOT** create another grace pointer. A grace
|
|
4450
|
-
* rotation is the terminal
|
|
6076
|
+
* rotation is the terminal operation of one rotation cycle — chaining grace pointers
|
|
4451
6077
|
* would allow an attacker who captured a refresh token to indefinitely keep a
|
|
4452
6078
|
* session alive by consuming consecutive grace windows, each one producing a
|
|
4453
6079
|
* fresh grace pointer.
|
|
@@ -4455,6 +6081,10 @@ declare class TokenManagerService {
|
|
|
4455
6081
|
* Concurrent legitimate retries are served by the primary `rt:` session; the
|
|
4456
6082
|
* grace pointer exists only to cover the narrow window in which the old token
|
|
4457
6083
|
* was already consumed but the client has not yet received the new one.
|
|
6084
|
+
*
|
|
6085
|
+
* The recovered session keeps its family, and the fresh hash joins the family index, so a
|
|
6086
|
+
* session born from a grace recovery stays revocable with the rest of its lineage. The
|
|
6087
|
+
* script has already refused the recovery if that family was revoked in the meantime.
|
|
4458
6088
|
*/
|
|
4459
6089
|
private rotateFromGrace;
|
|
4460
6090
|
/**
|
|
@@ -4467,7 +6097,28 @@ declare class TokenManagerService {
|
|
|
4467
6097
|
* or missing required `userId` / `role` fields.
|
|
4468
6098
|
*/
|
|
4469
6099
|
private parseSession;
|
|
4470
|
-
/**
|
|
6100
|
+
/**
|
|
6101
|
+
* Serializes a session record for storage, omitting an empty `familyId`.
|
|
6102
|
+
*
|
|
6103
|
+
* rust-auth skips the field when empty (`skip_serializing_if`), so emitting `"familyId":""`
|
|
6104
|
+
* here would make the same session serialize to different bytes on each side and break the
|
|
6105
|
+
* shared-Redis contract. A record with no family simply has no key.
|
|
6106
|
+
*
|
|
6107
|
+
* @param session - The record to store.
|
|
6108
|
+
* @returns The JSON string written under an `rt:`/`prt:` key.
|
|
6109
|
+
*/
|
|
6110
|
+
private serializeSession;
|
|
6111
|
+
/**
|
|
6112
|
+
* Constructs a session record from identity fields and request metadata.
|
|
6113
|
+
*
|
|
6114
|
+
* @param userId - Internal user ID for whom the session is being created.
|
|
6115
|
+
* @param tenantId - Tenant ID scoping the session. Empty string for platform admin sessions.
|
|
6116
|
+
* @param role - Role claim to persist in the session record.
|
|
6117
|
+
* @param ip - Client IP address for session audit metadata.
|
|
6118
|
+
* @param device - Human-readable device description (parsed from User-Agent).
|
|
6119
|
+
* @param mfaEnabled - Whether MFA is enabled on the account at session creation time.
|
|
6120
|
+
* @param familyId - Login lineage this session belongs to; `''` when it belongs to none.
|
|
6121
|
+
*/
|
|
4471
6122
|
private buildSession;
|
|
4472
6123
|
/**
|
|
4473
6124
|
* Issues an access token and assembles a {@link RotatedTokenResult} from a session record.
|
|
@@ -4522,6 +6173,28 @@ declare class TokenManagerService {
|
|
|
4522
6173
|
* Platform admins must re-complete the MFA challenge flow to re-acquire a verified token.
|
|
4523
6174
|
*/
|
|
4524
6175
|
private buildPlatformRotatedResult;
|
|
6176
|
+
/**
|
|
6177
|
+
* Re-signs a rotated platform access token with the authority the administrator holds *now*.
|
|
6178
|
+
*
|
|
6179
|
+
* The platform twin of the re-stamp the dashboard plane performs inline after its own
|
|
6180
|
+
* account re-read. Platform rotation builds its claims from the `prt:` record written at
|
|
6181
|
+
* login, so the role and MFA flag it carries are the ones the admin had then, inherited
|
|
6182
|
+
* unchanged through every later rotation. Demoting a `super_admin` to `support` therefore had
|
|
6183
|
+
* no effect on a live console session: it kept minting tokens carrying the old authority for
|
|
6184
|
+
* the refresh token's whole lifetime, and every role check reads that claim — on the
|
|
6185
|
+
* highest-privilege identity in the system. The dashboard plane closed this; the platform
|
|
6186
|
+
* plane was left with the identical hole.
|
|
6187
|
+
*
|
|
6188
|
+
* Everything the rotated token already established is kept, including `mfaVerified`: a second
|
|
6189
|
+
* factor already cleared on this session must not be silently demanded again. A fresh `jti`,
|
|
6190
|
+
* window and epoch are issued — the token this replaces was never handed out.
|
|
6191
|
+
*
|
|
6192
|
+
* @param claims - The claims of the token rotation just produced.
|
|
6193
|
+
* @param role - The administrator's current role.
|
|
6194
|
+
* @param mfaEnabled - Whether the administrator currently has a second factor.
|
|
6195
|
+
* @returns The re-signed platform access token.
|
|
6196
|
+
*/
|
|
6197
|
+
reissuePlatformAccessWithAuthority(claims: PlatformJwtPayload, role: string, mfaEnabled: boolean): Promise<string>;
|
|
4525
6198
|
/**
|
|
4526
6199
|
* Decodes a JWT without validating its expiration or signature.
|
|
4527
6200
|
*
|
|
@@ -4536,6 +6209,34 @@ declare class TokenManagerService {
|
|
|
4536
6209
|
* @throws {@link AuthException} with `TOKEN_INVALID` if the payload is not an
|
|
4537
6210
|
* object or lacks required `jti` (string) and `sub` (string) claims.
|
|
4538
6211
|
*/
|
|
6212
|
+
/**
|
|
6213
|
+
* Verifies an access token's signature under the pinned algorithm while **ignoring its
|
|
6214
|
+
* expiry**, returning the payload.
|
|
6215
|
+
*
|
|
6216
|
+
* Exactly one caller wants this: logout. An access token that expired while the user was
|
|
6217
|
+
* away is the normal case there, and refusing the request would leave the refresh session —
|
|
6218
|
+
* the long-lived credential logout exists to kill — alive for its whole lifetime. But the
|
|
6219
|
+
* signature still has to hold: the payload's `jti` decides which token gets blacklisted, so
|
|
6220
|
+
* reading it unverified would let a caller revoke an access token they do not own by naming
|
|
6221
|
+
* its id. Retired signing secrets are accepted, as everywhere else.
|
|
6222
|
+
*
|
|
6223
|
+
* @param token - The raw access token.
|
|
6224
|
+
* @returns The verified payload, expiry aside.
|
|
6225
|
+
* @throws Whatever the verifier throws when no configured secret accepts the token.
|
|
6226
|
+
*/
|
|
6227
|
+
verifyIgnoringExpiry(token: string): DashboardJwtPayload;
|
|
6228
|
+
/**
|
|
6229
|
+
* The platform twin of {@link verifyIgnoringExpiry}, for the same single caller: logout.
|
|
6230
|
+
*
|
|
6231
|
+
* An operator who walks away for longer than the access-token lifetime and then signs out is
|
|
6232
|
+
* the ordinary case, and refusing them leaves the refresh session — seven days of the
|
|
6233
|
+
* highest-privilege identity in the system — alive on a console they believed they had left.
|
|
6234
|
+
*
|
|
6235
|
+
* @param token - The raw platform access token.
|
|
6236
|
+
* @returns The verified payload, expiry aside.
|
|
6237
|
+
* @throws Whatever the verifier throws when no configured secret accepts the token.
|
|
6238
|
+
*/
|
|
6239
|
+
verifyPlatformIgnoringExpiry(token: string): PlatformJwtPayload;
|
|
4539
6240
|
decodeToken(token: string): DashboardJwtPayload | PlatformJwtPayload | MfaTempPayload;
|
|
4540
6241
|
/**
|
|
4541
6242
|
* Issues a short-lived MFA challenge token and stores it in Redis for
|
|
@@ -4581,7 +6282,8 @@ declare class TokenManagerService {
|
|
|
4581
6282
|
* `jti` to {@link consumeMfaTempToken} after TOTP validation succeeds.
|
|
4582
6283
|
* @throws {@link AuthException} with `MFA_TEMP_TOKEN_INVALID` if the
|
|
4583
6284
|
* Redis entry is missing (already consumed, expired, or never issued).
|
|
4584
|
-
* @throws
|
|
6285
|
+
* @throws {Error} When JWT signature or expiry validation fails (propagated
|
|
6286
|
+
* directly from `JwtService.verify()` — not wrapped in {@link AuthException}).
|
|
4585
6287
|
*/
|
|
4586
6288
|
verifyMfaTempToken(token: string): Promise<{
|
|
4587
6289
|
userId: string;
|
|
@@ -4600,7 +6302,7 @@ declare class TokenManagerService {
|
|
|
4600
6302
|
*
|
|
4601
6303
|
* @param jti - The `jti` claim returned by {@link verifyMfaTempToken}.
|
|
4602
6304
|
*/
|
|
4603
|
-
consumeMfaTempToken(jti: string): Promise<
|
|
6305
|
+
consumeMfaTempToken(jti: string): Promise<boolean>;
|
|
4604
6306
|
}
|
|
4605
6307
|
|
|
4606
6308
|
/**
|
|
@@ -4614,6 +6316,8 @@ declare class TokenManagerService {
|
|
|
4614
6316
|
* @remarks
|
|
4615
6317
|
* Hook errors from `after*` and `on*` hooks are caught and logged — they must
|
|
4616
6318
|
* never propagate to the caller. Only `beforeRegister` can block the flow.
|
|
6319
|
+
*
|
|
6320
|
+
* @layer Service
|
|
4617
6321
|
*/
|
|
4618
6322
|
declare class AuthService {
|
|
4619
6323
|
private readonly options;
|
|
@@ -4627,7 +6331,48 @@ declare class AuthService {
|
|
|
4627
6331
|
private readonly otpService;
|
|
4628
6332
|
private readonly sessionService;
|
|
4629
6333
|
private readonly logger;
|
|
6334
|
+
/**
|
|
6335
|
+
* Whether the tenant-mismatch misconfiguration has already been reported.
|
|
6336
|
+
*
|
|
6337
|
+
* The warning describes a permanent property of the deployment — a repository whose
|
|
6338
|
+
* `findByEmail` ignores its `tenantId` argument — so the second line and every line after it
|
|
6339
|
+
* carry no information the first did not. Emitting one per request would make the log a
|
|
6340
|
+
* function of traffic, and put a side effect on the losing side of a refusal that is meant to
|
|
6341
|
+
* be indistinguishable from the other two. Once is enough to make the defect visible.
|
|
6342
|
+
*/
|
|
6343
|
+
private warnedTenantMismatch;
|
|
4630
6344
|
constructor(options: ResolvedOptions, userRepo: IUserRepository, emailProvider: IEmailProvider | null, hooks: IAuthHooks | null, passwordService: PasswordService, tokenManager: TokenManagerService, bruteForce: BruteForceService, redis: AuthRedisService, otpService: OtpService, sessionService: SessionService);
|
|
6345
|
+
/**
|
|
6346
|
+
* Re-derive a proven password at the current parameters and store it.
|
|
6347
|
+
*
|
|
6348
|
+
* Detached from the login it follows: the user is already authenticated, and a failure here
|
|
6349
|
+
* costs nothing but the upgrade — the old hash keeps working. Errors are logged rather than
|
|
6350
|
+
* propagated for that reason.
|
|
6351
|
+
*
|
|
6352
|
+
* **`verifiedHash` is what makes this safe to detach.** The task carries the plaintext of the
|
|
6353
|
+
* password it is upgrading, and a KDF derivation is slow by construction, so it lands some
|
|
6354
|
+
* time after the login that scheduled it. In between, the same account may have changed its
|
|
6355
|
+
* password — and the case where that is most likely is exactly the dangerous one: the user
|
|
6356
|
+
* resets *because* the old password was compromised, and the attacker's own login is what
|
|
6357
|
+
* scheduled the task. Writing unconditionally then re-installs the compromised credential
|
|
6358
|
+
* over the new one, the old password works again, the new one does not, and the "password
|
|
6359
|
+
* changed" mail has already gone out. The window is the whole rehash, and `needsRehash` is
|
|
6360
|
+
* true for EVERY account during the parameter migration this feature exists to serve, so it
|
|
6361
|
+
* is not a rare alignment.
|
|
6362
|
+
*
|
|
6363
|
+
* So the write is conditional on the stored hash still being the one that was verified. This
|
|
6364
|
+
* is a re-read rather than a compare-and-set because `IUserRepository` is implemented by the
|
|
6365
|
+
* consuming application and a CAS primitive cannot be required of every backing store; the
|
|
6366
|
+
* remaining race is the repository round-trip rather than the derivation, and it can only
|
|
6367
|
+
* lose an upgrade, never a password — the next login reschedules it.
|
|
6368
|
+
*
|
|
6369
|
+
* @param userId - The account whose stored hash is being upgraded.
|
|
6370
|
+
* @param tenantId - The tenant that account belongs to, so the re-read cannot answer with a
|
|
6371
|
+
* different tenant's row in a store whose ids are not globally unique.
|
|
6372
|
+
* @param plain - The plaintext just verified against `verifiedHash`.
|
|
6373
|
+
* @param verifiedHash - The stored hash this upgrade is allowed to replace.
|
|
6374
|
+
*/
|
|
6375
|
+
private rehashPassword;
|
|
4631
6376
|
/**
|
|
4632
6377
|
* Registers a new dashboard user.
|
|
4633
6378
|
*
|
|
@@ -4664,11 +6409,26 @@ declare class AuthService {
|
|
|
4664
6409
|
/**
|
|
4665
6410
|
* Logs out a dashboard user by revoking the access token and deleting the refresh session.
|
|
4666
6411
|
*
|
|
4667
|
-
*
|
|
6412
|
+
* The route is deliberately **not** behind the access-token guard. The overwhelmingly
|
|
6413
|
+
* common case is a user who comes back after the 15-minute access token expired and clicks
|
|
6414
|
+
* "sign out": refusing that request leaves the refresh session — the long-lived credential
|
|
6415
|
+
* logout exists to kill — alive for its full lifetime, on a device the user just told the
|
|
6416
|
+
* system to sign out. The refresh token is the credential that authorizes this operation,
|
|
6417
|
+
* and possession of it is what the caller proves.
|
|
6418
|
+
*
|
|
6419
|
+
* The owner is read from the stored session rather than from the access token's claims, so
|
|
6420
|
+
* an absent, expired or forged access token cannot name a different user's session. The
|
|
6421
|
+
* access token is still *verified* (signature and pinned algorithm) before its `jti` is
|
|
6422
|
+
* blacklisted, only skipping the expiry check — reading it unverified would let a caller
|
|
6423
|
+
* blacklist someone else's access token by naming its id.
|
|
6424
|
+
*
|
|
6425
|
+
* @param accessToken - Raw JWT access token. Optional in practice: absent or expired is the
|
|
6426
|
+
* normal case, and only a signature-valid token contributes a blacklist entry.
|
|
4668
6427
|
* @param rawRefreshToken - Raw opaque refresh token (session key is derived from its hash).
|
|
4669
|
-
* @
|
|
6428
|
+
* @returns The id of the user whose session was revoked, or `''` when no live session
|
|
6429
|
+
* matched the presented refresh token (already logged out, or expired).
|
|
4670
6430
|
*/
|
|
4671
|
-
logout(accessToken: string, rawRefreshToken: string
|
|
6431
|
+
logout(accessToken: string, rawRefreshToken: string): Promise<string>;
|
|
4672
6432
|
/**
|
|
4673
6433
|
* Rotates a dashboard refresh token.
|
|
4674
6434
|
*
|
|
@@ -4681,7 +6441,27 @@ declare class AuthService {
|
|
|
4681
6441
|
* @param userAgent - User-Agent header value.
|
|
4682
6442
|
* @returns New tokens and minimal session identity.
|
|
4683
6443
|
*/
|
|
4684
|
-
refresh(oldRefreshToken: string, ip: string, userAgent: string): Promise<
|
|
6444
|
+
refresh(oldRefreshToken: string, ip: string, userAgent: string): Promise<DashboardRefreshResult>;
|
|
6445
|
+
/**
|
|
6446
|
+
* Ends every dashboard session for one account, and kills the access tokens already issued.
|
|
6447
|
+
*
|
|
6448
|
+
* The dashboard twin of {@link PlatformAuthService.revokeAllPlatformSessions}. It exists
|
|
6449
|
+
* because a library cannot see the moment a host suspends, bans, or deletes an account —
|
|
6450
|
+
* the user record is the host's — and until the host says so, the account's live sessions
|
|
6451
|
+
* keep working. ASVS v5 §7.4.2 requires that moment to terminate them, so the host needs a
|
|
6452
|
+
* supported way to say it. `SessionService.revokeAllExceptCurrent` cannot serve: it wants
|
|
6453
|
+
* the hash of a session to keep, and an administrator banning somebody else has none.
|
|
6454
|
+
*
|
|
6455
|
+
* Call it from wherever the account's status changes. Refresh applies the same gate on its
|
|
6456
|
+
* own, so a ban takes effect within one access-token lifetime even if this is never called
|
|
6457
|
+
* — but that is a backstop, not the mechanism.
|
|
6458
|
+
*
|
|
6459
|
+
* The epoch is bumped after the sweep, not before: a failure in the sweep then leaves the
|
|
6460
|
+
* operation visibly incomplete rather than reading as done while the sessions live on.
|
|
6461
|
+
*
|
|
6462
|
+
* @param userId - The account whose sessions are being ended.
|
|
6463
|
+
*/
|
|
6464
|
+
revokeAllSessions(userId: string): Promise<void>;
|
|
4685
6465
|
/**
|
|
4686
6466
|
* Retrieves the full safe user record for the currently authenticated user.
|
|
4687
6467
|
*
|
|
@@ -4751,7 +6531,7 @@ declare class AuthService {
|
|
|
4751
6531
|
* or the user does not exist (response shape is identical to prevent
|
|
4752
6532
|
* account enumeration via this endpoint).
|
|
4753
6533
|
*/
|
|
4754
|
-
verifyEmail(tenantId: string, email: string, otp: string): Promise<void>;
|
|
6534
|
+
verifyEmail(tenantId: string, email: string, otp: string, req: Request): Promise<void>;
|
|
4755
6535
|
/**
|
|
4756
6536
|
* Resends an email verification OTP with an atomic cooldown.
|
|
4757
6537
|
*
|
|
@@ -4762,20 +6542,272 @@ declare class AuthService {
|
|
|
4762
6542
|
* @param tenantId - Tenant scope.
|
|
4763
6543
|
* @param email - The email address to re-send to (not validated — always succeeds).
|
|
4764
6544
|
*/
|
|
4765
|
-
resendVerificationEmail(tenantId: string, email: string): Promise<void>;
|
|
6545
|
+
resendVerificationEmail(tenantId: string, email: string, req: Request): Promise<void>;
|
|
6546
|
+
/**
|
|
6547
|
+
* Clears an account's brute-force lockout so the next attempt is judged on its merits.
|
|
6548
|
+
*
|
|
6549
|
+
* A lockout is a denial of service the library imposes on its own users, and until now it
|
|
6550
|
+
* could only be waited out: the counter is keyed by an HMAC of `{tenantId}:{email}` under
|
|
6551
|
+
* the library's own `hmacKey`, which no consumer can derive, so a support desk facing "I
|
|
6552
|
+
* am locked out and I need in now" had nothing to offer. ASVS v5 §6.1.1 asks for an
|
|
6553
|
+
* administrative path to clear it — and the lockout is also the lever an attacker pulls to
|
|
6554
|
+
* deny service to a specific account, which makes the ability to undo it part of the
|
|
6555
|
+
* defence rather than a convenience.
|
|
6556
|
+
*
|
|
6557
|
+
* **This grants no access.** It restores the ability to *try*: the password, the status
|
|
6558
|
+
* gate, the verification gate and MFA all still apply. Authorising the caller is the
|
|
6559
|
+
* consumer's job — the library deliberately ships no route for this, because who may
|
|
6560
|
+
* unlock whom is a decision only the host application can make.
|
|
6561
|
+
*
|
|
6562
|
+
* Idempotent: unlocking an account that is not locked is a no-op.
|
|
6563
|
+
*
|
|
6564
|
+
* @param email - The account's address. Normalized here the same way login normalizes it,
|
|
6565
|
+
* or the derived key would miss the counter the lockout actually wrote.
|
|
6566
|
+
* @param tenantId - The tenant the account belongs to.
|
|
6567
|
+
*/
|
|
6568
|
+
unlockAccount(email: string, tenantId: string): Promise<void>;
|
|
6569
|
+
/**
|
|
6570
|
+
* The brute-force counter key for a dashboard account.
|
|
6571
|
+
*
|
|
6572
|
+
* The identity PLANE is part of the preimage, not just the tenant. Without it a tenant whose
|
|
6573
|
+
* id is literally `platform` produced a byte-identical identifier to the platform plane's
|
|
6574
|
+
* own `platform:{email}` — so five unauthenticated dashboard logins against an operator's
|
|
6575
|
+
* address locked that operator out of the console, repeatably, without the platform surface
|
|
6576
|
+
* ever being touched. The reverse held too: a successful dashboard login in that tenant
|
|
6577
|
+
* cleared the operator's lockout mid-attack. The MFA counters already carry their plane for
|
|
6578
|
+
* exactly this reason.
|
|
6579
|
+
*
|
|
6580
|
+
* One method rather than two call sites: `login` writes this counter and `unlockAccount`
|
|
6581
|
+
* clears it, and a preimage that drifted between them would make the unlock silently do
|
|
6582
|
+
* nothing — the failure mode is invisible, because clearing a key that does not exist
|
|
6583
|
+
* succeeds.
|
|
6584
|
+
*
|
|
6585
|
+
* @param tenantId - The resolved tenant.
|
|
6586
|
+
* @param email - The address, already normalized by the caller.
|
|
6587
|
+
* @returns The HMAC identifier, opaque and non-reversible.
|
|
6588
|
+
*/
|
|
6589
|
+
/**
|
|
6590
|
+
* Derives the OTP-record identifier for a `tenantId + email` pair.
|
|
6591
|
+
*
|
|
6592
|
+
* HMAC rather than a bare digest because an address is low-entropy: a bare SHA-256 of one is
|
|
6593
|
+
* reversible by dictionary, and these identifiers are the Redis key an operator can read.
|
|
6594
|
+
* The preimage is pinned by `conformance/wire-contract.json` and shared byte-for-byte with
|
|
6595
|
+
* rust-auth, which keys the same records in the same Redis.
|
|
6596
|
+
*
|
|
6597
|
+
* Deliberately distinct from {@link lockoutIdentifier}: that one namespaces the login
|
|
6598
|
+
* keyspace with a `dashboard:` prefix, and the two must never collide.
|
|
6599
|
+
*
|
|
6600
|
+
* @param tenantId - Tenant scope.
|
|
6601
|
+
* @param email - The canonicalized address.
|
|
6602
|
+
* @returns Hex HMAC-SHA-256 identifier.
|
|
6603
|
+
*/
|
|
6604
|
+
private otpIdentifier;
|
|
6605
|
+
private lockoutIdentifier;
|
|
4766
6606
|
private resolveTenantId;
|
|
4767
6607
|
private buildHookContext;
|
|
6608
|
+
/**
|
|
6609
|
+
* Records a failed credential attempt against the brute-force counter, and emits the failure
|
|
6610
|
+
* hooks the moment they are due — including {@link IAuthHooks.onLockout} on the attempt that
|
|
6611
|
+
* crosses the threshold.
|
|
6612
|
+
*
|
|
6613
|
+
* The lockout signal has to be emitted here rather than on the *next* attempt: an attacker
|
|
6614
|
+
* who trips the lock and walks away would otherwise never produce the event, and the account
|
|
6615
|
+
* would sit locked with nothing having announced it.
|
|
6616
|
+
*/
|
|
6617
|
+
private recordLoginFailure;
|
|
6618
|
+
/** Emits {@link IAuthHooks.onLoginFailed}, fire-and-forget. */
|
|
6619
|
+
private emitLoginFailed;
|
|
6620
|
+
/**
|
|
6621
|
+
* Runs a hook without awaiting it and without letting it change the caller's outcome.
|
|
6622
|
+
*
|
|
6623
|
+
* Every hook on this interface is advisory: a consumer's SIEM being down must not turn a
|
|
6624
|
+
* refused login into a different refusal, nor a successful one into a failure.
|
|
6625
|
+
*/
|
|
6626
|
+
private fireAndForget;
|
|
4768
6627
|
private assertUserNotBlocked;
|
|
4769
6628
|
private sendVerificationOtp;
|
|
4770
6629
|
}
|
|
4771
6630
|
|
|
6631
|
+
/**
|
|
6632
|
+
* Data Transfer Object for requesting an address change.
|
|
6633
|
+
*
|
|
6634
|
+
* Validated via NestJS `ValidationPipe` before reaching the service layer.
|
|
6635
|
+
*
|
|
6636
|
+
* @remarks
|
|
6637
|
+
* The account is never named here — it comes from the caller's own claims. A body that could
|
|
6638
|
+
* name a user id would let anyone holding any session move any account's recovery address,
|
|
6639
|
+
* which is account takeover in one field.
|
|
6640
|
+
*
|
|
6641
|
+
* @layer DTO
|
|
6642
|
+
*/
|
|
6643
|
+
declare class ChangeEmailDto {
|
|
6644
|
+
/**
|
|
6645
|
+
* The address to move to. Normalized to lowercase and trimmed so it is compared, stored,
|
|
6646
|
+
* and checked for uniqueness in the same form login resolves an account by.
|
|
6647
|
+
*/
|
|
6648
|
+
newEmail: string;
|
|
6649
|
+
/**
|
|
6650
|
+
* The account's current password.
|
|
6651
|
+
*
|
|
6652
|
+
* Re-proved because the address is the recovery credential: without this, a stolen access
|
|
6653
|
+
* token alone would be enough to point the account at a mailbox the thief controls.
|
|
6654
|
+
* Bounded at 128 to match the hasher's input limit — an unbounded field is a cheap way to
|
|
6655
|
+
* make someone else pay for a key derivation.
|
|
6656
|
+
*/
|
|
6657
|
+
currentPassword: string;
|
|
6658
|
+
}
|
|
6659
|
+
|
|
6660
|
+
/**
|
|
6661
|
+
* Data Transfer Object for confirming an address change.
|
|
6662
|
+
*
|
|
6663
|
+
* Validated via NestJS `ValidationPipe` before reaching the service layer.
|
|
6664
|
+
*
|
|
6665
|
+
* @remarks
|
|
6666
|
+
* The token is the whole payload: it names the account, the target address and the tenant,
|
|
6667
|
+
* all of which were fixed when it was minted. Accepting any of those from the body would let
|
|
6668
|
+
* the holder of one link redirect it at a different account.
|
|
6669
|
+
*
|
|
6670
|
+
* @layer DTO
|
|
6671
|
+
*/
|
|
6672
|
+
declare class ConfirmEmailChangeDto {
|
|
6673
|
+
/**
|
|
6674
|
+
* The single-use token that was mailed to the new address.
|
|
6675
|
+
*
|
|
6676
|
+
* Exactly 64 hex characters — the shape `generateSecureToken(32)` produces. Bounding it
|
|
6677
|
+
* here means a malformed value is refused before it is hashed into a key lookup.
|
|
6678
|
+
*/
|
|
6679
|
+
token: string;
|
|
6680
|
+
}
|
|
6681
|
+
|
|
6682
|
+
/**
|
|
6683
|
+
* Changing the address on an account, in two steps.
|
|
6684
|
+
*
|
|
6685
|
+
* The address is the account's recovery credential: whoever controls it can drive a password
|
|
6686
|
+
* reset to a mailbox the owner does not read. That makes moving it a security operation, not
|
|
6687
|
+
* a profile edit, and it is why the flow costs three things rather than one.
|
|
6688
|
+
*
|
|
6689
|
+
* **The current password is re-proved.** A stolen access token alone cannot move the recovery
|
|
6690
|
+
* address — the thief has to already hold the credential that would let them take the account
|
|
6691
|
+
* anyway.
|
|
6692
|
+
*
|
|
6693
|
+
* **The new address is proved before it is adopted.** A token goes to it and nowhere else, so
|
|
6694
|
+
* a typo cannot lock the owner out of their own account and an attacker cannot point the
|
|
6695
|
+
* account at a mailbox they merely claim.
|
|
6696
|
+
*
|
|
6697
|
+
* **The old address is told.** NIST SP 800-63B §4.6 asks for notification of a credential
|
|
6698
|
+
* change, and this is the one that matters most: it is the last message the owner can receive
|
|
6699
|
+
* at an address they still control, and it is what turns a silent takeover into one they can
|
|
6700
|
+
* see happening.
|
|
6701
|
+
*
|
|
6702
|
+
* @layer Service
|
|
6703
|
+
*/
|
|
6704
|
+
declare class EmailChangeService implements OnModuleInit {
|
|
6705
|
+
private readonly options;
|
|
6706
|
+
private readonly userRepo;
|
|
6707
|
+
private readonly emailProvider;
|
|
6708
|
+
private readonly passwordService;
|
|
6709
|
+
private readonly redis;
|
|
6710
|
+
private readonly bruteForce;
|
|
6711
|
+
private readonly logger;
|
|
6712
|
+
constructor(options: ResolvedOptions, userRepo: IUserRepository, emailProvider: IEmailProvider, passwordService: PasswordService, redis: AuthRedisService, bruteForce: BruteForceService);
|
|
6713
|
+
/**
|
|
6714
|
+
* Refuses to boot when the flow is enabled but the provider cannot deliver its token.
|
|
6715
|
+
*
|
|
6716
|
+
* This service is registered only when `controllers.emailChange` is on, so its presence is
|
|
6717
|
+
* the flow being enabled. Checking at startup rather than on the first request is the
|
|
6718
|
+
* difference between a deployment that fails immediately and one that mints `ec:` keys
|
|
6719
|
+
* nobody ever receives — a failure that looks like success from every side, and that a user
|
|
6720
|
+
* experiences as a verification email that simply never arrives.
|
|
6721
|
+
*
|
|
6722
|
+
* @throws When the configured {@link IEmailProvider} implements no
|
|
6723
|
+
* `sendEmailChangeVerification`.
|
|
6724
|
+
*/
|
|
6725
|
+
onModuleInit(): void;
|
|
6726
|
+
/**
|
|
6727
|
+
* Starts an address change: re-proves the password, then mails a single-use token to the
|
|
6728
|
+
* new address. Nothing about the account changes until that token comes back.
|
|
6729
|
+
*
|
|
6730
|
+
* @param userId - The authenticated caller, from their own claims — never the body.
|
|
6731
|
+
* @param dto - The new address and the current password.
|
|
6732
|
+
* @throws {@link AuthException} `INVALID_CREDENTIALS` when the account has no local password
|
|
6733
|
+
* or the submitted one is wrong — the same code a failed login returns, so a thief holding
|
|
6734
|
+
* an access token learns nothing they did not already know.
|
|
6735
|
+
* @throws {@link AuthException} `EMAIL_ALREADY_EXISTS` when the address is the account's own
|
|
6736
|
+
* or belongs to another account in the tenant.
|
|
6737
|
+
*/
|
|
6738
|
+
requestChange(userId: string, dto: ChangeEmailDto): Promise<void>;
|
|
6739
|
+
/**
|
|
6740
|
+
* Completes an address change against a token that came back from the new address.
|
|
6741
|
+
*
|
|
6742
|
+
* @param dto - The single-use token.
|
|
6743
|
+
* @throws {@link AuthException} `EMAIL_CHANGE_TOKEN_INVALID` when the token is unknown,
|
|
6744
|
+
* expired, already used, malformed, or no longer bound to the account's password.
|
|
6745
|
+
* @throws {@link AuthException} `EMAIL_ALREADY_EXISTS` when the address was taken between
|
|
6746
|
+
* the request and the confirmation.
|
|
6747
|
+
*/
|
|
6748
|
+
confirmChange(dto: ConfirmEmailChangeDto): Promise<void>;
|
|
6749
|
+
/**
|
|
6750
|
+
* Refuses an address the account already has, or that another account in the tenant holds.
|
|
6751
|
+
*
|
|
6752
|
+
* Answering `EMAIL_ALREADY_EXISTS` does disclose that an address is registered — the same
|
|
6753
|
+
* disclosure `register` and invitation acceptance already make, and the same one the caller
|
|
6754
|
+
* could obtain there. Withholding it here would buy nothing while leaving a user who typos
|
|
6755
|
+
* into a colleague's address waiting on a message that never comes, with no way to tell why.
|
|
6756
|
+
*
|
|
6757
|
+
* The account's own current address is refused through the same code: it is a change that
|
|
6758
|
+
* changes nothing, and letting it through would send a verification for a move that is not
|
|
6759
|
+
* happening.
|
|
6760
|
+
*
|
|
6761
|
+
* @param user - The account requesting the change.
|
|
6762
|
+
* @param newEmail - The normalized target address.
|
|
6763
|
+
*/
|
|
6764
|
+
private assertAddressIsFree;
|
|
6765
|
+
/**
|
|
6766
|
+
* Refuses a token whose binding no longer matches the account's password.
|
|
6767
|
+
*
|
|
6768
|
+
* A record with no fingerprint at all predates the binding — a rolling deploy, or a sibling
|
|
6769
|
+
* implementation that has not taken this change — and is accepted, exactly as the reset flow
|
|
6770
|
+
* accepts one: refusing them would break every change in flight for a window this narrow.
|
|
6771
|
+
* The empty string is accepted for the same reason it is written, an account that had no
|
|
6772
|
+
* password when the token was minted.
|
|
6773
|
+
*
|
|
6774
|
+
* Absence is the only tolerated departure from the contract, and it is the only one that can
|
|
6775
|
+
* reach here: anything stored under this name that is not a string fails
|
|
6776
|
+
* {@link isEmailChangeContext} and the token is refused before this runs. It used to be read
|
|
6777
|
+
* as "predates the binding", which turned every corrupted record into a bypass of the
|
|
6778
|
+
* property this method exists to enforce.
|
|
6779
|
+
*
|
|
6780
|
+
* @param context - The stored record.
|
|
6781
|
+
* @param user - The account it names.
|
|
6782
|
+
*/
|
|
6783
|
+
private assertStillBound;
|
|
6784
|
+
/**
|
|
6785
|
+
* Parses a stored context, answering `null` for anything that is not one.
|
|
6786
|
+
*
|
|
6787
|
+
* @param raw - The stored JSON.
|
|
6788
|
+
* @returns The validated record, or `null`.
|
|
6789
|
+
*/
|
|
6790
|
+
private parseContext;
|
|
6791
|
+
/**
|
|
6792
|
+
* Tells the old address that the account moved, fire-and-forget.
|
|
6793
|
+
*
|
|
6794
|
+
* A delivery failure does not roll back a change the user asked for and has proven — but it
|
|
6795
|
+
* is logged, because this message is the owner's last chance to see a takeover at an address
|
|
6796
|
+
* they still control, and an operator needs to know when it did not go out.
|
|
6797
|
+
*
|
|
6798
|
+
* @param oldEmail - The address the account is leaving.
|
|
6799
|
+
* @param newEmail - The address it moved to.
|
|
6800
|
+
*/
|
|
6801
|
+
private notifyOldAddress;
|
|
6802
|
+
}
|
|
6803
|
+
|
|
4772
6804
|
/**
|
|
4773
6805
|
* Result returned by {@link MfaService.setup} containing the TOTP secret,
|
|
4774
6806
|
* a QR code URI for authenticator apps, and the one-time plain-text recovery codes.
|
|
4775
6807
|
*
|
|
4776
6808
|
* @remarks
|
|
4777
6809
|
* `recoveryCodes` must be displayed to the user **once** at setup time and never
|
|
4778
|
-
* stored in plain text — the service stores
|
|
6810
|
+
* stored in plain text — the service stores a keyed HMAC-SHA-256 of each one.
|
|
4779
6811
|
* `secret` is provided for manual entry in authenticator apps that cannot scan a QR code.
|
|
4780
6812
|
*/
|
|
4781
6813
|
interface MfaSetupResult {
|
|
@@ -4798,6 +6830,8 @@ interface MfaSetupResult {
|
|
|
4798
6830
|
* @remarks
|
|
4799
6831
|
* This service is only registered when `options.mfa` is configured in
|
|
4800
6832
|
* `BymaxAuthModule.registerAsync()`. All crypto operations use `node:crypto` only.
|
|
6833
|
+
*
|
|
6834
|
+
* @layer Service
|
|
4801
6835
|
*/
|
|
4802
6836
|
declare class MfaService {
|
|
4803
6837
|
private readonly options;
|
|
@@ -4813,24 +6847,88 @@ declare class MfaService {
|
|
|
4813
6847
|
private readonly logger;
|
|
4814
6848
|
constructor(options: ResolvedOptions, userRepo: IUserRepository, platformUserRepo: IPlatformUserRepository | null, redis: AuthRedisService, tokenManager: TokenManagerService, bruteForce: BruteForceService, passwordService: PasswordService, sessionService: SessionService, emailProvider: IEmailProvider, hooks: IAuthHooks);
|
|
4815
6849
|
/**
|
|
4816
|
-
*
|
|
6850
|
+
* Returns the resolved MFA configuration. `options.mfa` is always present when `MfaService` is registered.
|
|
4817
6851
|
*
|
|
4818
6852
|
* `options.mfa` is always present when `MfaService` is registered — the module
|
|
4819
6853
|
* only registers the service when `mfa` is configured. The single suppression
|
|
4820
6854
|
* here eliminates repetitive `!` assertions throughout the class.
|
|
4821
6855
|
*/
|
|
4822
6856
|
private get mfaOptions();
|
|
6857
|
+
/**
|
|
6858
|
+
* Store the TOTP secret re-encrypted under the current key.
|
|
6859
|
+
*
|
|
6860
|
+
* Detached from the challenge it follows: the user is already authenticated and the retired
|
|
6861
|
+
* key still opens the secret, so a failure here costs the migration and nothing else.
|
|
6862
|
+
*
|
|
6863
|
+
* @param userId - The account whose stored secret is being re-encrypted.
|
|
6864
|
+
* @param context - Which identity plane the account belongs to.
|
|
6865
|
+
* @param secretBase32 - The decrypted secret.
|
|
6866
|
+
* @param recoveryCodes - The stored recovery digests, written back unchanged.
|
|
6867
|
+
*/
|
|
6868
|
+
private reencryptSecret;
|
|
6869
|
+
/**
|
|
6870
|
+
* Performs one MFA state transition as a serialized read-modify-write.
|
|
6871
|
+
*
|
|
6872
|
+
* Every MFA transition rewrites a single repository record that carries `mfaEnabled`, the
|
|
6873
|
+
* encrypted secret and the recovery-code digests **together**, and `updateMfa` replaces all
|
|
6874
|
+
* three wholesale — the interface offers no compare-and-set and the repository is the host's,
|
|
6875
|
+
* so the library cannot add one. Read-modify-write over a shared record with no CAS is
|
|
6876
|
+
* last-write-wins, and the three ways that bit were:
|
|
6877
|
+
*
|
|
6878
|
+
* - two challenges spending *different* recovery codes concurrently each write the full list
|
|
6879
|
+
* minus their own code, so the loser's code comes back and verifies again once the `rcu:`
|
|
6880
|
+
* claim expires. That claim is keyed on the code, so it serializes two attempts at the
|
|
6881
|
+
* *same* code and nothing else;
|
|
6882
|
+
* - a challenge that read the list before `regenerateRecoveryCodes` and splices after it
|
|
6883
|
+
* restores the entire old set, unspending it — precisely when the user replaced it because
|
|
6884
|
+
* it leaked — while the codes they just printed are gone;
|
|
6885
|
+
* - a challenge that splices after `disable` completes writes `mfaEnabled: true` back with
|
|
6886
|
+
* the pre-disable secret, putting the account under a factor the user removed and may no
|
|
6887
|
+
* longer hold.
|
|
6888
|
+
*
|
|
6889
|
+
* The fix is to serialize the whole read-modify-write per account and plane. `mutate` is
|
|
6890
|
+
* handed the record as it stands **inside** the lock — never the copy the caller read
|
|
6891
|
+
* earlier — and returns the update to write, or `null` to abandon the transition because
|
|
6892
|
+
* the record moved underneath it.
|
|
6893
|
+
*
|
|
6894
|
+
* A caller that cannot take the lock is refused with `MFA_STATE_CONFLICT` rather than made to
|
|
6895
|
+
* wait: concurrent MFA state changes on one account are pathological, and the honest answer
|
|
6896
|
+
* is "try again". The lock's TTL is short so a process that dies mid-transition does not
|
|
6897
|
+
* strand the account, and it is released in a `finally` so an ordinary failure does not
|
|
6898
|
+
* either.
|
|
6899
|
+
*
|
|
6900
|
+
* @param context - Which identity plane the account belongs to.
|
|
6901
|
+
* @param userId - The account being transitioned.
|
|
6902
|
+
* @param mutate - Given the record inside the lock, returns the update or `null` to abandon.
|
|
6903
|
+
* @returns `true` when a write happened, `false` when `mutate` abandoned the transition.
|
|
6904
|
+
* @throws {@link AuthException} `MFA_STATE_CONFLICT` when another transition holds the lock.
|
|
6905
|
+
*/
|
|
6906
|
+
private transitionMfaRecord;
|
|
4823
6907
|
/**
|
|
4824
6908
|
* Encrypts a TOTP secret for storage in the database using AES-256-GCM.
|
|
4825
6909
|
*/
|
|
4826
6910
|
private encryptSecret;
|
|
4827
6911
|
/**
|
|
4828
|
-
* Decrypts a stored TOTP secret.
|
|
6912
|
+
* Decrypts a stored TOTP secret, falling back to keys retired by a rotation.
|
|
6913
|
+
*
|
|
6914
|
+
* The ciphertext records no key identifier, so without the retired keys, changing
|
|
6915
|
+
* `mfa.encryptionKey` makes every stored secret undecryptable — every enrolled user's
|
|
6916
|
+
* authenticator stops matching at once, with no way back. AES-GCM authenticates, so a wrong
|
|
6917
|
+
* key fails unambiguously rather than returning garbage; trying them in order is safe.
|
|
4829
6918
|
*
|
|
4830
6919
|
* Re-throws any decryption failure as an opaque `TOKEN_INVALID` to prevent
|
|
4831
6920
|
* error-type oracle attacks (callers cannot distinguish format vs. tamper errors).
|
|
4832
6921
|
*/
|
|
4833
6922
|
private decryptSecret;
|
|
6923
|
+
/**
|
|
6924
|
+
* Decrypt under the current key, then under each retired one.
|
|
6925
|
+
*
|
|
6926
|
+
* @param encrypted - The stored ciphertext.
|
|
6927
|
+
* @returns The plaintext and whether a retired key produced it — the signal that the record
|
|
6928
|
+
* should be re-encrypted under the current key.
|
|
6929
|
+
* @throws {@link AuthException} `TOKEN_INVALID` when no key decrypts it.
|
|
6930
|
+
*/
|
|
6931
|
+
private decryptWithRotation;
|
|
4834
6932
|
/**
|
|
4835
6933
|
* Safely parses a Redis-stored {@link MfaSetupData} JSON payload.
|
|
4836
6934
|
*
|
|
@@ -4868,17 +6966,55 @@ declare class MfaService {
|
|
|
4868
6966
|
*/
|
|
4869
6967
|
private hashRecoveryCodes;
|
|
4870
6968
|
/**
|
|
4871
|
-
*
|
|
6969
|
+
* Derives the stored digest for a recovery code: a keyed HMAC-SHA-256, hex encoded.
|
|
4872
6970
|
*
|
|
4873
|
-
*
|
|
4874
|
-
*
|
|
4875
|
-
*
|
|
4876
|
-
*
|
|
4877
|
-
*
|
|
6971
|
+
* A recovery code is 96 bits of CSPRNG output, not a human-chosen password, so a
|
|
6972
|
+
* memory-hard KDF buys nothing against it — there is no dictionary to walk and brute
|
|
6973
|
+
* forcing 2^96 is out of reach whatever the hash costs. What the KDF did buy was an
|
|
6974
|
+
* attacker-reachable CPU amplifier: a challenge submitting a wrong recovery code scanned
|
|
6975
|
+
* every stored digest, so one request cost as many scrypt derivations as the user had
|
|
6976
|
+
* codes. The keyed MAC is the right primitive here — the secret key is what stops an
|
|
6977
|
+
* offline attacker precomputing digests from a leaked table, and it costs microseconds.
|
|
6978
|
+
*/
|
|
6979
|
+
private digestRecoveryCode;
|
|
6980
|
+
/**
|
|
6981
|
+
* Compares a submitted recovery code against every stored digest.
|
|
4878
6982
|
*
|
|
4879
|
-
*
|
|
6983
|
+
* One storage format only: a keyed MAC over the code. Every digest is compared in constant
|
|
6984
|
+
* time and the scan always runs to completion — including the step that picks the winner out
|
|
6985
|
+
* of the recorded results — so neither the position of a match nor the number of codes still
|
|
6986
|
+
* unused is observable in the response time.
|
|
6987
|
+
*
|
|
6988
|
+
* @returns Index of the first matching digest, or `-1` if none match.
|
|
4880
6989
|
*/
|
|
4881
6990
|
private verifyRecoveryCode;
|
|
6991
|
+
/**
|
|
6992
|
+
* Claims a matched recovery code for exactly one challenge.
|
|
6993
|
+
*
|
|
6994
|
+
* Consuming a code is a read-modify-write against the consumer's repository: the challenge
|
|
6995
|
+
* reads the whole array, removes one entry, and writes the rest back. Two challenges landing
|
|
6996
|
+
* together both read the array containing the code, both match it, and both write — one code
|
|
6997
|
+
* mints two sessions, which is the one property a recovery code has. The library cannot fix
|
|
6998
|
+
* that in the repository, because the repository is the consumer's and its atomicity is
|
|
6999
|
+
* theirs to define. It can fix it in the store it owns.
|
|
7000
|
+
*
|
|
7001
|
+
* `SET NX` over an HMAC of plane + user + code is the same primitive the TOTP anti-replay
|
|
7002
|
+
* marker already uses, for the same reason and with the same properties: the key discloses
|
|
7003
|
+
* neither the user nor the code, and it cannot be shared across identity planes whose id
|
|
7004
|
+
* spaces may collide. The first claim wins; every other reads as an invalid code, which is
|
|
7005
|
+
* what a code already spent is.
|
|
7006
|
+
*
|
|
7007
|
+
* The marker is deliberately short-lived. It exists to serialize a race measured in
|
|
7008
|
+
* milliseconds, not to be the durable record — that is the repository write. Outliving the
|
|
7009
|
+
* write by much would turn a failed write into a permanently unusable code that is still
|
|
7010
|
+
* sitting in the account's list.
|
|
7011
|
+
*
|
|
7012
|
+
* @param context - The identity plane the challenge belongs to.
|
|
7013
|
+
* @param userId - The account the code belongs to.
|
|
7014
|
+
* @param code - The submitted code, never stored — only its keyed MAC becomes a key.
|
|
7015
|
+
* @returns `true` when this challenge is the one that claimed it.
|
|
7016
|
+
*/
|
|
7017
|
+
private claimRecoveryCode;
|
|
4882
7018
|
/**
|
|
4883
7019
|
* Returns a `SafeAuthUser` projection of a dashboard user, stripping credentials
|
|
4884
7020
|
* and MFA secret fields before passing to hooks or email providers.
|
|
@@ -4918,7 +7054,7 @@ declare class MfaService {
|
|
|
4918
7054
|
* reused (rather than introducing a new one) because the consumer-facing
|
|
4919
7055
|
* meaning is the same: "platform MFA cannot operate".
|
|
4920
7056
|
*/
|
|
4921
|
-
setup(userId: string, context?: 'dashboard' | 'platform'): Promise<MfaSetupResult>;
|
|
7057
|
+
setup(userId: string, context?: 'dashboard' | 'platform', password?: string): Promise<MfaSetupResult>;
|
|
4922
7058
|
/**
|
|
4923
7059
|
* Verifies the first TOTP code from the user's authenticator app and permanently
|
|
4924
7060
|
* enables MFA on the account.
|
|
@@ -4933,6 +7069,7 @@ declare class MfaService {
|
|
|
4933
7069
|
* @param ip - Client IP address (forwarded to hooks).
|
|
4934
7070
|
* @param userAgent - User-Agent header (forwarded to hooks).
|
|
4935
7071
|
* @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
|
|
7072
|
+
* @throws {@link AuthException} MFA_ALREADY_ENABLED when MFA is already active on the account.
|
|
4936
7073
|
* @throws `MFA_SETUP_REQUIRED` if no pending setup data is found in Redis.
|
|
4937
7074
|
* @throws `MFA_INVALID_CODE` if the submitted TOTP code is invalid.
|
|
4938
7075
|
* @throws `MFA_NOT_ENABLED` if `context === 'platform'` and the platform user
|
|
@@ -4991,8 +7128,8 @@ declare class MfaService {
|
|
|
4991
7128
|
* the supplied `context`. The TOTP secret on the user record is unchanged — only
|
|
4992
7129
|
* the recovery code list is replaced.
|
|
4993
7130
|
*
|
|
4994
|
-
* Returns the plain-text codes once. They are NOT persisted in plain form; only
|
|
4995
|
-
*
|
|
7131
|
+
* Returns the plain-text codes once. They are NOT persisted in plain form; only a
|
|
7132
|
+
* keyed HMAC-SHA-256 of each goes into the database. The caller is responsible for showing the
|
|
4996
7133
|
* codes to the user exactly once and warning them to save them safely.
|
|
4997
7134
|
*
|
|
4998
7135
|
* @remarks
|
|
@@ -5034,13 +7171,278 @@ declare class MfaService {
|
|
|
5034
7171
|
*/
|
|
5035
7172
|
private verifyTotpWithAntiReplay;
|
|
5036
7173
|
/**
|
|
5037
|
-
*
|
|
5038
|
-
*
|
|
7174
|
+
* Requires the caller to re-prove the account password before a factor is changed.
|
|
7175
|
+
*
|
|
7176
|
+
* Counted like a login, and for the same reason. `login` refuses an account after N wrong
|
|
7177
|
+
* passwords; this door asks for the same secret and used to refuse nothing, so a caller
|
|
7178
|
+
* holding a stolen access token but not the password could guess it here indefinitely. The
|
|
7179
|
+
* only control left was the per-route IP limit, which a distributed caller sidesteps — and
|
|
7180
|
+
* winning the guess buys the whole account: enrol a factor, change the password, move the
|
|
7181
|
+
* address. A door that takes the password has to carry the password's lockout.
|
|
7182
|
+
*
|
|
7183
|
+
* The identifier is namespaced by flow and by plane. Sharing one counter with `login` would
|
|
7184
|
+
* let an authenticated caller lock the owner out of their own sign-in, and sharing it across
|
|
7185
|
+
* planes would let a dashboard user and a platform admin holding the same id exhaust each
|
|
7186
|
+
* other's budget — the same two reasons the challenge and disable counters are split.
|
|
7187
|
+
*
|
|
7188
|
+
* @param context - The authentication plane, part of the counter's key.
|
|
7189
|
+
* @param userId - The account being changed, part of the counter's key.
|
|
7190
|
+
* @param passwordHash - The account's stored hash, or `null` for an OAuth-only account.
|
|
7191
|
+
* @param password - The password the caller submitted, if any.
|
|
7192
|
+
* @throws {@link AuthException} `ACCOUNT_LOCKED` once the failure budget for this flow is
|
|
7193
|
+
* spent, or `INVALID_CREDENTIALS` when the account has a password and the submitted one is
|
|
7194
|
+
* absent or wrong. The latter is deliberately the same code a failed login returns: an
|
|
7195
|
+
* attacker holding a stolen token learns nothing from it beyond what they already knew.
|
|
7196
|
+
*/
|
|
7197
|
+
private assertReauthenticated;
|
|
7198
|
+
/**
|
|
7199
|
+
* Fetches a user from the correct repository based on the MFA context, and refuses one whose
|
|
7200
|
+
* account is blocked.
|
|
7201
|
+
*
|
|
7202
|
+
* The status gate lives here rather than in each caller because every entry point that
|
|
7203
|
+
* reaches this method changes or spends an authentication factor, and every one of them
|
|
7204
|
+
* must refuse a suspended or banned account. It used to live in `challenge` alone, so
|
|
7205
|
+
* `setup`, `verifyAndEnable`, `disable` and `regenerateRecoveryCodes` had no gate at all:
|
|
7206
|
+
* an operator who suspended a compromised account bought nothing against an attacker still
|
|
7207
|
+
* holding an unexpired access token, who could turn the second factor off — or enrol their
|
|
7208
|
+
* own authenticator over it — for the token's remaining lifetime. Nothing else covers that
|
|
7209
|
+
* window: no status change bumps the token epoch, so the per-request check is the only
|
|
7210
|
+
* defence, and neither MFA controller composes `UserStatusGuard` (the platform plane has no
|
|
7211
|
+
* status guard at all). Every other authority-bearing route in the library does gate on
|
|
7212
|
+
* status; changing an authentication factor is at least as privileged as minting an
|
|
7213
|
+
* invitation.
|
|
7214
|
+
*
|
|
7215
|
+
* Gating the fetch rather than the callers is deliberate: a method added later inherits the
|
|
7216
|
+
* check instead of having to remember it.
|
|
7217
|
+
*
|
|
7218
|
+
* @param context - Which identity plane the caller is acting on.
|
|
7219
|
+
* @param userId - The subject taken from the verified token.
|
|
7220
|
+
* @returns The account record, guaranteed to be in good standing.
|
|
5039
7221
|
* @throws `TOKEN_INVALID` if the user is not found.
|
|
7222
|
+
* @throws {@link AuthException} the status error when the account is blocked.
|
|
5040
7223
|
*/
|
|
5041
7224
|
private fetchUserForContext;
|
|
5042
7225
|
}
|
|
5043
7226
|
|
|
7227
|
+
declare class InvitationService {
|
|
7228
|
+
private readonly userRepo;
|
|
7229
|
+
private readonly emailProvider;
|
|
7230
|
+
private readonly hooks;
|
|
7231
|
+
private readonly redis;
|
|
7232
|
+
private readonly passwordService;
|
|
7233
|
+
private readonly sessionService;
|
|
7234
|
+
private readonly tokenManager;
|
|
7235
|
+
private readonly options;
|
|
7236
|
+
private readonly logger;
|
|
7237
|
+
constructor(userRepo: IUserRepository, emailProvider: IEmailProvider, hooks: IAuthHooks, redis: AuthRedisService, passwordService: PasswordService, sessionService: SessionService, tokenManager: TokenManagerService, options: ResolvedOptions);
|
|
7238
|
+
/**
|
|
7239
|
+
* Creates an invitation for `email` to join `tenantId` with `role`.
|
|
7240
|
+
*
|
|
7241
|
+
* Authorization sequence:
|
|
7242
|
+
* 1. Validates that `role` exists in `roles.hierarchy`.
|
|
7243
|
+
* 2. Fetches the inviter and verifies that `inviter.role >= role` via `hasRole()`.
|
|
7244
|
+
* 3. Generates a 32-byte (64 hex char) secure token, stores `inv:{sha256(token)}`
|
|
7245
|
+
* in Redis with the configured TTL, and emails the raw token to the invitee.
|
|
7246
|
+
* The raw token is passed as `inviteToken` in `InviteData` — the `IEmailProvider`
|
|
7247
|
+
* implementation is responsible for constructing the full accept URL.
|
|
7248
|
+
*
|
|
7249
|
+
* @param inviterUserId - Internal ID of the authenticated user sending the invite.
|
|
7250
|
+
* @param email - Email address to invite. Normalized to lowercase at this boundary.
|
|
7251
|
+
* @param role - Role to assign upon acceptance.
|
|
7252
|
+
* @param tenantId - Tenant the invitee will join.
|
|
7253
|
+
* @param tenantName - Optional display name for the tenant in the invitation email.
|
|
7254
|
+
* Falls back to `tenantId` when not provided.
|
|
7255
|
+
* @throws `ForbiddenException` with `INSUFFICIENT_ROLE` when the role is unknown
|
|
7256
|
+
* or the inviter lacks authority to issue the requested role.
|
|
7257
|
+
* @throws `AuthException` with `TOKEN_INVALID` when the inviter user is not found.
|
|
7258
|
+
*/
|
|
7259
|
+
invite(inviterUserId: string, email: string, role: string, tenantId: string, tenantName?: string): Promise<void>;
|
|
7260
|
+
/**
|
|
7261
|
+
* Accepts a pending invitation and creates the new user account.
|
|
7262
|
+
*
|
|
7263
|
+
* Steps:
|
|
7264
|
+
* 1. Atomically reads and deletes `inv:{sha256(dto.token)}` via `getdel()`.
|
|
7265
|
+
* Missing key → `INVALID_INVITATION_TOKEN`. The atomic consumption prevents
|
|
7266
|
+
* race conditions where two concurrent requests both read a valid token before
|
|
7267
|
+
* either deletes it.
|
|
7268
|
+
* 2. Validates and parses the stored JSON — rejects malformed payloads.
|
|
7269
|
+
* 3. Re-validates the stored `role` against the configured hierarchy to prevent
|
|
7270
|
+
* privilege escalation from a tampered Redis value.
|
|
7271
|
+
* 4. Verifies the invitee email is not already registered in the tenant.
|
|
7272
|
+
* 5. Hashes `dto.password` via `PasswordService`.
|
|
7273
|
+
* 6. Creates the user with `emailVerified: true` (invitation implies email ownership).
|
|
7274
|
+
* 7. Issues dashboard tokens.
|
|
7275
|
+
* 8. Calls `hooks.afterInvitationAccepted` if implemented.
|
|
7276
|
+
*
|
|
7277
|
+
* @param dto - Validated AcceptInvitationDto from the request body.
|
|
7278
|
+
* @param ip - Client IP address (for session audit and hooks).
|
|
7279
|
+
* @param userAgent - User-Agent string (for session audit and hooks).
|
|
7280
|
+
* @returns Full `AuthResult` with access + refresh tokens and the new user record.
|
|
7281
|
+
* @throws `AuthException` with `INVALID_INVITATION_TOKEN` if the token is missing or malformed.
|
|
7282
|
+
* @throws `AuthException` with `EMAIL_ALREADY_EXISTS` if the email is taken.
|
|
7283
|
+
*/
|
|
7284
|
+
/**
|
|
7285
|
+
* Whether an account's status still permits it to act.
|
|
7286
|
+
*
|
|
7287
|
+
* Routed through `assertNotBlocked` rather than an inline status test: one definition of
|
|
7288
|
+
* "blocked", and an inline version would have to re-implement its case-insensitive
|
|
7289
|
+
* comparison — a second implementation is a second thing to drift.
|
|
7290
|
+
*
|
|
7291
|
+
* @param user - The account to judge.
|
|
7292
|
+
* @returns `true` when the status is not one of the configured blocked ones.
|
|
7293
|
+
*/
|
|
7294
|
+
private inGoodStanding;
|
|
7295
|
+
/**
|
|
7296
|
+
* The invitee index key: the one handle the issuing side has on a pending invitation.
|
|
7297
|
+
*
|
|
7298
|
+
* The email is hashed rather than stored in the clear so a dump of the keyspace does not
|
|
7299
|
+
* enumerate who a tenant has been inviting, which the record itself never exposes either.
|
|
7300
|
+
*
|
|
7301
|
+
* @param email - The normalized invitee address.
|
|
7302
|
+
* @param tenantId - The tenant the invitation was issued for.
|
|
7303
|
+
* @returns The namespaced-by-caller key.
|
|
7304
|
+
*/
|
|
7305
|
+
private inviteeKey;
|
|
7306
|
+
/**
|
|
7307
|
+
* Derives the invitee-index identifier for an address: `hmac('{email}')`.
|
|
7308
|
+
*
|
|
7309
|
+
* HMAC rather than a bare digest because an address is low-entropy — a plain SHA-256 of one
|
|
7310
|
+
* is reversible by dictionary, and this key is the one handle anyone reading a keyspace dump
|
|
7311
|
+
* has on who a tenant has been inviting. The tenant is not in the preimage because it is
|
|
7312
|
+
* already a literal segment of the key.
|
|
7313
|
+
*
|
|
7314
|
+
* The preimage is pinned by `conformance/wire-contract.json` and shared byte-for-byte with
|
|
7315
|
+
* rust-auth, which writes the same index into the same Redis.
|
|
7316
|
+
*
|
|
7317
|
+
* @param email - The canonicalized address.
|
|
7318
|
+
* @returns Hex HMAC-SHA-256 identifier.
|
|
7319
|
+
*/
|
|
7320
|
+
private inviteeIdentifier;
|
|
7321
|
+
/**
|
|
7322
|
+
* Refuses a caller who may not destroy the invitation their new one would supersede.
|
|
7323
|
+
*
|
|
7324
|
+
* `create`'s own authorisation is `hasRole(inviter.role, requestedRole)` — a statement about
|
|
7325
|
+
* the role being granted, which says nothing about the role of the record being replaced.
|
|
7326
|
+
* `revokeInvitation` is deliberately strict about that second question, so reaching the same
|
|
7327
|
+
* end state through `create` must be too, or the strictness is decoration.
|
|
7328
|
+
*
|
|
7329
|
+
* An unparseable record is superseded without a check, exactly as `revokeInvitation` treats
|
|
7330
|
+
* it: it can no longer be accepted either, and leaving it behind would be worse.
|
|
7331
|
+
*
|
|
7332
|
+
* @param inviter - The authenticated caller, already known to be in the tenant.
|
|
7333
|
+
* @param email - The normalized invitee address.
|
|
7334
|
+
* @param tenantId - The tenant the invitation belongs to.
|
|
7335
|
+
* @throws {@link AuthException} `INSUFFICIENT_ROLE` when the caller is outranked by the
|
|
7336
|
+
* pending invitation. Unlike the revoke route this cannot answer silently — the caller is
|
|
7337
|
+
* asking to create something, and a silent success would report an invitation that does
|
|
7338
|
+
* not exist.
|
|
7339
|
+
*/
|
|
7340
|
+
private assertMaySupersede;
|
|
7341
|
+
/**
|
|
7342
|
+
* Approves the supersede and claims the index in one agreed step, retrying if the record
|
|
7343
|
+
* moves underneath the approval.
|
|
7344
|
+
*
|
|
7345
|
+
* The rank check and the claim are separate round trips, so on their own they can disagree
|
|
7346
|
+
* about WHICH invitation is being superseded: an outranked caller could pass the check while
|
|
7347
|
+
* the index was momentarily empty and then displace a higher-ranked invitation created in
|
|
7348
|
+
* between. The claim is therefore a compare-and-swap against the hash the check approved —
|
|
7349
|
+
* anything else means the record moved and the approval no longer describes what is there.
|
|
7350
|
+
*
|
|
7351
|
+
* A displaced approval is re-derived rather than refused: the contention is between two
|
|
7352
|
+
* legitimate inviters, and one of them losing a race is not an authorisation failure. The
|
|
7353
|
+
* retry is bounded, because an unbounded one turns a hot address into an unbounded loop.
|
|
7354
|
+
*
|
|
7355
|
+
* @param inviter - The authenticated caller, already known to be in the tenant.
|
|
7356
|
+
* @param email - The normalized invitee address.
|
|
7357
|
+
* @param tenantId - The tenant the invitation belongs to.
|
|
7358
|
+
* @param tokenHash - The new invitation's token hash.
|
|
7359
|
+
* @param ttl - The invitation TTL, in seconds.
|
|
7360
|
+
* @returns The displaced token hash, or `null` when there was no pending invitation.
|
|
7361
|
+
* @throws {@link AuthException} `INSUFFICIENT_ROLE` when the caller is outranked, or when the
|
|
7362
|
+
* index kept moving for the whole retry budget — the caller has not been shown to be
|
|
7363
|
+
* allowed to destroy whatever is there now.
|
|
7364
|
+
*/
|
|
7365
|
+
private supersedeApprovedInvitation;
|
|
7366
|
+
/**
|
|
7367
|
+
* Atomically points the invitee index at `tokenHash`, answering with the hash it displaced.
|
|
7368
|
+
*
|
|
7369
|
+
* A compare-and-swap, not a plain write: the claim proceeds only when the index still holds
|
|
7370
|
+
* exactly what the rank check approved. Two concurrent invites for one address therefore
|
|
7371
|
+
* cannot both believe they superseded nothing — exactly one wins, and the loser is told the
|
|
7372
|
+
* record moved so it can re-derive its approval against what is actually there.
|
|
7373
|
+
*
|
|
7374
|
+
* @param email - The normalized invitee address.
|
|
7375
|
+
* @param tenantId - The tenant the invitation belongs to.
|
|
7376
|
+
* @param tokenHash - The new invitation's token hash.
|
|
7377
|
+
* @param ttl - The invitation TTL, in seconds.
|
|
7378
|
+
* @param expected - The hash the rank check approved, or `null` for "no pending invitation".
|
|
7379
|
+
* @returns Whether this call claimed the index.
|
|
7380
|
+
*/
|
|
7381
|
+
private claimInviteeIndex;
|
|
7382
|
+
/**
|
|
7383
|
+
* Withdraws a pending invitation before it is accepted.
|
|
7384
|
+
*
|
|
7385
|
+
* An invitation is a credential: it provisions an account, at a role, inside a tenant,
|
|
7386
|
+
* to whoever holds the link. Until now the library could mint one and had no way to take
|
|
7387
|
+
* it back — a link sent to the wrong address, or sent by someone who has since left, stayed
|
|
7388
|
+
* redeemable for its whole TTL with nothing an operator could do about it. ASVS v5 §6.1.1
|
|
7389
|
+
* expects an administrative path to invalidate a credential that should no longer work.
|
|
7390
|
+
*
|
|
7391
|
+
* The revoker is held to the same bar as the issuer: they must belong to the tenant, be in
|
|
7392
|
+
* good standing, and out-rank the role the invitation grants. Anything looser would let a
|
|
7393
|
+
* member cancel an admin's invitations.
|
|
7394
|
+
*
|
|
7395
|
+
* Idempotent: revoking an invitation that never existed, already expired, or was already
|
|
7396
|
+
* accepted is not an error — the end state the caller asked for is the end state they get,
|
|
7397
|
+
* and reporting the difference would tell them whether an address has a pending invitation,
|
|
7398
|
+
* which is precisely what the index hashes the email to avoid disclosing.
|
|
7399
|
+
*
|
|
7400
|
+
* @param revokerUserId - Internal ID of the authenticated user withdrawing the invitation.
|
|
7401
|
+
* @param email - The invited address. Normalized at this boundary.
|
|
7402
|
+
* @param tenantId - The tenant the invitation was issued for.
|
|
7403
|
+
* @returns `true` when a pending invitation was removed, `false` when there was none.
|
|
7404
|
+
* @throws {@link AuthException} `TOKEN_INVALID` when the revoker no longer exists, or
|
|
7405
|
+
* `INSUFFICIENT_ROLE` when they may not withdraw this invitation.
|
|
7406
|
+
*/
|
|
7407
|
+
revokeInvitation(revokerUserId: string, email: string, tenantId: string): Promise<boolean>;
|
|
7408
|
+
/**
|
|
7409
|
+
* Parses a stored invitation, answering `null` for anything that is not one.
|
|
7410
|
+
*
|
|
7411
|
+
* @param raw - The stored JSON.
|
|
7412
|
+
* @returns The validated record, or `null`.
|
|
7413
|
+
*/
|
|
7414
|
+
private parseInvitation;
|
|
7415
|
+
/**
|
|
7416
|
+
* Whether `revoker` out-ranks the role `invitation` grants.
|
|
7417
|
+
*
|
|
7418
|
+
* Standing is checked by the caller, before the invitation is looked up at all: the two
|
|
7419
|
+
* belong on opposite sides of the disclosure line, because this comparison depends on the
|
|
7420
|
+
* target and that one does not.
|
|
7421
|
+
*
|
|
7422
|
+
* @param revoker - The authenticated user, already known to be in good standing.
|
|
7423
|
+
* @param invitation - The pending record.
|
|
7424
|
+
* @returns `true` when the withdrawal is authorised.
|
|
7425
|
+
*/
|
|
7426
|
+
private mayWithdraw;
|
|
7427
|
+
/**
|
|
7428
|
+
* Re-checks, at redemption time, everything that was true of the inviter when the link was
|
|
7429
|
+
* minted.
|
|
7430
|
+
*
|
|
7431
|
+
* An invitation is a delegation of authority, and authority is revocable. Validating it only
|
|
7432
|
+
* at creation means a 48-hour token carries whatever power its author had at the moment they
|
|
7433
|
+
* clicked send — surviving their suspension, their demotion, and their removal from the
|
|
7434
|
+
* tenant. The failure is answered as `INVALID_INVITATION_TOKEN` rather than as a role error:
|
|
7435
|
+
* the redeemer is not the one who lost authority, and telling them *why* would describe the
|
|
7436
|
+
* inviter's account status to someone who may be a stranger to it.
|
|
7437
|
+
*
|
|
7438
|
+
* @param invitation - The stored record, already shape-validated.
|
|
7439
|
+
* @throws {@link AuthException} `INVALID_INVITATION_TOKEN` when the inviter can no longer
|
|
7440
|
+
* grant what the invitation grants.
|
|
7441
|
+
*/
|
|
7442
|
+
private assertInviterStillAuthorised;
|
|
7443
|
+
acceptInvitation(dto: AcceptInvitationDto, ip: string, userAgent: string, headers: Record<string, string | string[] | undefined>): Promise<AuthResult>;
|
|
7444
|
+
}
|
|
7445
|
+
|
|
5044
7446
|
/**
|
|
5045
7447
|
* Manages the password-reset lifecycle for dashboard users.
|
|
5046
7448
|
*
|
|
@@ -5063,6 +7465,8 @@ declare class MfaService {
|
|
|
5063
7465
|
* same result regardless of whether the email exists or the user is eligible.
|
|
5064
7466
|
* Error codes and error shapes are intentionally identical for "not found" and
|
|
5065
7467
|
* "wrong input" to avoid leaking the existence of an account.
|
|
7468
|
+
*
|
|
7469
|
+
* @layer Service
|
|
5066
7470
|
*/
|
|
5067
7471
|
declare class PasswordResetService {
|
|
5068
7472
|
private readonly options;
|
|
@@ -5072,8 +7476,10 @@ declare class PasswordResetService {
|
|
|
5072
7476
|
private readonly otpService;
|
|
5073
7477
|
private readonly passwordService;
|
|
5074
7478
|
private readonly redis;
|
|
7479
|
+
private readonly sessionService;
|
|
7480
|
+
private readonly bruteForce;
|
|
5075
7481
|
private readonly logger;
|
|
5076
|
-
constructor(options: ResolvedOptions, userRepo: IUserRepository, emailProvider: IEmailProvider | null, hooks: IAuthHooks | null, otpService: OtpService, passwordService: PasswordService, redis: AuthRedisService);
|
|
7482
|
+
constructor(options: ResolvedOptions, userRepo: IUserRepository, emailProvider: IEmailProvider | null, hooks: IAuthHooks | null, otpService: OtpService, passwordService: PasswordService, redis: AuthRedisService, sessionService: SessionService, bruteForce: BruteForceService);
|
|
5077
7483
|
/**
|
|
5078
7484
|
* Initiates a password reset for the given email address.
|
|
5079
7485
|
*
|
|
@@ -5094,7 +7500,7 @@ declare class PasswordResetService {
|
|
|
5094
7500
|
*
|
|
5095
7501
|
* @param dto - Validated DTO containing `email` and `tenantId`.
|
|
5096
7502
|
*/
|
|
5097
|
-
initiateReset(dto: ForgotPasswordDto): Promise<void>;
|
|
7503
|
+
initiateReset(dto: ForgotPasswordDto, req: Request): Promise<void>;
|
|
5098
7504
|
/**
|
|
5099
7505
|
* Resets the user's password using a verified proof (token, OTP, or verifiedToken).
|
|
5100
7506
|
*
|
|
@@ -5112,10 +7518,10 @@ declare class PasswordResetService {
|
|
|
5112
7518
|
* @param dto - Validated DTO with `email`, `newPassword`, `tenantId`, and one proof field.
|
|
5113
7519
|
* @throws {@link AuthException} `PASSWORD_RESET_TOKEN_INVALID` when the proof is absent,
|
|
5114
7520
|
* consumed, expired, or method-mismatch detected.
|
|
5115
|
-
* @throws {@link AuthException} `OTP_INVALID`
|
|
7521
|
+
* @throws {@link AuthException} `OTP_INVALID` — one answer for every OTP failure — for
|
|
5116
7522
|
* OTP-path failures.
|
|
5117
7523
|
*/
|
|
5118
|
-
resetPassword(dto: ResetPasswordDto): Promise<void>;
|
|
7524
|
+
resetPassword(dto: ResetPasswordDto, req: Request): Promise<void>;
|
|
5119
7525
|
/**
|
|
5120
7526
|
* Verifies a password-reset OTP and exchanges it for a short-lived `verifiedToken`.
|
|
5121
7527
|
*
|
|
@@ -5128,13 +7534,12 @@ declare class PasswordResetService {
|
|
|
5128
7534
|
*
|
|
5129
7535
|
* @param dto - Validated DTO with `email`, `tenantId`, and `otp`.
|
|
5130
7536
|
* @returns The raw `verifiedToken` string (64-char hex) to forward to the client.
|
|
5131
|
-
* @throws {@link AuthException} `
|
|
5132
|
-
*
|
|
5133
|
-
* @throws {@link AuthException} `OTP_INVALID` when the OTP does not match.
|
|
7537
|
+
* @throws {@link AuthException} `OTP_INVALID` for every OTP failure — a wrong code, a
|
|
7538
|
+
* record that is not in Redis, and an exhausted attempt ceiling are indistinguishable.
|
|
5134
7539
|
* @throws {@link AuthException} `PASSWORD_RESET_TOKEN_INVALID` when the user is not
|
|
5135
7540
|
* found after OTP verification (prevents issuing tokens for non-existent accounts).
|
|
5136
7541
|
*/
|
|
5137
|
-
verifyOtp(dto: VerifyOtpDto): Promise<string>;
|
|
7542
|
+
verifyOtp(dto: VerifyOtpDto, req: Request): Promise<string>;
|
|
5138
7543
|
/**
|
|
5139
7544
|
* Requests a new password-reset OTP for the given email address.
|
|
5140
7545
|
*
|
|
@@ -5146,7 +7551,7 @@ declare class PasswordResetService {
|
|
|
5146
7551
|
*
|
|
5147
7552
|
* @param dto - Validated DTO with `email` and `tenantId`.
|
|
5148
7553
|
*/
|
|
5149
|
-
resendOtp(dto: ResendOtpDto): Promise<void>;
|
|
7554
|
+
resendOtp(dto: ResendOtpDto, req: Request): Promise<void>;
|
|
5150
7555
|
/**
|
|
5151
7556
|
* Token-based reset path: atomically consumes the token from Redis and updates
|
|
5152
7557
|
* the password.
|
|
@@ -5185,6 +7590,74 @@ declare class PasswordResetService {
|
|
|
5185
7590
|
* Cross-store atomicity between the DB and Redis is inherently unavailable.
|
|
5186
7591
|
* The current ordering minimises the security impact of a partial failure.
|
|
5187
7592
|
*/
|
|
7593
|
+
/**
|
|
7594
|
+
* Changes the password of an already-authenticated account, proving identity with the
|
|
7595
|
+
* current password rather than an emailed token.
|
|
7596
|
+
*
|
|
7597
|
+
* This is the flow ASVS v5 §6.2.2 and §6.2.3 require at Level 1 — "users can change their
|
|
7598
|
+
* password", and "password change functionality requires the user's current and new
|
|
7599
|
+
* password" — and it was the one credential operation this library did not own. Without it a
|
|
7600
|
+
* consumer either sends their users through the *unauthenticated* recovery flow to rotate a
|
|
7601
|
+
* password they already know, or rebuilds the operation themselves against a hash format the
|
|
7602
|
+
* README forbids them to touch.
|
|
7603
|
+
*
|
|
7604
|
+
* The current password is what makes it safe. A session alone is not proof of identity: a
|
|
7605
|
+
* token lifted by XSS or from a shared machine would otherwise be enough to rotate the
|
|
7606
|
+
* credential, lock the real owner out of an account they still know the password to, and
|
|
7607
|
+
* keep the attacker in.
|
|
7608
|
+
*
|
|
7609
|
+
* Every other session is ended on success (ASVS v5 §7.4.3), and the token epoch is bumped so
|
|
7610
|
+
* already-issued access tokens die with them. The caller's own refresh session survives when
|
|
7611
|
+
* it can be identified, so the device that just changed the password stays signed in —
|
|
7612
|
+
* silently re-minting its access token on the next rotation. When it cannot be identified,
|
|
7613
|
+
* every session goes, including this one: a change that leaves an unknown session alive is
|
|
7614
|
+
* the failure this control exists to prevent.
|
|
7615
|
+
*
|
|
7616
|
+
* @param userId - The authenticated account, taken from the verified token — never the body.
|
|
7617
|
+
* @param dto - Validated current and new password.
|
|
7618
|
+
* @param currentRefreshToken - The caller's raw refresh token, when the request carried one.
|
|
7619
|
+
* @throws {@link AuthException} `INVALID_CREDENTIALS` when the current password does not
|
|
7620
|
+
* match, or the account has no local password (an OAuth-only account has nothing to
|
|
7621
|
+
* change; its credential belongs to the provider).
|
|
7622
|
+
* @throws {@link AuthException} `PASSWORD_COMPROMISED` when the new password is refused by
|
|
7623
|
+
* the configured breach checker.
|
|
7624
|
+
*/
|
|
7625
|
+
changePassword(userId: string, dto: ChangePasswordDto, currentRefreshToken?: string): Promise<void>;
|
|
7626
|
+
/**
|
|
7627
|
+
* Sends the "your password changed" notice, fire-and-forget.
|
|
7628
|
+
*
|
|
7629
|
+
* NIST SP 800-63B §4.6 asks for a notification through a channel independent of the
|
|
7630
|
+
* transaction that bound the new credential. The classic takeover starts with a compromised
|
|
7631
|
+
* mailbox — trigger a reset, complete it, delete the mail — so this notice is what turns
|
|
7632
|
+
* "the victim finds out days later, at a failed login" into "the victim finds out now".
|
|
7633
|
+
*
|
|
7634
|
+
* Never awaited and never allowed to throw: a delivery failure must not undo a password that
|
|
7635
|
+
* has already been written, nor answer differently to the caller.
|
|
7636
|
+
*/
|
|
7637
|
+
private notifyPasswordChanged;
|
|
7638
|
+
/**
|
|
7639
|
+
* A digest of the account's current password hash, used to bind a reset token to it.
|
|
7640
|
+
*
|
|
7641
|
+
* The hash itself never leaves the repository — only this digest goes into Redis, so a leaked
|
|
7642
|
+
* snapshot of the reset keyspace reveals nothing about the credential. An account with no
|
|
7643
|
+
* local password yields the empty string, which is a value like any other: a token minted
|
|
7644
|
+
* then is invalidated as soon as one is set.
|
|
7645
|
+
*/
|
|
7646
|
+
private passwordFingerprintOf;
|
|
7647
|
+
/**
|
|
7648
|
+
* Refuses a reset token whose binding no longer matches the account's current password.
|
|
7649
|
+
*
|
|
7650
|
+
* Several `pw_reset:` keys can be alive at once, and completing a reset with one used to
|
|
7651
|
+
* leave the others valid — the wrong end state precisely when it matters, since a victim
|
|
7652
|
+
* resetting because an attacker read a link from their mailbox had not closed the link the
|
|
7653
|
+
* attacker read. The binding makes the first completed reset, or an authenticated change,
|
|
7654
|
+
* invalidate all of them.
|
|
7655
|
+
*
|
|
7656
|
+
* An empty stored fingerprint means the token predates the binding (a rolling deploy, or a
|
|
7657
|
+
* sibling implementation that has not taken this change), and is accepted: refusing those
|
|
7658
|
+
* would break every reset in flight for a window this narrow.
|
|
7659
|
+
*/
|
|
7660
|
+
private assertResetTokenStillBound;
|
|
5188
7661
|
private applyPasswordReset;
|
|
5189
7662
|
/**
|
|
5190
7663
|
* Generates and stores a password-reset token, then sends it to the user's email.
|
|
@@ -5222,6 +7695,120 @@ declare class PasswordResetService {
|
|
|
5222
7695
|
private parseResetContext;
|
|
5223
7696
|
}
|
|
5224
7697
|
|
|
7698
|
+
/**
|
|
7699
|
+
* Core authentication service for platform administrators.
|
|
7700
|
+
*
|
|
7701
|
+
* Orchestrates login, logout, token refresh, and session revocation for the
|
|
7702
|
+
* operator/super-admin layer. Platform admins are not tenant-scoped — they
|
|
7703
|
+
* authenticate against the global `IPlatformUserRepository`.
|
|
7704
|
+
*
|
|
7705
|
+
* All brute-force tracking uses an HMAC-SHA-256 identifier derived from the email
|
|
7706
|
+
* so that no PII appears in Redis keys and the identifier cannot be reversed via
|
|
7707
|
+
* dictionary lookup.
|
|
7708
|
+
*
|
|
7709
|
+
* @remarks
|
|
7710
|
+
* Platform refresh tokens are stored under `prt:{sha256(token)}` in Redis.
|
|
7711
|
+
* The `sess:{userId}` SET tracks all active session keys for a given admin,
|
|
7712
|
+
* enabling full-session revocation via {@link revokeAllPlatformSessions}.
|
|
7713
|
+
*
|
|
7714
|
+
* @layer Service
|
|
7715
|
+
*/
|
|
7716
|
+
declare class PlatformAuthService {
|
|
7717
|
+
private readonly platformUserRepo;
|
|
7718
|
+
private readonly passwordService;
|
|
7719
|
+
private readonly tokenManager;
|
|
7720
|
+
private readonly bruteForce;
|
|
7721
|
+
private readonly redis;
|
|
7722
|
+
private readonly options;
|
|
7723
|
+
private readonly logger;
|
|
7724
|
+
constructor(platformUserRepo: IPlatformUserRepository, passwordService: PasswordService, tokenManager: TokenManagerService, bruteForce: BruteForceService, redis: AuthRedisService, options: ResolvedOptions);
|
|
7725
|
+
/**
|
|
7726
|
+
* Authenticates a platform administrator with email and password.
|
|
7727
|
+
*
|
|
7728
|
+
* Returns either a full {@link PlatformAuthResult} or a {@link MfaChallengeResult}
|
|
7729
|
+
* when the admin has MFA enabled.
|
|
7730
|
+
*
|
|
7731
|
+
* @param dto - Login credentials (email + password).
|
|
7732
|
+
* @param ip - Client IP address (for session audit and brute-force tracking).
|
|
7733
|
+
* @param userAgent - User-Agent header value (for session description).
|
|
7734
|
+
* @returns Auth result or MFA challenge prompt.
|
|
7735
|
+
* @throws {@link AuthException} with `ACCOUNT_LOCKED` (429) when brute-force limit reached.
|
|
7736
|
+
* @throws {@link AuthException} with `INVALID_CREDENTIALS` on bad email/password.
|
|
7737
|
+
* @throws {@link AuthException} with the matching status code (403) when the admin's
|
|
7738
|
+
* account status is configured as blocked.
|
|
7739
|
+
*/
|
|
7740
|
+
login(dto: PlatformLoginDto, ip: string, userAgent: string): Promise<PlatformAuthResult | MfaChallengeResult>;
|
|
7741
|
+
/**
|
|
7742
|
+
* Logs out a platform administrator by revoking the access token JTI and
|
|
7743
|
+
* deleting the associated platform refresh session from Redis.
|
|
7744
|
+
*
|
|
7745
|
+
* @param userId - The authenticated admin's ID (from the verified JWT `sub` claim).
|
|
7746
|
+
* @param jti - The JWT ID claim (`jti`) from the access token (for revocation blacklist).
|
|
7747
|
+
* @param exp - The expiry Unix timestamp from the access token (for TTL calculation).
|
|
7748
|
+
* @param rawRefreshToken - The raw opaque platform refresh token.
|
|
7749
|
+
*/
|
|
7750
|
+
logout(accessToken: string, rawRefreshToken: string): Promise<string>;
|
|
7751
|
+
/**
|
|
7752
|
+
* Rotates a platform administrator's refresh token.
|
|
7753
|
+
*
|
|
7754
|
+
* Delegates to {@link TokenManagerService.reissuePlatformTokens}. Callers that
|
|
7755
|
+
* need the full admin record in the HTTP response must fetch it from the
|
|
7756
|
+
* repository using the returned `session.userId`.
|
|
7757
|
+
*
|
|
7758
|
+
* @param rawRefreshToken - The raw opaque platform refresh token from the client.
|
|
7759
|
+
* @param ip - Client IP address.
|
|
7760
|
+
* @param userAgent - User-Agent header value.
|
|
7761
|
+
* @returns New tokens and minimal session identity.
|
|
7762
|
+
* @throws {@link AuthException} with `REFRESH_TOKEN_INVALID` if the token is invalid or expired.
|
|
7763
|
+
*/
|
|
7764
|
+
refresh(rawRefreshToken: string, ip: string, userAgent: string): Promise<RotatedTokenResult>;
|
|
7765
|
+
/**
|
|
7766
|
+
* Retrieves the full safe platform admin record for the currently authenticated admin.
|
|
7767
|
+
*
|
|
7768
|
+
* @param userId - Subject claim from the verified platform JWT.
|
|
7769
|
+
* @returns Safe admin object (credential fields excluded).
|
|
7770
|
+
* @throws {@link AuthException} with `TOKEN_INVALID` if the admin no longer exists.
|
|
7771
|
+
*/
|
|
7772
|
+
getMe(userId: string): Promise<SafeAuthPlatformUser>;
|
|
7773
|
+
/**
|
|
7774
|
+
* Revokes all active platform sessions for the given admin.
|
|
7775
|
+
*
|
|
7776
|
+
* Delegates to {@link AuthRedisService.invalidateUserSessions} which uses an atomic
|
|
7777
|
+
* Lua script to read the `psess:{userId}` SET, delete all session and grace-pointer
|
|
7778
|
+
* keys, and remove the SET itself in a single Redis round-trip. This prevents the
|
|
7779
|
+
* TOCTOU race that would arise from a non-atomic SMEMBERS + loop + DEL approach.
|
|
7780
|
+
*
|
|
7781
|
+
* The token epoch is then advanced, so outstanding platform **access** tokens die with
|
|
7782
|
+
* the refresh sessions rather than working on to expiry — "log out everywhere" that
|
|
7783
|
+
* leaves every access token alive is not what those words promise. Bumped after the
|
|
7784
|
+
* sweep for the same reason the dashboard flow bumps last: a failure in the sweep
|
|
7785
|
+
* leaves the epoch untouched and the operation visibly incomplete, instead of the
|
|
7786
|
+
* reverse, which would read as done while the sessions live on.
|
|
7787
|
+
*
|
|
7788
|
+
* @param userId - The platform admin's internal ID.
|
|
7789
|
+
*/
|
|
7790
|
+
/**
|
|
7791
|
+
* Derives the brute-force identifier for a platform login: `hmac('platform:{email}')`.
|
|
7792
|
+
*
|
|
7793
|
+
* HMAC rather than a bare digest keeps PII out of the Redis key and blocks dictionary
|
|
7794
|
+
* reversal, and the derived `hmacKey` keeps the identifier domain independent of the
|
|
7795
|
+
* JWT-signing secret. The `platform:` namespace is what keeps this counter disjoint from
|
|
7796
|
+
* the dashboard's: without it, a tenant whose id is literally `platform` produced a
|
|
7797
|
+
* byte-identical identifier, so unauthenticated dashboard logins against an operator's
|
|
7798
|
+
* address could lock that operator out of the console — and a successful one cleared the
|
|
7799
|
+
* lockout mid-attack.
|
|
7800
|
+
*
|
|
7801
|
+
* Single source on purpose: every platform site that touches the counter derives it here,
|
|
7802
|
+
* so no two of them can drift apart. The preimage is pinned by
|
|
7803
|
+
* `conformance/wire-contract.json` and shared byte-for-byte with rust-auth.
|
|
7804
|
+
*
|
|
7805
|
+
* @param email - The canonicalized address.
|
|
7806
|
+
* @returns Hex HMAC-SHA-256 identifier.
|
|
7807
|
+
*/
|
|
7808
|
+
private lockoutIdentifier;
|
|
7809
|
+
revokeAllPlatformSessions(userId: string): Promise<void>;
|
|
7810
|
+
}
|
|
7811
|
+
|
|
5225
7812
|
/**
|
|
5226
7813
|
* @fileoverview OAuth 2.0 Authorization Code flow service for @bymax-one/nest-auth.
|
|
5227
7814
|
*
|
|
@@ -5237,6 +7824,8 @@ declare class PasswordResetService {
|
|
|
5237
7824
|
* is the appropriate validation point. Without an `onOAuthLogin` implementation,
|
|
5238
7825
|
* any caller triggers `OAUTH_FAILED` — OAuth sign-in is fully disabled by default.
|
|
5239
7826
|
* Implement `onOAuthLogin` to enable it and enforce tenant membership.
|
|
7827
|
+
*
|
|
7828
|
+
* @layer Service
|
|
5240
7829
|
*/
|
|
5241
7830
|
|
|
5242
7831
|
/**
|
|
@@ -5244,7 +7833,7 @@ declare class PasswordResetService {
|
|
|
5244
7833
|
*
|
|
5245
7834
|
* Each OAuth provider is abstracted by an {@link OAuthProviderPlugin}. The
|
|
5246
7835
|
* service resolves the correct plugin by name and delegates the provider-specific
|
|
5247
|
-
*
|
|
7836
|
+
* operations (authorize URL, code exchange, profile fetch) to the plugin.
|
|
5248
7837
|
*/
|
|
5249
7838
|
declare class OAuthService {
|
|
5250
7839
|
private readonly plugins;
|
|
@@ -5259,7 +7848,7 @@ declare class OAuthService {
|
|
|
5259
7848
|
/**
|
|
5260
7849
|
* Initiates the OAuth 2.0 Authorization Code flow.
|
|
5261
7850
|
*
|
|
5262
|
-
*
|
|
7851
|
+
* Sequence:
|
|
5263
7852
|
* 1. Validates the `provider` format and resolves the named plugin.
|
|
5264
7853
|
* 2. Generates a 32-byte (64 hex char) cryptographically random state nonce.
|
|
5265
7854
|
* 3. Stores `os:{sha256(state)} → { tenantId }` in Redis with a 10-minute TTL.
|
|
@@ -5267,17 +7856,19 @@ declare class OAuthService {
|
|
|
5267
7856
|
* 5. Issues a 302 redirect via the Express `res` object.
|
|
5268
7857
|
*
|
|
5269
7858
|
* @param provider - Provider name matching a registered {@link OAuthProviderPlugin}.
|
|
5270
|
-
* @param tenantId - Tenant the user will join on successful login.
|
|
5271
|
-
*
|
|
5272
|
-
* to enforce tenant membership. Without
|
|
7859
|
+
* @param tenantId - Tenant the user will join on successful login, as named by the caller.
|
|
7860
|
+
* Superseded by the configured `tenantIdResolver` when there is one, and never validated
|
|
7861
|
+
* against the database — implement `onOAuthLogin` to enforce tenant membership. Without
|
|
7862
|
+
* the hook, OAuth sign-in is disabled.
|
|
7863
|
+
* @param req - Incoming Express request, read by the configured `tenantIdResolver`.
|
|
5273
7864
|
* @param res - Express response in passthrough mode (used for the 302 redirect).
|
|
5274
7865
|
* @throws `AuthException(OAUTH_FAILED)` when no plugin is registered for `provider`.
|
|
5275
7866
|
*/
|
|
5276
|
-
initiateOAuth(provider: string, tenantId: string, res: Response): Promise<void>;
|
|
7867
|
+
initiateOAuth(provider: string, tenantId: string, req: Request, res: Response): Promise<void>;
|
|
5277
7868
|
/**
|
|
5278
7869
|
* Processes the OAuth provider callback and issues auth tokens.
|
|
5279
7870
|
*
|
|
5280
|
-
*
|
|
7871
|
+
* Sequence:
|
|
5281
7872
|
* 1. Validates the `provider` format before touching Redis.
|
|
5282
7873
|
* 2. Validates the `state` nonce — atomically reads and deletes `os:{sha256(state)}`.
|
|
5283
7874
|
* Missing key → `OAUTH_FAILED` (expired, forged, or already consumed).
|
|
@@ -5299,6 +7890,8 @@ declare class OAuthService {
|
|
|
5299
7890
|
* @param provider - Provider name matching a registered plugin.
|
|
5300
7891
|
* @param code - Authorization code received on the callback URL.
|
|
5301
7892
|
* @param state - CSRF nonce received on the callback URL (must match the stored value).
|
|
7893
|
+
* @param stateCookie - Value of the `oauth_state` cookie planted by `initiateOAuth()`, or
|
|
7894
|
+
* `undefined` when the browser sent none. Must equal `state`; see the binding check below.
|
|
5302
7895
|
* @param ip - Client IP for session audit (truncated to 64 chars).
|
|
5303
7896
|
* @param userAgent - User-Agent string for session audit.
|
|
5304
7897
|
* @param headers - Raw request headers passed to the `onOAuthLogin` hook context.
|
|
@@ -5308,7 +7901,7 @@ declare class OAuthService {
|
|
|
5308
7901
|
* shapes to different responses (session cookies vs MFA-challenge cookie/redirect).
|
|
5309
7902
|
* @throws `AuthException(OAUTH_FAILED)` when state is invalid, expired, or the hook rejects.
|
|
5310
7903
|
*/
|
|
5311
|
-
handleCallback(provider: string, code: string, state: string, ip: string, userAgent: string, headers: Record<string, string | string[] | undefined>): Promise<AuthResult | OAuthMfaChallengeResult>;
|
|
7904
|
+
handleCallback(provider: string, code: string, state: string, stateCookie: string | undefined, ip: string, userAgent: string, headers: Record<string, string | string[] | undefined>): Promise<AuthResult | OAuthMfaChallengeResult>;
|
|
5312
7905
|
/**
|
|
5313
7906
|
* Resolves a plugin by name or throws `OAUTH_FAILED` when not found.
|
|
5314
7907
|
*
|
|
@@ -5325,7 +7918,7 @@ declare class OAuthService {
|
|
|
5325
7918
|
}
|
|
5326
7919
|
|
|
5327
7920
|
/**
|
|
5328
|
-
* HTTP header sanitization utility for @bymax-one/nest-auth.
|
|
7921
|
+
* @fileoverview HTTP header sanitization utility for @bymax-one/nest-auth.
|
|
5329
7922
|
*
|
|
5330
7923
|
* Removes sensitive headers before they are included in a HookContext
|
|
5331
7924
|
* or any audit/log output. Two complementary strategies are applied:
|
|
@@ -5333,6 +7926,8 @@ declare class OAuthService {
|
|
|
5333
7926
|
* 2. Pattern match — regex catch-all for custom secret-bearing headers.
|
|
5334
7927
|
*
|
|
5335
7928
|
* All output keys are normalized to lowercase for consistent downstream handling.
|
|
7929
|
+
*
|
|
7930
|
+
* @layer Utility
|
|
5336
7931
|
*/
|
|
5337
7932
|
|
|
5338
7933
|
/**
|
|
@@ -5365,6 +7960,11 @@ declare class OAuthService {
|
|
|
5365
7960
|
*/
|
|
5366
7961
|
declare function sanitizeHeaders(headers: Record<string, string | string[] | undefined>): Record<string, string | string[] | undefined>;
|
|
5367
7962
|
|
|
7963
|
+
/**
|
|
7964
|
+
* @fileoverview Timing normalization utility for anti-enumeration endpoints.
|
|
7965
|
+
*
|
|
7966
|
+
* @layer Utility
|
|
7967
|
+
*/
|
|
5368
7968
|
/**
|
|
5369
7969
|
* Returns a Promise that resolves after the specified number of milliseconds.
|
|
5370
7970
|
*
|
|
@@ -5389,14 +7989,14 @@ declare function sanitizeHeaders(headers: Record<string, string | string[] | und
|
|
|
5389
7989
|
* ```
|
|
5390
7990
|
*
|
|
5391
7991
|
* @param ms - Desired duration in milliseconds (clamped to 0–10 000).
|
|
5392
|
-
*
|
|
5393
|
-
* @public
|
|
5394
|
-
* Exported from `@bymax-one/nest-auth` for use in consumer-implemented auth
|
|
5395
|
-
* controllers that need to apply the same constant-time anti-enumeration
|
|
5396
|
-
* pattern to their own endpoints.
|
|
5397
7992
|
*/
|
|
5398
7993
|
declare function sleep(ms: number): Promise<void>;
|
|
5399
7994
|
|
|
7995
|
+
/**
|
|
7996
|
+
* @fileoverview Role-hierarchy utility for @bymax-one/nest-auth.
|
|
7997
|
+
*
|
|
7998
|
+
* @layer Utility
|
|
7999
|
+
*/
|
|
5400
8000
|
/**
|
|
5401
8001
|
* Checks whether a user role satisfies a required role in a denormalized hierarchy.
|
|
5402
8002
|
*
|
|
@@ -5427,4 +8027,34 @@ declare function sleep(ms: number): Promise<void>;
|
|
|
5427
8027
|
*/
|
|
5428
8028
|
declare function hasRole(userRole: string, requiredRole: string, hierarchy: Record<string, string[]>): boolean;
|
|
5429
8029
|
|
|
5430
|
-
|
|
8030
|
+
/** One route's limit: `limit` requests per `ttl` milliseconds, per client IP. */
|
|
8031
|
+
interface AuthRateLimitWindow {
|
|
8032
|
+
/** Requests allowed inside the window. */
|
|
8033
|
+
limit: number;
|
|
8034
|
+
/** Window length in milliseconds. */
|
|
8035
|
+
ttl: number;
|
|
8036
|
+
}
|
|
8037
|
+
/**
|
|
8038
|
+
* Declares the per-IP limit `AuthRateLimitGuard` enforces for a route.
|
|
8039
|
+
*
|
|
8040
|
+
* @remarks
|
|
8041
|
+
* The values come from `AUTH_THROTTLE_CONFIGS`, so a route is described once and both the
|
|
8042
|
+
* library's own guard and a host-side `@Throttle()` read the same numbers.
|
|
8043
|
+
*
|
|
8044
|
+
* @param config - The named entry from `AUTH_THROTTLE_CONFIGS`.
|
|
8045
|
+
* @returns The method decorator.
|
|
8046
|
+
*
|
|
8047
|
+
* @example
|
|
8048
|
+
* ```typescript
|
|
8049
|
+
* @AuthRateLimit(AUTH_THROTTLE_CONFIGS.login)
|
|
8050
|
+
* @Post('login')
|
|
8051
|
+
* login() { ... }
|
|
8052
|
+
* ```
|
|
8053
|
+
*
|
|
8054
|
+
* @layer Decorator
|
|
8055
|
+
*/
|
|
8056
|
+
declare function AuthRateLimit(config: {
|
|
8057
|
+
default: AuthRateLimitWindow;
|
|
8058
|
+
}): MethodDecorator;
|
|
8059
|
+
|
|
8060
|
+
export { AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, type SessionInfo as ActiveSessionInfo, AllowAllBreachChecker, type AuthErrorCode, AuthException, AuthExceptionFilter, type AuthFieldError, type AuthModuleAsyncOptions, type AuthPlatformUser, AuthRateLimit, AuthRateLimitGuard, type AuthRateLimitWindow, type AuthResult, AuthService, type AuthUser, Authenticated, type AuthenticatedRequest, BYMAX_AUTH_BREACH_CHECKER, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, type BearerAuthResponse, type BeforeRegisterResult, type BothAuthResponse, BruteForceService, BymaxAuthModule, type BymaxAuthModuleOptions, type BymaxAuthRateLimitOptions, ChangePasswordDto, type ClientIpSource, CommonPasswordChecker, type CookieAuthResponse, CreateInvitationDto, type CreateUserData, type CreateWithOAuthData, CurrentUser, type DashboardJwtPayload, EmailChangeService, ForgotPasswordDto, HibpBreachChecker, type HookContext, type IAuthHooks, type IEmailProvider, type IPasswordBreachChecker, type IPlatformUserRepository, IS_PUBLIC_KEY, type IUserRepository, InvitationService, type InviteData, JwtAuthGuard, JwtPlatformGuard, LoginDto, MfaChallengeDto, type MfaChallengeResult, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, type MfaSetupResult, type MfaTempPayload, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, type OAuthLoginResult, type OAuthMfaChallengeResult, type OAuthProfile, type OAuthProviderPlugin, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, type PlatformAuthResult, PlatformAuthService, type PlatformAuthenticatedRequest, type PlatformBearerAuthResponse, type PlatformJwtPayload, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, type ResolvedOptions, Roles, RolesGuard, type RotatedTokenResult, SKIP_MFA_KEY, type SafeAuthPlatformUser, type SafeAuthUser, SelfOrAdminGuard, type SessionInfo$1 as SessionInfo, SessionService, SkipMfa, TokenDeliveryService, TrustedOriginGuard, type UpdateMfaData, type UpdatePlatformMfaData, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WS_TICKET_TTL_SECONDS, WsJwtGuard, WsTicketService, type WsTicketSnapshot, createAuthValidationPipe, decrypt, encrypt, generateSecureToken, hasRole, hmacSha256, reduceToBaseWord, sanitizeHeaders, sha256, sleep, timingSafeCompare };
|