@bymax-one/nest-auth 1.1.1 → 1.2.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.
@@ -501,6 +501,27 @@ interface BymaxAuthModuleOptions {
501
501
  * @throws {Error} When the value fails validation at module initialisation.
502
502
  */
503
503
  costFactor?: number;
504
+ /**
505
+ * Minimum password length the deployment accepts. Default: `15`.
506
+ *
507
+ * NIST SP 800-63B-4 §3.1.1.1 requires 15 characters for a password used as a SINGLE
508
+ * authentication factor, and permits 8 only when the password is part of multi-factor
509
+ * authentication. MFA in this library is opt-in per user, so the default deployment is
510
+ * single-factor and 15 is the number that applies. Lower it to 8 — the structural floor the
511
+ * DTOs enforce, and the lowest the standard allows under any circumstance — only in a
512
+ * deployment that makes MFA mandatory.
513
+ *
514
+ * @remarks
515
+ * `costFactor` sets the price of one guess; this sets how many guesses there are. Only the
516
+ * second is what an offline attacker actually runs out of, and the breach and common-password
517
+ * screens remove passwords that are already *known*, not short ones nobody has seen yet.
518
+ *
519
+ * Deliberately not paired with any composition rule: the same clause says verifiers SHALL
520
+ * NOT impose them, and none of the password DTOs carries one.
521
+ *
522
+ * @throws {Error} When the value is not an integer in `[8, 128]`.
523
+ */
524
+ minLength?: number;
504
525
  /**
505
526
  * scrypt block size parameter (r).
506
527
  * Default: `8`
@@ -539,19 +560,38 @@ interface BymaxAuthModuleOptions {
539
560
  * Default: `'cookie'`
540
561
  */
541
562
  tokenDelivery?: 'cookie' | 'bearer' | 'both';
563
+ /**
564
+ * The deployment environment, supplied explicitly.
565
+ *
566
+ * This is the ONLY input that answers "is this production". The library never reads the
567
+ * ambient `process.env`, and it is secure by default: an unset value is `'production'`, so
568
+ * `secureCookies` resolves to `true` and the production-gated OAuth-redirect checks apply
569
+ * unless the host opts into `'development'` or `'test'`.
570
+ *
571
+ * Default: `'production'`.
572
+ *
573
+ * @remarks
574
+ * This replaces reading `process.env['NODE_ENV'] === 'production'`. That test decided cookie
575
+ * `Secure`, OAuth callback HTTPS enforcement and three redirect validations, and it failed
576
+ * open on every near miss — unset, `'staging'`, `'prod'`, or `'production '` with a trailing
577
+ * space each silently took the insecure branch. Whether a deployment is production is
578
+ * something the deployer knows and the process environment only hints at, so it is now passed
579
+ * in rather than sniffed. Matches `Environment` in rust-auth.
580
+ */
581
+ environment?: 'production' | 'development' | 'test';
542
582
  /**
543
583
  * Whether to set the `Secure` flag on auth cookies.
544
584
  *
545
585
  * When `true`, cookies are only sent over HTTPS. When `false`, cookies are
546
586
  * sent over HTTP as well (useful for local development).
547
587
  *
548
- * Default: `process.env['NODE_ENV'] === 'production'` (evaluated once at module
549
- * startup via `resolveOptions()` — not re-evaluated per request).
588
+ * Default: `true`, unless {@link BymaxAuthModuleOptions.environment} is
589
+ * `'development'` or `'test'`. Evaluated once at module startup via
590
+ * `resolveOptions()` — not re-evaluated per request.
550
591
  *
551
592
  * @remarks
552
- * Override this explicitly in staging environments that do not set
553
- * `NODE_ENV=production` but are served over HTTPS, to ensure cookies are
554
- * marked Secure regardless of the environment variable.
593
+ * Set this explicitly to `true` in a non-production environment that is nonetheless served
594
+ * over HTTPS, so the cookies are marked `Secure` there too.
555
595
  */
556
596
  secureCookies?: boolean;
557
597
  /**
@@ -1316,7 +1356,7 @@ declare const BYMAX_AUTH_REDIS_CLIENT: unique symbol;
1316
1356
  * interface-extension compatibility check with `exactOptionalPropertyTypes`,
1317
1357
  * which rejects intersection widening of optional function properties.
1318
1358
  */
1319
- type ResolvedOptions = Omit<BymaxAuthModuleOptions, 'jwt' | 'password' | 'tokenDelivery' | 'cookies' | 'sessions' | 'bruteForce' | 'passwordReset' | 'emailVerification' | 'platform' | 'invitations' | 'controllers' | 'blockedStatuses' | 'redisNamespace' | 'routePrefix' | 'userStatusCacheTtlSeconds' | 'secureCookies' | 'mfa' | 'rateLimit'> & {
1359
+ type ResolvedOptions = Omit<BymaxAuthModuleOptions, 'jwt' | 'password' | 'tokenDelivery' | 'cookies' | 'sessions' | 'bruteForce' | 'passwordReset' | 'emailVerification' | 'platform' | 'invitations' | 'controllers' | 'blockedStatuses' | 'redisNamespace' | 'routePrefix' | 'userStatusCacheTtlSeconds' | 'environment' | 'secureCookies' | 'mfa' | 'rateLimit'> & {
1320
1360
  jwt: Required<Omit<BymaxAuthModuleOptions['jwt'], 'previousSecrets' | 'issuer' | 'audience'>> & Pick<BymaxAuthModuleOptions['jwt'], 'previousSecrets' | 'issuer' | 'audience'>;
1321
1361
  password: Required<NonNullable<BymaxAuthModuleOptions['password']>>;
1322
1362
  tokenDelivery: NonNullable<BymaxAuthModuleOptions['tokenDelivery']>;
@@ -1337,6 +1377,12 @@ type ResolvedOptions = Omit<BymaxAuthModuleOptions, 'jwt' | 'password' | 'tokenD
1337
1377
  redisNamespace: string;
1338
1378
  routePrefix: string;
1339
1379
  userStatusCacheTtlSeconds: number;
1380
+ /**
1381
+ * The deployment environment as the host declared it. The only input that answers "is this
1382
+ * production"; the library never reads `process.env`. See
1383
+ * {@link BymaxAuthModuleOptions.environment}.
1384
+ */
1385
+ environment: 'production' | 'development' | 'test';
1340
1386
  /** `true` if auth cookies should carry the `Secure` flag. */
1341
1387
  secureCookies: boolean;
1342
1388
  /**
@@ -2193,18 +2239,30 @@ interface IEmailProvider {
2193
2239
  */
2194
2240
  sendMfaDisabledNotification(email: string, locale?: string): Promise<void>;
2195
2241
  /**
2196
- * Sends a security alert when a new session is detected from an unrecognized
2197
- * device or location.
2242
+ * Sends a security alert about a newly established session.
2198
2243
  *
2199
- * Called after a successful login when new-session detection is enabled. The
2200
- * email should display the device description, IP address, and session hash so
2201
- * the user can identify whether the login was authorized.
2244
+ * **This library never calls it.** The method is optional, and it is here as a typed
2245
+ * signature for you to call from the {@link IAuthHooks.onNewSession} hook — which the
2246
+ * library does fire, on every session it creates, with the same {@link SessionInfo} this
2247
+ * takes.
2248
+ *
2249
+ * The alert deliberately does not live inside the library, because the library cannot send
2250
+ * it well. Without device recognition it fires on *every* login, and an alert that arrives
2251
+ * on every login is one the user learns to dismiss — at which point the control has stopped
2252
+ * existing while still appearing to be in place. Recognizing a device means keeping a
2253
+ * per-user device history, and the consumer already has one (or can key it to their own
2254
+ * user record); the library would have to invent that state in the Redis keyspace it shares
2255
+ * with rust-auth, which is a contract change to solve a problem the caller is better placed
2256
+ * to solve.
2257
+ *
2258
+ * So: decide in your `onNewSession` hook whether the session is worth alerting about, and
2259
+ * call this when it is.
2202
2260
  *
2203
2261
  * @param email - Recipient's email address.
2204
2262
  * @param sessionInfo - Device, IP, and session identifier details.
2205
2263
  * @param locale - BCP 47 locale tag for email language (e.g. `'en'`, `'pt-BR'`).
2206
2264
  */
2207
- sendNewSessionAlert(email: string, sessionInfo: SessionInfo$1, locale?: string): Promise<void>;
2265
+ sendNewSessionAlert?(email: string, sessionInfo: SessionInfo$1, locale?: string): Promise<void>;
2208
2266
  /**
2209
2267
  * Sends a tenant invitation email to a prospective member.
2210
2268
  *
@@ -3878,6 +3936,30 @@ declare class AuthRedisService {
3878
3936
  * @returns How many dead members were dropped.
3879
3937
  */
3880
3938
  pruneExpiredGraceMembers(setKey: string, gracePrefix: string): Promise<number>;
3939
+ /**
3940
+ * Drops index members whose own key is gone, and leaves every other member in place.
3941
+ *
3942
+ * A reader that walks `sess:{userId}` learns a session is stale from something *about* the
3943
+ * session — a detail record that is missing, unreadable or malformed. None of those facts is
3944
+ * the session. The credential is the `rt:{hash}` key, and only its absence means the member
3945
+ * names nothing: a live `rt:` with no `sd:` is a session that still opens the account.
3946
+ *
3947
+ * Removing such a member is not a tidy-up, it is a revocation bypass. `invalidateUserSessions`
3948
+ * revokes what the index names, so a member dropped while its `rt:` key lives produces a
3949
+ * session that survives "sign out everywhere" and keeps rotating, while the user is told every
3950
+ * device was signed out — and the un-indexing is triggered by the user's own session listing.
3951
+ *
3952
+ * So the caller supplies candidates and this decides, with `EXISTS` as the only evidence
3953
+ * admitted. The check and the `SREM` share one script because they must: a candidate whose
3954
+ * `rt:` key is written between the two would otherwise be dropped anyway. A Redis fault makes
3955
+ * the whole script fail rather than prune, which is the safe direction — an index that keeps a
3956
+ * dead member costs a wasted read, an index that loses a live one costs the revocation.
3957
+ *
3958
+ * @param setKey - The un-namespaced index key (`sess:{id}` or `psess:{id}`).
3959
+ * @param members - Candidate members, each a full key suffix (`rt:{hash}`).
3960
+ * @returns How many candidates were actually dropped.
3961
+ */
3962
+ pruneDeadMembers(setKey: string, members: string[]): Promise<number>;
3881
3963
  /**
3882
3964
  * Atomically deletes every refresh session belonging to one identity plane.
3883
3965
  *
@@ -4969,7 +5051,14 @@ declare class AcceptInvitationDto {
4969
5051
  * Plaintext password for the new account.
4970
5052
  *
4971
5053
  * @remarks
4972
- * Minimum 8 characters for usability; maximum 128 characters as a practical
5054
+ * The 8-character floor here is STRUCTURAL, not the deployment's policy: it is the lowest
5055
+ * NIST SP 800-63B-4 §3.1.1.1 permits under any circumstance, and it is what a decorator
5056
+ * can express — decorators are evaluated when the class is defined, before any
5057
+ * configuration exists. The policy floor is `password.minLength` (default 15, as the
5058
+ * standard requires of a single-factor password), enforced by `PasswordService` and
5059
+ * answering this same `auth.validation` code and details shape.
5060
+ *
5061
+ * Maximum 128 characters as a practical
4973
5062
  * input bound to prevent DoS via pathological scrypt inputs.
4974
5063
  * The service layer hashes this value immediately — it is never logged or
4975
5064
  * persisted in plaintext.
@@ -5263,7 +5352,14 @@ declare class RegisterDto {
5263
5352
  * Plaintext password supplied by the user.
5264
5353
  *
5265
5354
  * @remarks
5266
- * Minimum 8 characters for usability; maximum 128 characters as a practical
5355
+ * The 8-character floor here is STRUCTURAL, not the deployment's policy: it is the lowest
5356
+ * NIST SP 800-63B-4 §3.1.1.1 permits under any circumstance, and it is what a decorator
5357
+ * can express — decorators are evaluated when the class is defined, before any
5358
+ * configuration exists. The policy floor is `password.minLength` (default 15, as the
5359
+ * standard requires of a single-factor password), enforced by `PasswordService` and
5360
+ * answering this same `auth.validation` code and details shape.
5361
+ *
5362
+ * Maximum 128 characters as a practical
5267
5363
  * input bound. The service layer hashes this value immediately after receipt —
5268
5364
  * it is never logged or persisted in plaintext.
5269
5365
  */
@@ -5351,7 +5447,14 @@ declare class ChangePasswordDto {
5351
5447
  currentPassword: string;
5352
5448
  /**
5353
5449
  * New plaintext password chosen by the user.
5354
- * Minimum 8 characters for usability; maximum 128 characters as a practical bound.
5450
+ * The 8-character floor here is STRUCTURAL, not the deployment's policy: it is the lowest
5451
+ * NIST SP 800-63B-4 §3.1.1.1 permits under any circumstance, and it is what a decorator
5452
+ * can express — decorators are evaluated when the class is defined, before any
5453
+ * configuration exists. The policy floor is `password.minLength` (default 15, as the
5454
+ * standard requires of a single-factor password), enforced by `PasswordService` and
5455
+ * answering this same `auth.validation` code and details shape.
5456
+ *
5457
+ * Maximum 128 characters as a practical bound.
5355
5458
  * Hashed immediately by the service layer — never persisted in plaintext.
5356
5459
  */
5357
5460
  newPassword: string;
@@ -5380,7 +5483,14 @@ declare class ResetPasswordDto {
5380
5483
  email: string;
5381
5484
  /**
5382
5485
  * New plaintext password chosen by the user.
5383
- * Minimum 8 characters for usability; maximum 128 characters as a practical bound.
5486
+ * The 8-character floor here is STRUCTURAL, not the deployment's policy: it is the lowest
5487
+ * NIST SP 800-63B-4 §3.1.1.1 permits under any circumstance, and it is what a decorator
5488
+ * can express — decorators are evaluated when the class is defined, before any
5489
+ * configuration exists. The policy floor is `password.minLength` (default 15, as the
5490
+ * standard requires of a single-factor password), enforced by `PasswordService` and
5491
+ * answering this same `auth.validation` code and details shape.
5492
+ *
5493
+ * Maximum 128 characters as a practical bound.
5384
5494
  * Hashed immediately by the service layer — never persisted in plaintext.
5385
5495
  */
5386
5496
  newPassword: string;
@@ -5636,6 +5746,7 @@ declare class PasswordService {
5636
5746
  private readonly breachChecker;
5637
5747
  private readonly logger;
5638
5748
  private readonly N;
5749
+ private readonly minLength;
5639
5750
  private readonly r;
5640
5751
  private readonly p;
5641
5752
  private readonly maxmem;
@@ -5652,6 +5763,43 @@ declare class PasswordService {
5652
5763
  * // '$scrypt$ln=17,r=8,p=1$YmFzZTY0c2FsdA$…'
5653
5764
  * ```
5654
5765
  */
5766
+ /**
5767
+ * The whole password policy, applied wherever a password is being *set*.
5768
+ *
5769
+ * One entry point so the four call sites — registration, reset, authenticated change and
5770
+ * invitation acceptance — cannot drift into applying different halves of it.
5771
+ *
5772
+ * Order matters: length first, because it is decided locally and for free, and the breach
5773
+ * check may reach a network corpus. A password refused for being short should not cost a
5774
+ * round trip, and should not be sent anywhere first.
5775
+ *
5776
+ * @param plain - The plaintext password the user is trying to set.
5777
+ * @param field - The request field to name in a length failure's `details`.
5778
+ * @throws {@link AuthException} with `VALIDATION` when it is too short, or
5779
+ * `PASSWORD_COMPROMISED` when the corpus knows it.
5780
+ */
5781
+ assertAcceptable(plain: string, field: string): Promise<void>;
5782
+ /**
5783
+ * Rejects a password shorter than the configured minimum.
5784
+ *
5785
+ * The DTOs carry a structural `@MinLength(8)` — the lowest NIST SP 800-63B-4 permits under any
5786
+ * circumstance — and this is the deployment's policy on top of it, which is configurable and
5787
+ * defaults to 15 because that is what §3.1.1.1 requires of a single-factor password. The check
5788
+ * lives here rather than in a decorator because a decorator is evaluated when the class is
5789
+ * defined, before any configuration exists.
5790
+ *
5791
+ * It answers the same `auth.validation` code and the same `{ field, message }[]` details the
5792
+ * validation pipe produces for a length failure, so a client already handling a short password
5793
+ * sees no new shape and the shared error catalog gains no entry. The breach and
5794
+ * common-password screens run after: they remove passwords that are already *known*, which is
5795
+ * a different question from how many guesses the password is worth.
5796
+ *
5797
+ * @param plain - The plaintext password the user is trying to set.
5798
+ * @param field - The request field to name in `details`, so the message points at the input
5799
+ * the caller actually sent (`password` on registration, `newPassword` on a reset).
5800
+ * @throws {@link AuthException} with `VALIDATION` when the password is too short.
5801
+ */
5802
+ assertLongEnough(plain: string, field: string): void;
5655
5803
  /**
5656
5804
  * Rejects a password that appears in a known-breach corpus.
5657
5805
  *
@@ -5801,9 +5949,11 @@ declare class SessionService {
5801
5949
  *
5802
5950
  * Reads all `rt:`-prefixed members from `sess:{userId}`, fetches the
5803
5951
  * corresponding `sd:{hash}` detail records, and marks the caller's own
5804
- * session via `isCurrent`. Stale members (no matching detail record or
5805
- * unparseable JSON) are removed from the SET asynchronously (fire-and-forget)
5806
- * and excluded from the result.
5952
+ * session via `isCurrent`. A member whose detail record is missing, unreadable
5953
+ * or malformed is excluded from the result, and removed from the SET
5954
+ * asynchronously (fire-and-forget) only if its `rt:` key is also gone — see
5955
+ * {@link AuthRedisService.pruneDeadMembers} for why the detail record alone
5956
+ * does not settle it.
5807
5957
  *
5808
5958
  * Results are sorted by `createdAt` descending (newest session first).
5809
5959
  *
@@ -6758,7 +6908,9 @@ declare class ConfirmEmailChangeDto {
6758
6908
  *
6759
6909
  * **The current password is re-proved.** A stolen access token alone cannot move the recovery
6760
6910
  * address — the thief has to already hold the credential that would let them take the account
6761
- * anyway.
6911
+ * anyway. It is also why no session is revoked here: anyone who can complete this flow could
6912
+ * already sign in, so ending the caller's other sessions would cost the user their devices and
6913
+ * buy nothing. A password *change* does revoke, because there the factor itself moved.
6762
6914
  *
6763
6915
  * **The new address is proved before it is adopted.** A token goes to it and nowhere else, so
6764
6916
  * a typo cannot lock the owner out of their own account and an attacker cannot point the
@@ -7189,6 +7341,45 @@ declare class MfaService {
7189
7341
  * @throws `MFA_INVALID_CODE` if the submitted TOTP code is incorrect.
7190
7342
  */
7191
7343
  disable(userId: string, code: string, ip: string, userAgent: string, context?: 'dashboard' | 'platform'): Promise<void>;
7344
+ /**
7345
+ * Removes a user's second factor without their TOTP code, for a support desk facing a user
7346
+ * who has lost their authenticator AND their recovery codes.
7347
+ *
7348
+ * Every self-service exit from MFA needs the factor itself: {@link disable} wants a valid
7349
+ * TOTP code, and the recovery codes want the codes. A user who has lost both is locked out
7350
+ * permanently, by the control that exists to protect them — ASVS v5 §6.1.1 asks for an
7351
+ * administrative path out for exactly that reason.
7352
+ *
7353
+ * **Authorising the caller is the consumer's job.** The library deliberately ships no route
7354
+ * for this, the same decision and for the same reason as {@link AuthService.unlockAccount}:
7355
+ * who may reset whom is a question only the host application can answer, and all 39 routes
7356
+ * this library does ship are scoped to the caller's own account.
7357
+ *
7358
+ * Idempotent: resetting an account that has no second factor is a no-op, so a support desk
7359
+ * retrying does not get an error for a job already done.
7360
+ *
7361
+ * Three things happen beyond clearing the record, and none of them are optional:
7362
+ *
7363
+ * - **Sessions are invalidated and the token epoch is bumped**, so access tokens carrying
7364
+ * `mfaVerified: true` die with the factor rather than outliving it.
7365
+ * - **The user is notified**, through the same channel {@link disable} uses. An
7366
+ * administrative reset that the account holder cannot see is an account-takeover path:
7367
+ * an attacker who reaches the support desk removes the second factor silently. The
7368
+ * notification is what makes it an event the owner can detect and dispute.
7369
+ * - **It is logged** under its own prefix, so an administrative removal is distinguishable
7370
+ * from a user-initiated one in the library's own log.
7371
+ *
7372
+ * The `afterMfaDisabled` hook fires too, so consumer-side alerting keeps working. It is not
7373
+ * given a separate hook: the consumer is the one calling this method, so they already know
7374
+ * an administrative reset happened — the hook exists to tell them about the paths they do
7375
+ * not initiate.
7376
+ *
7377
+ * @param userId - Internal ID of the user whose second factor is being removed.
7378
+ * @param context - Which identity plane the user belongs to: `'dashboard'` (default) or
7379
+ * `'platform'`. Must match the plane the account lives in, or the lookup misses.
7380
+ * @throws `TOKEN_INVALID` if no user with that ID exists in the given plane.
7381
+ */
7382
+ resetMfa(userId: string, context?: 'dashboard' | 'platform'): Promise<void>;
7192
7383
  /**
7193
7384
  * Regenerates the user's MFA recovery codes after verifying a current TOTP code.
7194
7385
  *
@@ -7921,7 +8112,9 @@ declare class OAuthService {
7921
8112
  * Sequence:
7922
8113
  * 1. Validates the `provider` format and resolves the named plugin.
7923
8114
  * 2. Generates a 32-byte (64 hex char) cryptographically random state nonce.
7924
- * 3. Stores `os:{sha256(state)} → { tenantId }` in Redis with a 10-minute TTL.
8115
+ * 3. Stores `os:{sha256(state)} → { provider, tenantId, codeVerifier }` in Redis with a
8116
+ * 10-minute TTL. `provider` is what the callback checks itself against (RFC 9700
8117
+ * mix-up defence).
7925
8118
  * 4. Constructs the provider's authorization URL via `plugin.authorizeUrl(state)`.
7926
8119
  * 5. Issues a 302 redirect via the Express `res` object.
7927
8120
  *