@bymax-one/nest-auth 1.2.0 → 1.3.1

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 CHANGED
@@ -7,6 +7,127 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.3.1] - 2026-08-08
11
+
12
+ Adds the revocation checker and the overridable default auth-email provider, carries the tenant
13
+ on the email port, and refreshes the mutation figures the packaged README and CHANGELOG report.
14
+ All of it stays in the 1.3.x line: there are no published dependents, so nothing installed breaks.
15
+
16
+ ### Added
17
+
18
+ - **`DefaultAuthEmailProvider` is exported**, the overridable default that fills the email port so a
19
+ derived backend no longer hand-writes the same bridge onto its notification channel. It carries
20
+ the policy that should not be copied per backend: HTML escaping on a path that renders
21
+ caller-chosen text (an inviter's name, a tenant's name, the address an account moved to), the
22
+ NIST SP 800-63B notification catalogue (a password-changed notice, MFA enable/disable notices, an
23
+ email-changed notice to the _previous_ address), and a swallow-and-log failure policy so a down
24
+ channel never turns "enable MFA" into a failed request. It sends through `AuthEmailSink`, a port
25
+ narrow enough that the class imports no concrete mailer — `@bymax-one/nest-notification`'s
26
+ `EmailService` satisfies it structurally — and it consumes the tenant the email port now carries,
27
+ so a multi-tenant channel can attribute and route each message. Pass `messages` to override any
28
+ subset of the copy with a product's own wording or branding; the escaping and failure policy
29
+ still apply. It closes bymaxone/nest-notification#54.
30
+
31
+ - **`AuthRevocationService` is exported**, answering whether a verified access token has been
32
+ revoked across both channels the module writes to — the per-token blacklist a logout writes and
33
+ the per-user epoch a password reset or revoke-all advances. It closes bymaxone/nest-auth#92: a
34
+ backend bridging this library to a realtime transport can inject it and consult the same two
35
+ channels the HTTP guards do, instead of verifying a token's signature and granting a stream that
36
+ outlives every revocation window. The `JwtAuthGuard`, `WsJwtGuard` and `JwtPlatformGuard` now
37
+ delegate to it rather than each carrying its own copy of the two Redis reads — one source of
38
+ truth for the check, so a fix reaches all three and every consumer at once. No behaviour changed:
39
+ the guards' full suites pass unmodified.
40
+
41
+ ### Changed
42
+
43
+ - **`IEmailProvider` carries the tenant on every method.** Each of the ten methods now
44
+ takes `tenantId: string` as its first parameter, ahead of the recipient address. A notification
45
+ backend serving more than one tenant could not, before this, tell which tenant a password-reset
46
+ or invitation email belonged to: it saw only an address, so it could not pick the right sender
47
+ identity, branding, locale default or audit stream. The tenant was known at every call site — a
48
+ dashboard user carries its own `tenantId`, and a cross-tenant platform admin is attributed to the
49
+ `'platform'` plane, mirroring the `pep:` epoch namespace — it simply was not being passed. It
50
+ closes bymaxone/nest-auth#93.
51
+
52
+ **Apply to a derived backend.** Any `IEmailProvider` implementation must add `tenantId: string`
53
+ as the first argument of every method it defines and route on it as its backend requires; a
54
+ provider that ignores tenancy can name the parameter `_tenantId` and change nothing else. The
55
+ bundled `NoOpEmailProvider` already conforms.
56
+
57
+ Migrate **every** method, not only the one the compiler flags. Because the added argument is a
58
+ `string` prepended to methods whose other arguments are also strings, a stale
59
+ `sendPasswordResetToken(email, token)` stays assignable to the new type — TypeScript accepts an
60
+ implementation with fewer parameters — so it compiles while binding `tenantId` to the recipient
61
+ at runtime. Only `sendInvitation`, whose second argument is an object, fails compilation. Fixing
62
+ that one is not proof the rest are done; the surest path is to extend the `DefaultAuthEmailProvider`
63
+ this release adds rather than hand-write the port.
64
+
65
+ The library has no published dependents yet, so this breaks nothing already released and ships in
66
+ the ordinary `1.3.x` line rather than as a major — SemVer's promise is to existing consumers, and
67
+ there are none to break.
68
+
69
+ - **The mutation score is re-measured rather than restated.** The last recorded run was
70
+ 2026-07-28, before 1.1.0, 1.1.1, 1.2.0, 1.3.0 and the third security audit, and the README still
71
+ quoted its figures: 3,474 faults killed against 2,458 tests. A cold run on 2026-08-08 —
72
+ incremental baseline deleted, nothing inherited, and now covering this release's own additions —
73
+ puts the library at **100.00% with 4,870 mutants detected (4,849 killed, 21 timed out), no
74
+ survivors and none without coverage**, out of 7,718 instrumented across 147 files. The suite
75
+ behind it is **3,547 tests** (3,420 unit, 127 end-to-end). All five subpaths are individually at
76
+ 100.00%.
77
+
78
+ The count of documented equivalents is now reported as the number it is — **350 mutants under
79
+ 217 `// Stryker disable` directives** — instead of "the handful that no test can kill". Nothing
80
+ about them changed; the README's description of them had simply stopped matching their size, and
81
+ a number that is written down can be audited.
82
+
83
+ - **`docs/mutation_testing_results.md` records the run** in a new dated section, with the full
84
+ outcome table, the per-subpath split, and where the twenty-one timeouts sit. The earlier
85
+ sections are left as they were — they are the record of the passes that produced them. The
86
+ reproduce instructions are corrected in the same pass: they named `pnpm mutation:incremental`,
87
+ which is not a script in this package, and promised a ten-minute run that now takes
88
+ forty-eight at `--concurrency 2`.
89
+
90
+ ## [1.3.0] - 2026-08-08
91
+
92
+ Minor rather than patch because the API now accepts a request it previously rejected: with a
93
+ `tenantIdResolver` configured, `tenantId` may be omitted from the body. Nothing a consumer sends
94
+ today stops working, and no option changed meaning.
95
+
96
+ ### Fixed
97
+
98
+ - **`tenantId` is optional on every DTO that carries it**, so a deployment that configures
99
+ `tenantIdResolver` no longer forces its clients to send a value the server discards. The
100
+ option's whole purpose is that the resolved tenant wins and the body's is ignored, but the nine
101
+ DTOs declared the field with `@IsString() @IsNotEmpty()` and no `@IsOptional()`, so a request
102
+ that omitted it was rejected before any service ran. The two configurations were both wrong in
103
+ opposite directions: without a resolver the body named the tenant and was trusted, and with one
104
+ the body was mandatory and ignored.
105
+
106
+ `resolveTenantId` now refuses a request that no resolver and no body value can scope, answering
107
+ `auth.validation` with the same `{ field, message }[]` shape the validation pipe produces. It is
108
+ refused rather than defaulted deliberately: inventing a tenant name would gather into one scope
109
+ every account a misconfigured deployment created. `null` counts as absent there, because
110
+ `@IsOptional()` skips validation for `null` as well as for `undefined` — a caller may send
111
+ `tenantId: null` past every DTO constraint, and admitting it would carry `null` into the
112
+ tenant-scoped lookups and into the Redis and HMAC keys built from it.
113
+
114
+ Nothing changes for a consumer that sends `tenantId` today, with or without a resolver.
115
+
116
+ - **`jwt.absoluteSessionLifetimeDays` is documented as the 30-day default it actually is.** The
117
+ option's doc comment, the README's option table, the README's "deliberately off by default"
118
+ note and the specification's table all still described the pre-1.2.0 behaviour, where the cap
119
+ was off unless a deployment asked for it. 1.2.0 turned it on at 30 days as a security fix and
120
+ the prose did not follow, so the surface a consumer reads in their editor argued for planning
121
+ around sessions that never end.
122
+
123
+ ### Changed
124
+
125
+ - `AuthService.register`, `AuthService.login`, `AuthService.verifyEmail`,
126
+ `AuthService.resendVerificationEmail` and `OAuthService.initiateOAuth` accept `tenantId` as
127
+ optional, matching the DTOs that feed them. The password-reset flows now read the resolved
128
+ tenant from the local binding rather than from the reassigned DTO, which is the same value and
129
+ removes the question of whether the reassignment happened.
130
+
10
131
  ## [1.2.0] - 2026-08-08
11
132
 
12
133
  Carries the third security audit and the findings that surfaced while driving the mutation
@@ -1152,7 +1273,9 @@ ever installable.
1152
1273
  - Phase 4 password-reset tests cover: both `token` and `otp` flows, mutual exclusivity validation, `verifiedToken` exchange, resend cooldown, anti-enumeration (no error on unknown email), and session invalidation on reset
1153
1274
  - Phase 5 tests cover: platform login with MFA path and brute-force lockout, `JwtPlatformGuard` cross-context rejection, `PlatformRolesGuard` hierarchy enforcement, OAuth CSRF state lifecycle, `onOAuthLogin` hook resolution strategies, and invitation role-authorization + acceptance single-use enforcement
1154
1275
 
1155
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.2.0...HEAD
1276
+ [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.3.1...HEAD
1277
+ [1.3.1]: https://github.com/bymaxone/nest-auth/compare/v1.3.0...v1.3.1
1278
+ [1.3.0]: https://github.com/bymaxone/nest-auth/compare/v1.2.0...v1.3.0
1156
1279
  [1.2.0]: https://github.com/bymaxone/nest-auth/compare/v1.1.1...v1.2.0
1157
1280
  [1.1.1]: https://github.com/bymaxone/nest-auth/compare/v1.1.0...v1.1.1
1158
1281
  [1.1.0]: https://github.com/bymaxone/nest-auth/compare/v1.0.11...v1.1.0
package/README.md CHANGED
@@ -299,7 +299,12 @@ export class ResendEmailProvider implements IEmailProvider {
299
299
  private readonly from = 'no-reply@example.com'
300
300
  private readonly appUrl = process.env.APP_URL!
301
301
 
302
- async sendPasswordResetToken(email: string, token: string, _locale?: string): Promise<void> {
302
+ async sendPasswordResetToken(
303
+ _tenantId: string,
304
+ email: string,
305
+ token: string,
306
+ _locale?: string
307
+ ): Promise<void> {
303
308
  const url = `${this.appUrl}/reset-password?token=${encodeURIComponent(token)}`
304
309
  await this.client.emails.send({
305
310
  from: this.from,
@@ -309,7 +314,12 @@ export class ResendEmailProvider implements IEmailProvider {
309
314
  })
310
315
  }
311
316
 
312
- async sendPasswordResetOtp(email: string, otp: string, _locale?: string): Promise<void> {
317
+ async sendPasswordResetOtp(
318
+ _tenantId: string,
319
+ email: string,
320
+ otp: string,
321
+ _locale?: string
322
+ ): Promise<void> {
313
323
  await this.client.emails.send({
314
324
  from: this.from,
315
325
  to: email,
@@ -318,7 +328,12 @@ export class ResendEmailProvider implements IEmailProvider {
318
328
  })
319
329
  }
320
330
 
321
- async sendEmailVerificationOtp(email: string, otp: string, _locale?: string): Promise<void> {
331
+ async sendEmailVerificationOtp(
332
+ _tenantId: string,
333
+ email: string,
334
+ otp: string,
335
+ _locale?: string
336
+ ): Promise<void> {
322
337
  await this.client.emails.send({
323
338
  from: this.from,
324
339
  to: email,
@@ -327,7 +342,11 @@ export class ResendEmailProvider implements IEmailProvider {
327
342
  })
328
343
  }
329
344
 
330
- async sendMfaEnabledNotification(email: string, _locale?: string): Promise<void> {
345
+ async sendMfaEnabledNotification(
346
+ _tenantId: string,
347
+ email: string,
348
+ _locale?: string
349
+ ): Promise<void> {
331
350
  await this.client.emails.send({
332
351
  from: this.from,
333
352
  to: email,
@@ -336,7 +355,11 @@ export class ResendEmailProvider implements IEmailProvider {
336
355
  })
337
356
  }
338
357
 
339
- async sendMfaDisabledNotification(email: string, _locale?: string): Promise<void> {
358
+ async sendMfaDisabledNotification(
359
+ _tenantId: string,
360
+ email: string,
361
+ _locale?: string
362
+ ): Promise<void> {
340
363
  await this.client.emails.send({
341
364
  from: this.from,
342
365
  to: email,
@@ -346,6 +369,7 @@ export class ResendEmailProvider implements IEmailProvider {
346
369
  }
347
370
 
348
371
  async sendNewSessionAlert(
372
+ _tenantId: string,
349
373
  email: string,
350
374
  sessionInfo: SessionInfo,
351
375
  _locale?: string
@@ -365,7 +389,12 @@ export class ResendEmailProvider implements IEmailProvider {
365
389
  })
366
390
  }
367
391
 
368
- async sendInvitation(email: string, inviteData: InviteData, _locale?: string): Promise<void> {
392
+ async sendInvitation(
393
+ _tenantId: string,
394
+ email: string,
395
+ inviteData: InviteData,
396
+ _locale?: string
397
+ ): Promise<void> {
369
398
  const url = `${this.appUrl}/accept-invite?token=${encodeURIComponent(inviteData.inviteToken)}`
370
399
  await this.client.emails.send({
371
400
  from: this.from,
@@ -644,25 +673,25 @@ both channels are accepted, and a ticket wins when both are present.
644
673
 
645
674
  All options are configurable via `registerAsync()`. Here are the key configuration groups:
646
675
 
647
- | Group | Key Options | Default |
648
- | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- |
649
- | **jwt** | `secret` (required), `previousSecrets`, `accessExpiresIn`, `refreshExpiresInDays`, `absoluteSessionLifetimeDays`, `algorithm`, `issuer`, `audience` | `15m`, `7d`, off, `HS256`, both off |
650
- | **environment** | `'production'` \| `'development'` \| `'test'` — the only input that answers "is this production" | `'production'` |
651
- | **password** | `minLength`, `costFactor`, `blockSize`, `parallelization` | `15`, scrypt N=2¹⁷, r=8, p=1 |
652
- | **tokenDelivery** | `'cookie'` \| `'bearer'` \| `'both'` | `'cookie'` |
653
- | **cookies** | `accessTokenName`, `refreshTokenName`, `sessionSignalName`, `refreshCookiePath`, `sameSite`, `trustedOrigins`, `resolveDomains` | `'lax'`, `[]` (see cookie section) |
654
- | **mfa** | `encryptionKey`, `previousEncryptionKeys`, `issuer`, `totpWindow`, `recoveryCodeCount` | — |
655
- | **sessions** | `enabled`, `defaultMaxSessions`, `maxSessionsResolver` | `false`, `5`, — |
656
- | **bruteForce** | `maxAttempts`, `windowSeconds` | `5`, `900` |
657
- | **rateLimit** | `enabled`, `clientIpSource` (`'peer'` \| `'trusted-proxy'`) — per-IP limits over Redis | `true`, **required** |
658
- | **passwordReset** | `method` (`'token'` \| `'otp'`), `otpLength`, `otpTtlSeconds` | `'token'` |
659
- | **platform** | `enabled` | `false` |
660
- | **invitations** | `enabled`, `tokenTtlSeconds` | `false` |
661
- | **roles** | `hierarchy` (required), `platformHierarchy` | — |
662
- | **oauth** | `google: { clientId, clientSecret, callbackUrl }` | — |
663
- | **emailVerification** | `required`, `otpTtlSeconds` | `true`, `600` |
664
- | **password** (screen) | `blocklist` — extra words the default screen refuses, on top of the ones it ships | `[]` |
665
- | **controllers** | Toggle individual controllers on/off | `auth`, `passwordReset` on; rest opt-in |
676
+ | Group | Key Options | Default |
677
+ | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- |
678
+ | **jwt** | `secret` (required), `previousSecrets`, `accessExpiresIn`, `refreshExpiresInDays`, `absoluteSessionLifetimeDays`, `algorithm`, `issuer`, `audience` | `15m`, `7d`, `30d` cap, `HS256`, both off |
679
+ | **environment** | `'production'` \| `'development'` \| `'test'` — the only input that answers "is this production" | `'production'` |
680
+ | **password** | `minLength`, `costFactor`, `blockSize`, `parallelization` | `15`, scrypt N=2¹⁷, r=8, p=1 |
681
+ | **tokenDelivery** | `'cookie'` \| `'bearer'` \| `'both'` | `'cookie'` |
682
+ | **cookies** | `accessTokenName`, `refreshTokenName`, `sessionSignalName`, `refreshCookiePath`, `sameSite`, `trustedOrigins`, `resolveDomains` | `'lax'`, `[]` (see cookie section) |
683
+ | **mfa** | `encryptionKey`, `previousEncryptionKeys`, `issuer`, `totpWindow`, `recoveryCodeCount` | — |
684
+ | **sessions** | `enabled`, `defaultMaxSessions`, `maxSessionsResolver` | `false`, `5`, — |
685
+ | **bruteForce** | `maxAttempts`, `windowSeconds` | `5`, `900` |
686
+ | **rateLimit** | `enabled`, `clientIpSource` (`'peer'` \| `'trusted-proxy'`) — per-IP limits over Redis | `true`, **required** |
687
+ | **passwordReset** | `method` (`'token'` \| `'otp'`), `otpLength`, `otpTtlSeconds` | `'token'` |
688
+ | **platform** | `enabled` | `false` |
689
+ | **invitations** | `enabled`, `tokenTtlSeconds` | `false` |
690
+ | **roles** | `hierarchy` (required), `platformHierarchy` | — |
691
+ | **oauth** | `google: { clientId, clientSecret, callbackUrl }` | — |
692
+ | **emailVerification** | `required`, `otpTtlSeconds` | `true`, `600` |
693
+ | **password** (screen) | `blocklist` — extra words the default screen refuses, on top of the ones it ships | `[]` |
694
+ | **controllers** | Toggle individual controllers on/off | `auth`, `passwordReset` on; rest opt-in |
666
695
 
667
696
  > [!NOTE]
668
697
  > When a feature is not configured (e.g., `mfa`, `sessions`, `platform`), its controllers and services are **not registered** in the NestJS container — zero overhead.
@@ -765,14 +794,22 @@ All options are configurable via `registerAsync()`. Here are the key configurati
765
794
  > rather than letting it fail open, and rejects an unreadable time span or a non-positive
766
795
  > lifetime on the same pass.
767
796
 
768
- Two options are deliberately off by default because switching them on changes behaviour for
769
- sessions and origins that already exist:
797
+ `jwt.absoluteSessionLifetimeDays` caps how long one login can be extended by rotation, and is
798
+ **on by default at 30 days** — NIST SP 800-63B-4 §3 makes a definite reauthentication timeout a
799
+ SHALL and puts it at no more than 30 days for AAL1. Without a cap, a client refreshing every
800
+ fifteen minutes keeps a session alive forever, and a refresh token stolen once becomes permanent
801
+ access. Raise it to a value the product can justify, or set `0` to accept unbounded sessions
802
+ deliberately.
803
+
804
+ Lowering the value ends sessions that are already older than the new one, at their next rotation;
805
+ raising it or setting `0` ends nothing. Sessions established before the cap existed carry no
806
+ recorded birth time and are never capped, whatever the value — they age out under
807
+ `refreshExpiresInDays` like any other.
770
808
 
771
- - `jwt.absoluteSessionLifetimeDays` caps how long one login can be extended by rotation. Without
772
- it, a client refreshing every fifteen minutes keeps a session alive forever.
773
- - `cookies.trustedOrigins` is required as soon as `cookies.sameSite: 'none'` is set, and refused
774
- otherwise — that posture is the only one where the browser sends the session cookie
775
- cross-site, and it is the only one where the origin check has anything to authorize.
809
+ `cookies.trustedOrigins` is deliberately off by default, because switching it on changes
810
+ behaviour for origins that already exist. It is required as soon as `cookies.sameSite: 'none'`
811
+ is set, and refused otherwise — that posture is the only one where the browser sends the session
812
+ cookie cross-site, and it is the only one where the origin check has anything to authorize.
776
813
 
777
814
  The breach check is opt-in for a different reason: it is the only part of the credential path
778
815
  that reaches the network, and a library should not start talking to a third party because it was
@@ -919,9 +956,9 @@ When integrating `@bymax-one/nest-auth` in production, verify each of the follow
919
956
  Authentication is critical infrastructure, so the suite is held to a bar beyond "it runs" — every behavior is pinned so that a regression **fails a test**.
920
957
 
921
958
  - ✅ **100% line coverage** — statements, branches, functions, and lines, enforced as a release gate across unit + e2e
922
- - ✅ **100% mutation score** — verified with [Stryker](https://stryker-mutator.io/): 3,474 seeded faults killed, **no survivors and nothing left uncovered**, against a `break` threshold of 95
923
- - ✅ **2,458 tests** — unit and end-to-end, spanning all five subpaths
924
- - ✅ **Every equivalent mutant documented** — the handful that no test can kill (a redundant guard, a dependency array of stable references) carries an inline `// Stryker disable` with the reason it cannot be killed, so the score is an accounting rather than a number
959
+ - ✅ **100% mutation score** — verified with [Stryker](https://stryker-mutator.io/): 4,870 seeded faults detected (4,849 killed, 21 timed out), **no survivors and nothing left uncovered**, against a `break` threshold of 95 ([measured cold on 2026-08-08](./docs/mutation_testing_results.md#re-measured-cold--2026-08-08))
960
+ - ✅ **3,547 tests** — 3,420 unit and 127 end-to-end, spanning all five subpaths
961
+ - ✅ **Every equivalent mutant documented** — the 350 mutants that no test can kill (a redundant guard, a dependency array of stable references) each carry an inline `// Stryker disable` with the reason, so the score is an accounting rather than a number
925
962
 
926
963
  ```bash
927
964
  pnpm test # unit suite