@bymax-one/nest-auth 1.3.0 → 1.3.2

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,132 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.3.2] - 2026-08-10
11
+
12
+ Binds the MFA challenge to its tenant and scopes every MFA key, counter and write by it — the
13
+ multi-tenant hardening rust-auth mirrors byte-for-byte. It stays in the 1.3.x line, where the
14
+ library still has no published dependents; the one breaking change is the
15
+ `IUserRepository.updateMfa` signature, which a derived backend adopts as it upgrades.
16
+
17
+ ### Security
18
+
19
+ - **The MFA challenge is bound to its tenant, and every MFA key is scoped by it.** The MFA temp
20
+ token carried no tenant, so the challenge resolved its subject by id across every tenant
21
+ (`findById(sub)` with no tenant) — and the status gate, the decrypted secret, the recovery
22
+ digests and the account the session was finally minted for all ran against whatever row the
23
+ repository returned. A library cannot assume a host's user ids are unique across tenants —
24
+ `findById` takes a tenant precisely because they may not be — so under a schema that numbers users
25
+ per tenant, every tenant has a user `1`. The token now carries `tenantId` (present on the
26
+ dashboard plane, absent on the platform plane), `verifyMfaTempToken` refuses a dashboard token
27
+ that lacks it and a platform token that carries it — a refusal, not a fallback (RFC 8725 §3.9 /
28
+ §3.12, ASVS 5.0 6.6.2) — and `assertPlaneTenant` enforces the same rule at the five public
29
+ `MfaService` entry points before any repository read.
30
+
31
+ - **Eight MFA store keys and failure counters were scoped by plane but not by tenant**, so two
32
+ tenants' user `1` shared all of them. The three `lf:` counters were the worst: a shared lockout
33
+ counter is a credential-free cross-tenant lockout — failures against one tenant's user spend
34
+ another's budget, and a success on either clears the other — which is not the per-subscriber
35
+ rate limiting NIST SP 800-63B requires. All eight now derive from one tenant-scoped `mfaSubject`,
36
+ driven by the plane rather than by whether a tenant was supplied. The wire contract gains
37
+ `mfaSubjectPreimages` and `mfaSubjectDerivedKeys`, pinning the shape rust-auth mirrors byte-for-byte.
38
+
39
+ - **The MFA write is scoped by tenant too, and a blank tenant is refused.** Every MFA transition
40
+ writes — the recovery-code splice and the key-rotation re-encrypt — and both wrote through
41
+ `updateMfa(id, data)`, keyed by id alone, so under colliding ids the write could land on another
42
+ tenant's row and leave a spent recovery code in the list. **`IUserRepository.updateMfa` now takes
43
+ the tenant: `updateMfa(id, tenantId, data)`** — a breaking change that forces every implementation
44
+ to scope the write as its read is scoped (the platform repository is unchanged). And
45
+ `assertPlaneTenant` now refuses a blank `tenantId`, not merely a missing one: `''` — what an unset
46
+ environment variable becomes — would build `dashboard::{userId}`, a third keyspace.
47
+
48
+ **Apply to a derived backend:** upgrade and deploy this release **in full** before the one that
49
+ follows it. For a rolling upgrade this release dual-writes the anti-replay marker and the three
50
+ failure counters (every read consults both the old plane-only key and the new tenant-scoped key,
51
+ every write touches both) and dual-acquires the transition lock, so old and new pods stay
52
+ consistent while both are live. A later release drops the legacy arm; deploying it before this one
53
+ has fully rolled out would split the anti-replay and lockout state across the two key shapes. No
54
+ host code changes: the tenant is sourced from the authenticated account, never from the request.
55
+
56
+ ## [1.3.1] - 2026-08-08
57
+
58
+ Adds the revocation checker and the overridable default auth-email provider, carries the tenant
59
+ on the email port, and refreshes the mutation figures the packaged README and CHANGELOG report.
60
+ All of it stays in the 1.3.x line: there are no published dependents, so nothing installed breaks.
61
+
62
+ ### Added
63
+
64
+ - **`DefaultAuthEmailProvider` is exported**, the overridable default that fills the email port so a
65
+ derived backend no longer hand-writes the same bridge onto its notification channel. It carries
66
+ the policy that should not be copied per backend: HTML escaping on a path that renders
67
+ caller-chosen text (an inviter's name, a tenant's name, the address an account moved to), the
68
+ NIST SP 800-63B notification catalogue (a password-changed notice, MFA enable/disable notices, an
69
+ email-changed notice to the _previous_ address), and a swallow-and-log failure policy so a down
70
+ channel never turns "enable MFA" into a failed request. It sends through `AuthEmailSink`, a port
71
+ narrow enough that the class imports no concrete mailer — `@bymax-one/nest-notification`'s
72
+ `EmailService` satisfies it structurally — and it consumes the tenant the email port now carries,
73
+ so a multi-tenant channel can attribute and route each message. Pass `messages` to override any
74
+ subset of the copy with a product's own wording or branding; the escaping and failure policy
75
+ still apply. It closes bymaxone/nest-notification#54.
76
+
77
+ - **`AuthRevocationService` is exported**, answering whether a verified access token has been
78
+ revoked across both channels the module writes to — the per-token blacklist a logout writes and
79
+ the per-user epoch a password reset or revoke-all advances. It closes bymaxone/nest-auth#92: a
80
+ backend bridging this library to a realtime transport can inject it and consult the same two
81
+ channels the HTTP guards do, instead of verifying a token's signature and granting a stream that
82
+ outlives every revocation window. The `JwtAuthGuard`, `WsJwtGuard` and `JwtPlatformGuard` now
83
+ delegate to it rather than each carrying its own copy of the two Redis reads — one source of
84
+ truth for the check, so a fix reaches all three and every consumer at once. No behaviour changed:
85
+ the guards' full suites pass unmodified.
86
+
87
+ ### Changed
88
+
89
+ - **`IEmailProvider` carries the tenant on every method.** Each of the ten methods now
90
+ takes `tenantId: string` as its first parameter, ahead of the recipient address. A notification
91
+ backend serving more than one tenant could not, before this, tell which tenant a password-reset
92
+ or invitation email belonged to: it saw only an address, so it could not pick the right sender
93
+ identity, branding, locale default or audit stream. The tenant was known at every call site — a
94
+ dashboard user carries its own `tenantId`, and a cross-tenant platform admin is attributed to the
95
+ `'platform'` plane, mirroring the `pep:` epoch namespace — it simply was not being passed. It
96
+ closes bymaxone/nest-auth#93.
97
+
98
+ **Apply to a derived backend.** Any `IEmailProvider` implementation must add `tenantId: string`
99
+ as the first argument of every method it defines and route on it as its backend requires; a
100
+ provider that ignores tenancy can name the parameter `_tenantId` and change nothing else. The
101
+ bundled `NoOpEmailProvider` already conforms.
102
+
103
+ Migrate **every** method, not only the one the compiler flags. Because the added argument is a
104
+ `string` prepended to methods whose other arguments are also strings, a stale
105
+ `sendPasswordResetToken(email, token)` stays assignable to the new type — TypeScript accepts an
106
+ implementation with fewer parameters — so it compiles while binding `tenantId` to the recipient
107
+ at runtime. Only `sendInvitation`, whose second argument is an object, fails compilation. Fixing
108
+ that one is not proof the rest are done; the surest path is to extend the `DefaultAuthEmailProvider`
109
+ this release adds rather than hand-write the port.
110
+
111
+ The library has no published dependents yet, so this breaks nothing already released and ships in
112
+ the ordinary `1.3.x` line rather than as a major — SemVer's promise is to existing consumers, and
113
+ there are none to break.
114
+
115
+ - **The mutation score is re-measured rather than restated.** The last recorded run was
116
+ 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
117
+ quoted its figures: 3,474 faults killed against 2,458 tests. A cold run on 2026-08-08 —
118
+ incremental baseline deleted, nothing inherited, and now covering this release's own additions —
119
+ puts the library at **100.00% with 4,870 mutants detected (4,849 killed, 21 timed out), no
120
+ survivors and none without coverage**, out of 7,718 instrumented across 147 files. The suite
121
+ behind it is **3,547 tests** (3,420 unit, 127 end-to-end). All five subpaths are individually at
122
+ 100.00%.
123
+
124
+ The count of documented equivalents is now reported as the number it is — **350 mutants under
125
+ 217 `// Stryker disable` directives** — instead of "the handful that no test can kill". Nothing
126
+ about them changed; the README's description of them had simply stopped matching their size, and
127
+ a number that is written down can be audited.
128
+
129
+ - **`docs/mutation_testing_results.md` records the run** in a new dated section, with the full
130
+ outcome table, the per-subpath split, and where the twenty-one timeouts sit. The earlier
131
+ sections are left as they were — they are the record of the passes that produced them. The
132
+ reproduce instructions are corrected in the same pass: they named `pnpm mutation:incremental`,
133
+ which is not a script in this package, and promised a ten-minute run that now takes
134
+ forty-eight at `--concurrency 2`.
135
+
10
136
  ## [1.3.0] - 2026-08-08
11
137
 
12
138
  Minor rather than patch because the API now accepts a request it previously rejected: with a
@@ -1193,7 +1319,9 @@ ever installable.
1193
1319
  - 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
1194
1320
  - 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
1195
1321
 
1196
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.3.0...HEAD
1322
+ [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.3.2...HEAD
1323
+ [1.3.2]: https://github.com/bymaxone/nest-auth/compare/v1.3.1...v1.3.2
1324
+ [1.3.1]: https://github.com/bymaxone/nest-auth/compare/v1.3.0...v1.3.1
1197
1325
  [1.3.0]: https://github.com/bymaxone/nest-auth/compare/v1.2.0...v1.3.0
1198
1326
  [1.2.0]: https://github.com/bymaxone/nest-auth/compare/v1.1.1...v1.2.0
1199
1327
  [1.1.1]: https://github.com/bymaxone/nest-auth/compare/v1.1.0...v1.1.1
package/README.md CHANGED
@@ -209,9 +209,11 @@ export class PrismaUserRepository implements IUserRepository {
209
209
  await this.prisma.user.update({ where: { id }, data: { passwordHash } })
210
210
  }
211
211
 
212
- async updateMfa(id: string, data: UpdateMfaData): Promise<void> {
213
- await this.prisma.user.update({
214
- where: { id },
212
+ async updateMfa(id: string, tenantId: string | undefined, data: UpdateMfaData): Promise<void> {
213
+ // Scoped by tenant, like findById: `updateMany` with both id and tenantId so an id shared
214
+ // across tenants cannot cross the write onto the wrong account.
215
+ await this.prisma.user.updateMany({
216
+ where: { id, tenantId },
215
217
  data: {
216
218
  mfaEnabled: data.mfaEnabled,
217
219
  mfaSecret: data.mfaSecret,
@@ -299,7 +301,12 @@ export class ResendEmailProvider implements IEmailProvider {
299
301
  private readonly from = 'no-reply@example.com'
300
302
  private readonly appUrl = process.env.APP_URL!
301
303
 
302
- async sendPasswordResetToken(email: string, token: string, _locale?: string): Promise<void> {
304
+ async sendPasswordResetToken(
305
+ _tenantId: string,
306
+ email: string,
307
+ token: string,
308
+ _locale?: string
309
+ ): Promise<void> {
303
310
  const url = `${this.appUrl}/reset-password?token=${encodeURIComponent(token)}`
304
311
  await this.client.emails.send({
305
312
  from: this.from,
@@ -309,7 +316,12 @@ export class ResendEmailProvider implements IEmailProvider {
309
316
  })
310
317
  }
311
318
 
312
- async sendPasswordResetOtp(email: string, otp: string, _locale?: string): Promise<void> {
319
+ async sendPasswordResetOtp(
320
+ _tenantId: string,
321
+ email: string,
322
+ otp: string,
323
+ _locale?: string
324
+ ): Promise<void> {
313
325
  await this.client.emails.send({
314
326
  from: this.from,
315
327
  to: email,
@@ -318,7 +330,12 @@ export class ResendEmailProvider implements IEmailProvider {
318
330
  })
319
331
  }
320
332
 
321
- async sendEmailVerificationOtp(email: string, otp: string, _locale?: string): Promise<void> {
333
+ async sendEmailVerificationOtp(
334
+ _tenantId: string,
335
+ email: string,
336
+ otp: string,
337
+ _locale?: string
338
+ ): Promise<void> {
322
339
  await this.client.emails.send({
323
340
  from: this.from,
324
341
  to: email,
@@ -327,7 +344,11 @@ export class ResendEmailProvider implements IEmailProvider {
327
344
  })
328
345
  }
329
346
 
330
- async sendMfaEnabledNotification(email: string, _locale?: string): Promise<void> {
347
+ async sendMfaEnabledNotification(
348
+ _tenantId: string,
349
+ email: string,
350
+ _locale?: string
351
+ ): Promise<void> {
331
352
  await this.client.emails.send({
332
353
  from: this.from,
333
354
  to: email,
@@ -336,7 +357,11 @@ export class ResendEmailProvider implements IEmailProvider {
336
357
  })
337
358
  }
338
359
 
339
- async sendMfaDisabledNotification(email: string, _locale?: string): Promise<void> {
360
+ async sendMfaDisabledNotification(
361
+ _tenantId: string,
362
+ email: string,
363
+ _locale?: string
364
+ ): Promise<void> {
340
365
  await this.client.emails.send({
341
366
  from: this.from,
342
367
  to: email,
@@ -346,6 +371,7 @@ export class ResendEmailProvider implements IEmailProvider {
346
371
  }
347
372
 
348
373
  async sendNewSessionAlert(
374
+ _tenantId: string,
349
375
  email: string,
350
376
  sessionInfo: SessionInfo,
351
377
  _locale?: string
@@ -365,7 +391,12 @@ export class ResendEmailProvider implements IEmailProvider {
365
391
  })
366
392
  }
367
393
 
368
- async sendInvitation(email: string, inviteData: InviteData, _locale?: string): Promise<void> {
394
+ async sendInvitation(
395
+ _tenantId: string,
396
+ email: string,
397
+ inviteData: InviteData,
398
+ _locale?: string
399
+ ): Promise<void> {
369
400
  const url = `${this.appUrl}/accept-invite?token=${encodeURIComponent(inviteData.inviteToken)}`
370
401
  await this.client.emails.send({
371
402
  from: this.from,
@@ -927,9 +958,9 @@ When integrating `@bymax-one/nest-auth` in production, verify each of the follow
927
958
  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**.
928
959
 
929
960
  - ✅ **100% line coverage** — statements, branches, functions, and lines, enforced as a release gate across unit + e2e
930
- - ✅ **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
931
- - ✅ **2,458 tests** — unit and end-to-end, spanning all five subpaths
932
- - ✅ **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
961
+ - ✅ **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))
962
+ - ✅ **3,547 tests** — 3,420 unit and 127 end-to-end, spanning all five subpaths
963
+ - ✅ **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
933
964
 
934
965
  ```bash
935
966
  pnpm test # unit suite