@bymax-one/nest-notification 1.3.1 → 1.4.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
@@ -5,6 +5,173 @@ All notable changes to `@bymax-one/nest-notification` will be documented in this
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [Unreleased]
9
+
10
+ ## [1.4.1] - 2026-10-30
11
+
12
+ ### Security
13
+
14
+ - **Peer ranges raised past published advisories.** `nodemailer` `^9.0.1` → `^10.1.4` (13
15
+ advisories, the highest severity "high", fixed from 10.1.4) and `handlebars` `^4.7.9` →
16
+ `^4.7.10` (3 advisories, the highest "critical", fixed in 4.7.10). A declared peer range states
17
+ which versions this package supports, so the floor no longer admits a version with a known
18
+ advisory. See the note below for what a `nodemailer` 9 consumer has to do.
19
+ - **`OtpService` refuses a blank scope before it reaches the storage.** `generate`, `resend`,
20
+ `verify`, `consume` and `getStatus` now throw `NotificationException` with code
21
+ `INVALID_SCOPE_IDENTIFIER` when `tenantId` or `recipient` is empty, whitespace-only or not a
22
+ string. `details` carries `{ boundary: 'OtpService', parameter, reason }` and never the value.
23
+ When the OTP channel is not configured, `generate`, `resend`, `verify` and `consume` still throw
24
+ `OTP_STORAGE_NOT_CONFIGURED` first; `getStatus` has no such check and validates the scope first.
25
+ - **Reference storages** (`InMemoryOtpStorage`, `RedisOtpStorage`): no change, they already
26
+ threw through `hashTenantRecipient`.
27
+ - **A custom `IOtpStorage` that accepted a blank tenant or recipient:** those calls now throw
28
+ instead of reaching the adapter. Before, such an adapter could share one scope between every
29
+ caller that sent a blank value.
30
+ - **`otpStorageContract` checks the tenant/recipient boundary with a second delimiter.** The
31
+ entry-key and cooldown-key cases now also use a pair that collides when the key is built by
32
+ joining the raw values around `::`. A storage that did so passed the contract before and now
33
+ fails it.
34
+
35
+ ### ⚠️ Apply before upgrading
36
+
37
+ - **A consumer on `nodemailer` 9.** The optional peer range of `nodemailer` moves from `^9.0.1` to `^10.1.4`, so a consumer on
38
+ `nodemailer` 9 has to upgrade to 10.1.4 or later. The only breaking change between the two
39
+ majors is that `nodemailer` 10 requires Node.js 20 or newer ([its changelog](https://github.com/nodemailer/nodemailer/blob/master/CHANGELOG.md),
40
+ 10.0.0); this package already requires Node.js 24. `SmtpEmailProvider` works with both the ESM and
41
+ CommonJS builds of `nodemailer` 10. No 9.x release fixes these advisories: 9.1.1 is the last 9.x and
42
+ still falls inside the vulnerable range of nine of them.
43
+ - **A consumer that brings `handlebars`.** The optional peer range moves from `^4.7.9` to
44
+ `^4.7.10`, so a consumer that uses `handlebars` for a template renderer has to be on 4.7.10 or
45
+ later. This package never imports `handlebars` itself; the range states which versions are
46
+ supported when you provide it.
47
+ - **A consumer with a custom `IOtpStorage`.** `OtpService` now refuses a blank, whitespace-only or
48
+ non-string `tenantId` or `recipient` with `INVALID_SCOPE_IDENTIFIER` before it calls your
49
+ storage. If your callers can pass such a value, validate it before the call, because those calls
50
+ used to reach the adapter. The reference storages already refused them.
51
+
52
+ ### Changed
53
+
54
+ - **The published `dist/` changes in this release; it is not a documentation-only release.**
55
+ `OtpService` gains the scope validation above, `otpStorageContract` gains the second boundary
56
+ pair, and the declaration files carry new doc comments on `NotificationAuditInterceptor` and on
57
+ `GlobalOptions.tenantIdResolver`, plus the export-statement form described next.
58
+ - **Bundler `tsup` 9.** The published JavaScript (`.mjs` and `.cjs`, every subpath) is byte-identical
59
+ to what `tsup` 8 produced from the same source. The declaration files (`.d.ts`, `.d.cts`) differ
60
+ only in how the export list is written: values in one `export { }`, types in a separate
61
+ `export type { }`. Nothing about the exported names or their types changes.
62
+ - Development and CI tooling only, with no effect on the published package: pnpm override floors
63
+ raised; the dev dependency group refreshed; `osv-scanner.toml` time-boxes the advisory
64
+ (`deepmerge`) that has no patched release.
65
+
66
+ ### Documentation
67
+
68
+ - **What the audit interceptor does with a tenant id that identifies nobody (behaviour since 1.4.0).**
69
+ `NotificationAuditInterceptor` refuses a tenant id that is not a string, is empty, or is
70
+ whitespace-only, on every path that produces it: the value `tenantIdResolver` returns, the
71
+ payload's `tenantId` when no resolver is configured, and the payload's `tenantId` when a resolver
72
+ is configured but there is no HTTP request. The 1.4.0 entry only named an empty value from the
73
+ resolver. The refusal does not reach the caller: with `audit.swallowErrors: true` (the default) it
74
+ is swallowed and no audit entry is written; with `false` it surfaces as `AUDIT_LOG_FAILED` with a
75
+ sanitized copy of the refusal as its `cause`. A payload whose `tenantId` is not a string is
76
+ ignored instead: the argument is not recognised as a dispatch, so there is no entry and no error.
77
+ - **README corrections a consumer reads.**
78
+ - `NoOpEmailProvider` logs a masked recipient only, never the subject or the body. The README
79
+ said it logged the subject and the recipient.
80
+ - The module is described as running on Resend or SMTP out of the box, or on any provider you
81
+ implement. The README named SendGrid as if it were bundled.
82
+ - The package has four subpaths, including `./testing`. One README line said three.
83
+ - The multi-tenant example is a header-based resolver, not a JWT claim, and the README now says
84
+ what the audit interceptor does with a tenant id that identifies nobody.
85
+ - The bundle-budget table lists the `testing` budget. The fixed test count and the stale
86
+ error-code count in the exports table (it said 22) are gone.
87
+ - Vulnerability reporting points to GitHub Private Vulnerability Reporting, with email as the
88
+ fallback.
89
+ - Documents that are not part of the package (SECURITY, CONTRIBUTING, CLAUDE.md, AGENTS.md, the
90
+ specification and guides under `docs/`) were brought in line with the code as well.
91
+
92
+ ## [1.4.0] - 2026-09-04
93
+
94
+ > ### ⚠️ Read before deploying — the version number does not warn you
95
+ >
96
+ > **Every OTP storage key changes in this release, and nothing in the type system will tell
97
+ > you.** It compiles, the suite passes, and on deploy every OTP and resend cooldown still in
98
+ > flight becomes unreachable. An operator reading `fix(otp)` and a minor version bump will not
99
+ > infer that every code in flight stops working — this paragraph is the only warning there is.
100
+ >
101
+ > **Scope, so this reads as accurate rather than alarming.** The defect it fixes is a
102
+ > cross-tenant key collision that is real in the library and **unreachable in today's only
103
+ > consumer**: `bymax-one` resolves tenants through a host-label guard that rejects both an empty
104
+ > label and a colon, so it provably never emits an identity that could collide. A backend
105
+ > resolving tenants from a database column, a JWT claim or an admin-entered field inherits none
106
+ > of that protection.
107
+ >
108
+ > What to do about it is in [Apply to a derived backend](#-apply-to-a-derived-backend) below.
109
+
110
+ ### Security
111
+
112
+ - **Storage keys no longer collapse two different `(tenantId, recipient)` pairs onto one key.**
113
+ The key was `sha256(`${tenantId}:${recipient}`)` — the two fields joined around a delimiter,
114
+ which does not encode where the boundary falls. `('acme:bob', 'x')` and `('acme', 'bob:x')`
115
+ produced the same input string and therefore the same key, so under a consumer whose tenant
116
+ ids or recipient ids can contain a colon, one tenant's `verify` could consume another tenant's
117
+ OTP. Each component is now hashed to a fixed length before the two are joined:
118
+ `sha256(sha256(tenantId):sha256(recipient))`.
119
+
120
+ This was never a weakness in SHA-256, and the documentation said otherwise — `README.md` and
121
+ `CLAUDE.md` claimed cross-tenant collision was "computationally infeasible (SHA-256 preimage
122
+ resistance)". Preimage resistance is irrelevant to it: the two pairs were the same input, and
123
+ every digest property held perfectly while they collided. Those claims are corrected.
124
+
125
+ `InMemoryOtpStorage` composed its map key the same way, with `::`, and had the same defect.
126
+
127
+ - **New error code `notification.invalid_scope_identifier`** (23 codes, up from 22). The refusal
128
+ below is a `NotificationException` rather than a bare `Error`: it reaches a consumer through
129
+ every `IOtpStorage` method, and this library's contract is that a consumer branches on `code`.
130
+ A raw throw surfaced as an untyped 500 carrying an internal message, where the condition is a
131
+ 400 the caller can act on. `details` names the boundary, the parameter and the reason — never
132
+ the value, which is serialized into the response and is exactly what must not be echoed back.
133
+
134
+ - **A component that identifies nothing is refused rather than hashed** — empty, whitespace-only,
135
+ or not a string at all. An empty component put every caller that omitted it into one shared
136
+ namespace, the same isolation failure reached from the other side. Whitespace produced a
137
+ distinct key and therefore no collision, but named no tenant. The `typeof` check is there
138
+ because the declared `string` is a contract this library states and a consumer may not honour:
139
+ a `null` claim or a numeric database id type-checks at their call site and previously failed
140
+ inside `createHash` with a message naming crypto's `data` argument instead of this rule.
141
+
142
+ - **`NotificationAuditInterceptor` refuses an empty tenant id from `tenantIdResolver`.** An empty
143
+ scope does not identify a tenant, and recording it filed the event under a scope shared with
144
+ every other empty result. The refusal is subject to `audit.swallowErrors` like any other audit
145
+ failure: the entry is skipped rather than written wrong.
146
+
147
+ ### ⚠️ Apply to a derived backend
148
+
149
+ **Every OTP storage key changes with this release, and nothing in the type system will tell you.**
150
+ It compiles, the suite passes, and on deploy every OTP and resend cooldown still in flight becomes
151
+ unreachable — the old keys are never read again. Consequences to plan for:
152
+
153
+ - Users mid-verification get `OTP_NOT_FOUND` and must request a new code.
154
+ - Resend cooldowns reset, so a user who was throttled can request again immediately.
155
+ - Stale entries expire on their own TTL; nothing needs to be purged, but nothing is migrated
156
+ either. There is no dual-read path, deliberately: reading the old construction back would mean
157
+ keeping the colliding key alive.
158
+
159
+ Deploy when a short window of "request your code again" is acceptable, or drain OTP traffic first.
160
+
161
+ **If you implement `IOtpStorage` yourself,** re-run the contract from `@bymax-one/nest-notification/testing`.
162
+ It has two new cases — `keeps the tenant and recipient boundary when composing a key` and the same
163
+ for a cooldown key — which fail any implementation that concatenates the two fields around a
164
+ delimiter. **Both are needed:** the entry key and the cooldown key are composed separately, so a
165
+ storage that fixes one and not the other passes every case that exercises only the first. 21 cases,
166
+ up from 19. A survey
167
+ of the sibling libraries found 108 composite key constructions and 2 that encode their components,
168
+ so this defect is the default rather than the exception.
169
+
170
+ ### Fixed
171
+
172
+ - `loadOptionalPeer` attaches the caught error as `cause` on the "package is not installed" path
173
+ as well, so a resolution failure names the specifier the runtime actually rejected.
174
+
8
175
  ## [1.3.1] - 2026-08-18
9
176
 
10
177
  ### Documentation
@@ -605,7 +772,9 @@ rejected at startup rather than failing on the first send.
605
772
 
606
773
  [1.0.4]: https://github.com/bymaxone/nest-notification/compare/v1.0.3...v1.0.4
607
774
  [1.0.3]: https://github.com/bymaxone/nest-notification/compare/v1.0.2...v1.0.3
608
- [Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.3.1...HEAD
775
+ [Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.4.1...HEAD
776
+ [1.4.1]: https://github.com/bymaxone/nest-notification/compare/v1.4.0...v1.4.1
777
+ [1.4.0]: https://github.com/bymaxone/nest-notification/compare/v1.3.1...v1.4.0
609
778
  [1.3.1]: https://github.com/bymaxone/nest-notification/compare/v1.3.0...v1.3.1
610
779
  [1.3.0]: https://github.com/bymaxone/nest-notification/compare/v1.2.2...v1.3.0
611
780
  [1.2.2]: https://github.com/bymaxone/nest-notification/compare/v1.2.1...v1.2.2
package/README.md CHANGED
@@ -35,12 +35,12 @@
35
35
 
36
36
  `@bymax-one/nest-notification` is a **transactional notification library for NestJS 11** that ships two channels — **email** and **OTP** (one-time passwords) — behind a single dynamic module, plus a React subpath for the OTP input box.
37
37
 
38
- Everything that touches the outside world — the email transport, the OTP store, the template renderer, the audit sink — is an **interface** you implement or pick from the bundled reference adapters. The same module runs on Resend or SendGrid, on Redis or an in-memory map, with a Prisma audit log or none at all, without changing a single call site.
38
+ Everything that touches the outside world — the email transport, the OTP store, the template renderer, the audit sink — is an **interface** you implement or pick from the bundled reference adapters. The same module runs on Resend or SMTP out of the box (or any provider you implement, SendGrid for example), on Redis or an in-memory map, with a Prisma audit log or none at all, without changing a single call site.
39
39
 
40
40
  ### Why nest-notification?
41
41
 
42
42
  - **🔌 Your database, your provider** — The library defines the contracts (`IEmailProvider`, `IOtpStorage`, `IEmailTemplateRenderer`, `INotificationLogRepository`). You supply the implementations. It **never imports `@prisma/client`** or any other ORM — a CI gate fails the build if one appears — so a cross-cutting concern never hard-wires your schema.
43
- - **🏢 Multi-tenant from the first line** — Every operation is scoped by `tenantId`, store keys are `sha256(tenantId:recipient)`, and the audit interceptor resolves the trusted tenant from the request rather than the request body.
43
+ - **🏢 Multi-tenant from the first line** — Every operation is scoped by `tenantId`, store keys are `sha256(sha256(tenantId):sha256(recipient))`, and the audit interceptor resolves the trusted tenant from the request rather than the request body when you configure a resolver.
44
44
  - **🔒 Native crypto only** — Codes come from `crypto.randomInt` and are compared with `crypto.timingSafeEqual`. No `crypto-js`, no `otpauth`, no `uuid`, no `nanoid` — the most security-sensitive path carries no third-party supply-chain risk.
45
45
  - **⚛️ Atomic by construction** — The attempt counter and the resend cooldown are mutated **inside the storage** (Redis Lua / `SET NX EX`), never by a service-side read-then-write. A `get` + `update` pair races, and the race is exactly how a max-attempts ceiling gets bypassed under concurrent requests.
46
46
  - **🪶 Pay for what you use** — `"dependencies": {}`. NestJS, your email SDK, your Redis client, and React are all peer dependencies, and only the channels you configure are registered in the container.
@@ -55,7 +55,7 @@ pnpm add @bymax-one/nest-notification
55
55
 
56
56
  ### 📧 Email
57
57
 
58
- - ✅ **Pluggable transport** — `IEmailProvider` with a bundled `ResendEmailProvider`, an `SmtpEmailProvider` that speaks the protocol every relay and mail-capture server understands, and a `NoOpEmailProvider` for dev/test that logs subject and recipient only, never the body
58
+ - ✅ **Pluggable transport** — `IEmailProvider` with a bundled `ResendEmailProvider`, an `SmtpEmailProvider` that speaks the protocol every relay and mail-capture server understands, and a `NoOpEmailProvider` for dev/test that logs a masked recipient only, never the body
59
59
  - ✅ **Template rendering** — `IEmailTemplateRenderer` with a bundled `{{var}}` renderer that **HTML-escapes** interpolated values in the HTML body
60
60
  - ✅ **Canonical template names** — `CANONICAL_EMAIL_TEMPLATES` so providers and templates agree on the wire
61
61
  - ✅ **Attachment guard** — a configurable total size ceiling (10 MiB by default) rejected before the provider is called
@@ -71,15 +71,15 @@ pnpm add @bymax-one/nest-notification
71
71
 
72
72
  ### 🏢 Multi-Tenant & Audit
73
73
 
74
- - ✅ **SHA-256 storage keys** — `sha256(tenantId:recipient)`: no recipient PII in a key, no cross-tenant collision
74
+ - ✅ **SHA-256 storage keys** — `sha256(sha256(tenantId):sha256(recipient))`: no recipient PII in a key, and the encoding adds no ambiguity of its own, so two pairs never share one by construction
75
75
  - ✅ **`tenantIdResolver`** — the audited tenant comes from a trusted source (a JWT claim, a subdomain, a gateway-checked header), not the payload
76
76
  - ✅ **Opt-in audit log** — a fire-and-forget `INotificationLogRepository` plus a `NotificationAuditInterceptor`; audit failures never break delivery
77
77
  - ✅ **This library never logs a code** — not to a logger, not to an audit entry, not into an error message it authors, enforced by a regression test. Text a **provider** authors is a separate problem with a documented ceiling: an error quoting the body in another encoding survives every guard, so control whether provider error text reaches your logs at all
78
78
 
79
79
  ### 🧩 Developer Experience
80
80
 
81
- - ✅ **Three subpaths** — server, zero-dependency shared types, and React hooks
82
- - ✅ **Stable error catalog** — 22 namespaced codes shared byte-for-byte between server and frontend, so you localize on the `code`
81
+ - ✅ **Subpaths** — server, zero-dependency shared types, React hooks, and a `testing` storage contract
82
+ - ✅ **Stable error catalog** — 23 namespaced codes shared byte-for-byte between server and frontend, so you localize on the `code`
83
83
  - ✅ **Dual-format output** — ESM + CJS + declarations for both, verified against the packed tarball on every PR
84
84
  - ✅ **Typed end to end** — TypeScript `strict` with `exactOptionalPropertyTypes` and `noUncheckedIndexedAccess`; zero `any`
85
85
 
@@ -146,7 +146,7 @@ pnpm add react
146
146
 
147
147
  ### 2. Development — `NoOpEmailProvider` + `InMemoryOtpStorage`
148
148
 
149
- No external services. Emails are logged (subject and recipient only, never the body), and OTP state lives in process memory. Ideal for local dev and tests.
149
+ No external services. Emails are logged (a masked recipient only, never the subject or the body), and OTP state lives in process memory. Ideal for local dev and tests.
150
150
 
151
151
  ```typescript
152
152
  import { Module } from '@nestjs/common'
@@ -582,14 +582,14 @@ OTP codes are bearer secrets with a short life and a wide blast radius: whoever
582
582
 
583
583
  ### SHA-256 storage keys
584
584
 
585
- OTP entries and resend cooldowns are stored under a key derived from `sha256(tenantId:recipient)` — never the plaintext recipient or tenant id:
585
+ OTP entries and resend cooldowns are stored under a key derived from `sha256(sha256(tenantId):sha256(recipient))` — never the plaintext recipient or tenant id:
586
586
 
587
587
  ```
588
588
  notification:otp:email_verification:7f3d8c91… (64 hex chars)
589
589
  ```
590
590
 
591
591
  - **Privacy.** An operator with `KEYS notification:otp:*` access to Redis — or anyone holding a leaked backup — cannot enumerate which addresses have a pending OTP. The recipient never appears in a key.
592
- - **Isolation.** Two tenants sharing the same recipient produce different keys, so a cross-tenant collision is computationally infeasible (SHA-256 preimage resistance). One tenant's OTP, cooldown, and verification can never touch another's.
592
+ - **Isolation.** Each component is hashed to a fixed length before the two are joined, so distinct `(tenantId, recipient)` pairs cannot produce the same key. This is a property of the encoding rather than of the digest — joining the raw values around a delimiter would map `('acme:bob', 'x')` and `('acme', 'bob:x')` onto one key while SHA-256's preimage and collision resistance held perfectly. Both components must be non-empty; an empty one is refused rather than hashed, because it would place every caller that omits it into a single shared scope.
593
593
 
594
594
  The trade-off — opaque keys you cannot read back to a recipient — is intentional: keys are an index, not a data source. The recipient lives only inside the TTL-bound value and, optionally masked, in the audit log.
595
595
 
@@ -608,13 +608,15 @@ BymaxNotificationModule.forRoot({
608
608
  // …channels
609
609
  })
610
610
 
611
- // JWT-claim based (the request is augmented by your auth middleware):
611
+ // Header based (set by a gateway you trust):
612
612
  const tenantIdResolver = (req: NotificationRequest): string =>
613
613
  String(req.headers['x-tenant-id'] ?? 'default')
614
614
  ```
615
615
 
616
616
  `NotificationRequest` is a minimal, framework-agnostic request shape declared by the library itself, so a public signature never drags in a framework's types. When a resolver is set, the `NotificationAuditInterceptor` uses it as the **source of truth** for the audited tenant id — any `tenantId` in the payload becomes a suggestion the resolver overrides.
617
617
 
618
+ A tenant id that identifies nobody is never recorded. The interceptor refuses a value that is not a string, is empty, or is whitespace-only, on every path that produces the id: what `tenantIdResolver` returns, the payload's `tenantId` when no resolver is configured, and the payload's `tenantId` when a resolver is configured but there is no HTTP request to read it from (a non-HTTP context). Your caller never sees the refusal itself. With `audit.swallowErrors: true` (the default) it is swallowed and no audit entry is written; with `false` it surfaces as `AUDIT_LOG_FAILED`, whose `cause` is a sanitized copy of the refusal. One input is ignored, not refused: an argument whose payload `tenantId` is not a string is not recognised as a dispatch at all, so it produces no audit entry and no error.
619
+
618
620
  > [!NOTE]
619
621
  > The resolver governs what the audit interceptor trusts. Service methods still take an explicit `tenantId`: resolve the tenant in your controller and pass it down — there is no hidden override of a method argument.
620
622
 
@@ -656,7 +658,7 @@ When integrating `@bymax-one/nest-notification` in production, verify each of th
656
658
  | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
657
659
  | Code Generation | `crypto.randomInt` per character over the configured alphabet — uniform at every position, no modulo bias |
658
660
  | Code Comparison | `crypto.timingSafeEqual` (constant-time), never `===` |
659
- | Storage Keys | `sha256(tenantId:recipient)` — no recipient PII, no cross-tenant collision |
661
+ | Storage Keys | `sha256(sha256(tenantId):sha256(recipient))` — no recipient PII; the encoding adds no ambiguity, so no two pairs share a key by construction |
660
662
  | Attempt Ceiling | Counter spent atomically inside the storage (Redis Lua) — never a service-side read-then-write |
661
663
  | Resend Cooldown | `SET NX EX` acquire, released only on delivery failure — two concurrent resends cannot both win |
662
664
  | Code Lifetime | TTL-bound in the store; expiry and absence are reported identically so neither leaks the other |
@@ -694,21 +696,21 @@ A one-time password is a credential, so the suite is held to a bar beyond "it ru
694
696
 
695
697
  - ✅ **100% line coverage** — statements, branches, functions, and lines, enforced per file as a release gate across unit + e2e
696
698
  - ✅ **100% mutation score** — verified with [Stryker](https://stryker-mutator.io/): every viable seeded fault killed, with **no survivors**, against a `break` threshold of 100. The equivalents that no test can kill carry their reason on the line they apply to, so the number is an accounting rather than a target
697
- - ✅ **680 tests** — unit and end-to-end, spanning all four subpaths
699
+ - ✅ **100% coverage** — unit and end-to-end tests spanning every subpath
698
700
  - ✅ **Invariants asserted, not assumed** — the never-log-codes rule is a test (`JSON.stringify(entry).includes(code) === false` on every audit entry, and the thrown exception is serialized recursively — message, stack, response body, every nested `cause` — asserting the code appears at no depth), not a review convention
699
701
  - ✅ **Published shape verified** — `attw` resolves every entrypoint against the packed tarball, and a dogfood smoke test installs the package into a scratch consumer before any tag is cut
700
702
  - ✅ **Every equivalent mutant documented** — the ones no test can kill carry an inline `// Stryker disable` with the reason, so the score is an accounting rather than a number
701
703
 
702
- | Gate | Standard |
703
- | -------------- | ---------------------------------------------------------------------- |
704
- | Type safety | TypeScript `strict`, zero `any` |
705
- | Coverage | **100%** line/branch/function/statement per file (`pnpm test:cov:all`) |
706
- | Mutation | Stryker score **100%** (`break: 100`), no survivors |
707
- | Lint | ESLint flat config + `eslint-plugin-security`, zero warnings |
708
- | Bundle budgets | server < 30 KB · shared < 4 KB · react < 8 KB brotli (`pnpm size`) |
709
- | Prisma-free | `pnpm check:no-prisma` — the library never imports `@prisma/client` |
710
- | Export map | `pnpm check:exports` — `attw` against the packed tarball, ESM and CJS |
711
- | Supply chain | published with npm provenance (OIDC), CodeQL + OpenSSF Scorecard |
704
+ | Gate | Standard |
705
+ | -------------- | ----------------------------------------------------------------------------------- |
706
+ | Type safety | TypeScript `strict`, zero `any` |
707
+ | Coverage | **100%** line/branch/function/statement per file (`pnpm test:cov:all`) |
708
+ | Mutation | Stryker score **100%** (`break: 100`), no survivors |
709
+ | Lint | ESLint flat config + `eslint-plugin-security`, zero warnings |
710
+ | Bundle budgets | server < 30 KB · shared < 4 KB · react < 8 KB · testing < 4 KB brotli (`pnpm size`) |
711
+ | Prisma-free | `pnpm check:no-prisma` — the library never imports `@prisma/client` |
712
+ | Export map | `pnpm check:exports` — `attw` against the packed tarball, ESM and CJS |
713
+ | Supply chain | published with npm provenance (OIDC), CodeQL + OpenSSF Scorecard |
712
714
 
713
715
  ```bash
714
716
  pnpm test # unit suite
@@ -757,7 +759,7 @@ pnpm mutation # Stryker mutation testing
757
759
  | -------------------------------- | -------------------------------------------------------------------------- |
758
760
  | `NotificationException` | `HttpException` carrying a stable `code`, a status, and optional `details` |
759
761
  | `NotificationExceptionOptions` | Constructor options bag: `{ status?, message?, cause? }` |
760
- | `NOTIFICATION_ERROR_CODES` | The 22 stable `notification.*` codes — branch on these, not on messages |
762
+ | `NOTIFICATION_ERROR_CODES` | The 23 stable `notification.*` codes — branch on these, not on messages |
761
763
  | `NOTIFICATION_ERROR_DEFINITIONS` | Server-side code → HTTP status + default English message |
762
764
 
763
765
  Error codes are namespaced (`notification.otp_invalid_code`, `notification.otp_cooldown_active`, `notification.email_send_failed`, …) and never change once published. Default messages are English; localize on the `code`.
@@ -797,7 +799,7 @@ The default is `true`, and deliberately so: for a receipt or a marketing send th
797
799
  | ------------------------------- | ---------------------------- | -------------------------------------------- |
798
800
  | `ResendEmailProvider` | `IEmailProvider` | Production email via Resend |
799
801
  | `SmtpEmailProvider` | `IEmailProvider` | Any SMTP relay, and Mailpit/MailHog in tests |
800
- | `NoOpEmailProvider` | `IEmailProvider` | Dev/test — logs subject and recipient only |
802
+ | `NoOpEmailProvider` | `IEmailProvider` | Dev/test — logs a masked recipient only |
801
803
  | `RedisOtpStorage` | `IOtpStorage` | Production OTP state (atomic via Lua) |
802
804
  | `InMemoryOtpStorage` | `IOtpStorage` | Dev/test — single-process only |
803
805
  | `DefaultTemplateRenderer` | `IEmailTemplateRenderer` | `{{var}}` interpolation with HTML escaping |
@@ -825,7 +827,7 @@ The default is `true`, and deliberately so: for a receipt or a marketing send th
825
827
 
826
828
  | Export | Subpath | Purpose |
827
829
  | --------------------------- | --------------------------- | -------------------------------------------------------------- |
828
- | `NOTIFICATION_ERROR_CODES` | `./shared` (and the server) | The 22 stable codes, with zero dependencies on the shared side |
830
+ | `NOTIFICATION_ERROR_CODES` | `./shared` (and the server) | The stable codes, with zero dependencies on the shared side |
829
831
  | `DEFAULT_TTLS` | `./shared` (and the server) | Default lifetimes, so a frontend countdown matches the backend |
830
832
  | `NOTIFICATION_PURPOSES` | server | Canonical purposes (`email_verification`, `password_reset`, …) |
831
833
  | `CANONICAL_EMAIL_TEMPLATES` | server | Canonical template names (`otp_code`, `welcome`, …) |
@@ -861,7 +863,7 @@ pnpm typecheck
861
863
 
862
864
  ## 🔒 Security Policy
863
865
 
864
- If you discover a security vulnerability, please **do not** open a public issue. Instead, email us at **support@bymax.one** with details. We take security seriously and will respond promptly. The full policy is in [SECURITY.md](./SECURITY.md).
866
+ If you discover a security vulnerability, please **do not** open a public issue. Instead, use GitHub Private Vulnerability Reporting (or email **support@bymax.one** if you cannot) with details. We take security seriously and will respond promptly. The full policy is in [SECURITY.md](./SECURITY.md).
865
867
 
866
868
  ---
867
869
 
@@ -102,4 +102,5 @@ declare function useOtpInput(options?: UseOtpInputOptions): UseOtpInputState;
102
102
  */
103
103
  declare function useOtpCountdown(options: UseOtpCountdownOptions): UseOtpCountdownState;
104
104
 
105
- export { type OtpInputType, type UseOtpCountdownOptions, type UseOtpCountdownState, type UseOtpInputOptions, type UseOtpInputState, useOtpCountdown, useOtpInput };
105
+ export { useOtpCountdown, useOtpInput };
106
+ export type { OtpInputType, UseOtpCountdownOptions, UseOtpCountdownState, UseOtpInputOptions, UseOtpInputState };
@@ -102,4 +102,5 @@ declare function useOtpInput(options?: UseOtpInputOptions): UseOtpInputState;
102
102
  */
103
103
  declare function useOtpCountdown(options: UseOtpCountdownOptions): UseOtpCountdownState;
104
104
 
105
- export { type OtpInputType, type UseOtpCountdownOptions, type UseOtpCountdownState, type UseOtpInputOptions, type UseOtpInputState, useOtpCountdown, useOtpInput };
105
+ export { useOtpCountdown, useOtpInput };
106
+ export type { OtpInputType, UseOtpCountdownOptions, UseOtpCountdownState, UseOtpInputOptions, UseOtpInputState };
@@ -146,7 +146,14 @@ var NOTIFICATION_ERROR_CODES = {
146
146
  PUSH_PROVIDER_NOT_CONFIGURED: "notification.push_provider_not_configured",
147
147
  PUSH_SEND_FAILED: "notification.push_send_failed",
148
148
  AUDIT_LOG_FAILED: "notification.audit_log_failed",
149
- CHANNEL_DISABLED: "notification.channel_disabled"
149
+ CHANNEL_DISABLED: "notification.channel_disabled",
150
+ /**
151
+ * A `tenantId` or `recipient` that identifies nobody reached a scoping
152
+ * boundary — empty, whitespace-only, or not a string at all. Distinct from
153
+ * {@link EMAIL_INVALID_RECIPIENT}, which is about a malformed address rather
154
+ * than a value that cannot scope anything.
155
+ */
156
+ INVALID_SCOPE_IDENTIFIER: "notification.invalid_scope_identifier"
150
157
  };
151
158
 
152
159
  // src/server/errors/notification-error-codes.ts
@@ -260,6 +267,11 @@ var NOTIFICATION_ERROR_DEFINITIONS = {
260
267
  code: NOTIFICATION_ERROR_CODES.CHANNEL_DISABLED,
261
268
  status: common.HttpStatus.NOT_IMPLEMENTED,
262
269
  message: "Channel not enabled in module config"
270
+ },
271
+ INVALID_SCOPE_IDENTIFIER: {
272
+ code: NOTIFICATION_ERROR_CODES.INVALID_SCOPE_IDENTIFIER,
273
+ status: common.HttpStatus.BAD_REQUEST,
274
+ message: "Tenant or recipient identifier does not identify anybody"
263
275
  }
264
276
  };
265
277
  var NOTIFICATION_ERROR_DEFINITION_MAP = new Map(
@@ -1186,6 +1198,23 @@ function formatCooldown(remainingSeconds) {
1186
1198
  }
1187
1199
  return parts.join(" ");
1188
1200
  }
1201
+
1202
+ // src/server/utils/tenant-scope.ts
1203
+ function refuse(owner, label, reason) {
1204
+ return new NotificationException(
1205
+ "INVALID_SCOPE_IDENTIFIER",
1206
+ { boundary: owner, parameter: label, reason },
1207
+ { message: `[${owner}] ${label} ${reason}` }
1208
+ );
1209
+ }
1210
+ function assertIdentifies(owner, label, value) {
1211
+ if (typeof value !== "string") {
1212
+ throw refuse(owner, label, `expected a string, received ${typeof value}`);
1213
+ }
1214
+ if (value.trim() === "") {
1215
+ throw refuse(owner, label, "empty or whitespace-only");
1216
+ }
1217
+ }
1189
1218
  function safeCompare(expected, actual) {
1190
1219
  const expectedBytes = Buffer.from(expected, "utf8");
1191
1220
  const actualBytes = Buffer.from(actual, "utf8");
@@ -1231,6 +1260,7 @@ exports.OtpService = class OtpService {
1231
1260
  */
1232
1261
  async generate(input) {
1233
1262
  const otp = this.requireOtpOptions();
1263
+ this.assertScope(input);
1234
1264
  const cfg = otp.resolveForPurpose(input.purpose);
1235
1265
  await this.acquireCooldownOrThrow(input, cfg.resendCooldownSeconds);
1236
1266
  const code = generateOtpCode(cfg.length, cfg.codeType);
@@ -1248,6 +1278,7 @@ exports.OtpService = class OtpService {
1248
1278
  */
1249
1279
  async verify(input) {
1250
1280
  const otp = this.requireOtpOptions();
1281
+ this.assertScope(input);
1251
1282
  const result = await this.storage.consumeAttempt(input.tenantId, input.recipient, input.purpose);
1252
1283
  if (result.status === "not_found") {
1253
1284
  await this.audit(this.otpAuditEntry("failed", input, { reason: "not_found" }));
@@ -1279,6 +1310,7 @@ exports.OtpService = class OtpService {
1279
1310
  */
1280
1311
  async consume(input) {
1281
1312
  this.requireOtpOptions();
1313
+ this.assertScope(input);
1282
1314
  await this.storage.delete(input.tenantId, input.recipient, input.purpose);
1283
1315
  await this.storage.clearCooldown(input.tenantId, input.recipient, input.purpose);
1284
1316
  }
@@ -1298,6 +1330,7 @@ exports.OtpService = class OtpService {
1298
1330
  * @returns Existence, expiry, attempt counters, validation flag, and cooldown.
1299
1331
  */
1300
1332
  async getStatus(input) {
1333
+ this.assertScope(input);
1301
1334
  const [entry, cooldownSeconds] = await Promise.all([
1302
1335
  this.storage.get(input.tenantId, input.recipient, input.purpose),
1303
1336
  this.storage.getCooldown(input.tenantId, input.recipient, input.purpose)
@@ -1419,6 +1452,19 @@ exports.OtpService = class OtpService {
1419
1452
  }
1420
1453
  await this.audit(this.otpAuditEntry("verified", input, void 0));
1421
1454
  }
1455
+ /**
1456
+ * Refuses a tenant id or recipient that identifies nobody, before any storage call.
1457
+ *
1458
+ * The reference storage already refuses these through `hashTenantRecipient`, but a
1459
+ * consumer-supplied {@link IOtpStorage} is not required to, and a blank scope would
1460
+ * then be shared by every caller that sent one.
1461
+ *
1462
+ * @throws NotificationException `INVALID_SCOPE_IDENTIFIER` when either is blank.
1463
+ */
1464
+ assertScope(ref) {
1465
+ assertIdentifies("OtpService", "tenantId", ref.tenantId);
1466
+ assertIdentifies("OtpService", "recipient", ref.recipient);
1467
+ }
1422
1468
  /** Returns the resolved OTP options or throws `OTP_STORAGE_NOT_CONFIGURED`. */
1423
1469
  requireOtpOptions() {
1424
1470
  if (!this.options.otp) {
@@ -1835,6 +1881,7 @@ function instantiate(valueOrClass) {
1835
1881
  }
1836
1882
  return new ctor();
1837
1883
  }
1884
+ var INTERCEPTOR_NAME = "NotificationAuditInterceptor";
1838
1885
  var INTERCEPTOR_PROVIDER_NAME = "__interceptor__";
1839
1886
  function toErrorMessage(error) {
1840
1887
  return error instanceof Error ? error.message : String(error);
@@ -1910,19 +1957,36 @@ exports.NotificationAuditInterceptor = class NotificationAuditInterceptor {
1910
1957
  return typeof candidate.payload === "object" && candidate.payload !== null;
1911
1958
  }
1912
1959
  /**
1913
- * Resolves the trusted tenant id: `tenantIdResolver(request)` when configured and
1914
- * a request is available, otherwise the payload-supplied `fallback`.
1960
+ * Resolves the trusted tenant id from `tenantIdResolver(request)`.
1961
+ *
1962
+ * Falls back to the payload-supplied value only when no resolver is configured or
1963
+ * no request is available — the payload reaches the handler from the caller, so
1964
+ * that value is asserted rather than authenticated, and an entry built from it
1965
+ * attributes the event to whichever tenant the caller named. Configure a resolver
1966
+ * whenever this interceptor runs on an HTTP boundary.
1967
+ *
1968
+ * A value that identifies nobody is refused rather than recorded, on BOTH paths:
1969
+ * the resolver's answer and the payload fallback. The fallback is the default path
1970
+ * — most consumers configure no resolver — so guarding only the resolver would
1971
+ * leave the common case unchecked, which is where a blank tenant actually arrives.
1972
+ *
1973
+ * @throws Error When either the resolved or the fallback tenant id is not a
1974
+ * string, or is blank.
1915
1975
  */
1916
1976
  async resolveTenantId(context, fallback) {
1917
1977
  const resolver = this.options.global.tenantIdResolver;
1918
1978
  if (resolver === void 0) {
1979
+ assertIdentifies(INTERCEPTOR_NAME, "the payload tenant id", fallback);
1919
1980
  return fallback;
1920
1981
  }
1921
1982
  const request = this.extractRequest(context);
1922
1983
  if (request === null) {
1984
+ assertIdentifies(INTERCEPTOR_NAME, "the payload tenant id", fallback);
1923
1985
  return fallback;
1924
1986
  }
1925
- return resolver(request);
1987
+ const resolved = await resolver(request);
1988
+ assertIdentifies(INTERCEPTOR_NAME, "the resolved tenant id", resolved);
1989
+ return resolved;
1926
1990
  }
1927
1991
  /** Reads the HTTP request from the context, returning `null` outside an HTTP context. */
1928
1992
  extractRequest(context) {
@@ -2050,7 +2114,8 @@ async function loadOptionalPeer(moduleName) {
2050
2114
  } catch (error) {
2051
2115
  if (isModuleNotFound(error, moduleName)) {
2052
2116
  throw new Error(
2053
- `\`${moduleName}\` package is not installed. Run \`pnpm add ${moduleName}\` in the consumer app.`
2117
+ `\`${moduleName}\` package is not installed. Run \`pnpm add ${moduleName}\` in the consumer app.`,
2118
+ { cause: error }
2054
2119
  );
2055
2120
  }
2056
2121
  const reason = error instanceof Error ? error.message : String(error);
@@ -2659,11 +2724,21 @@ _options2 = new WeakMap();
2659
2724
  exports.SmtpEmailProvider = __decorateClass([
2660
2725
  common.Injectable()
2661
2726
  ], exports.SmtpEmailProvider);
2727
+ function sha256(value) {
2728
+ return crypto.createHash("sha256").update(value).digest("hex");
2729
+ }
2730
+ function hashTenantRecipient(tenantId, recipient) {
2731
+ assertIdentifies("hashTenantRecipient", "tenantId", tenantId);
2732
+ assertIdentifies("hashTenantRecipient", "recipient", recipient);
2733
+ return crypto.createHash("sha256").update(`${sha256(tenantId)}:${sha256(recipient)}`).digest("hex");
2734
+ }
2735
+
2736
+ // src/server/providers/in-memory-otp.storage.ts
2662
2737
  var MS_PER_SECOND3 = 1e3;
2663
2738
  exports.InMemoryOtpStorage = class InMemoryOtpStorage {
2664
2739
  constructor() {
2665
2740
  this.name = "memory";
2666
- /** OTP entries keyed by `${tenantId}::${recipient}::${purpose}`. */
2741
+ /** OTP entries keyed by `${hashTenantRecipient(tenantId, recipient)}::${purpose}`. */
2667
2742
  this.store = /* @__PURE__ */ new Map();
2668
2743
  /** Cooldown expiries (epoch ms) keyed by the same composite key. */
2669
2744
  this.cooldowns = /* @__PURE__ */ new Map();
@@ -2822,19 +2897,22 @@ exports.InMemoryOtpStorage = class InMemoryOtpStorage {
2822
2897
  size() {
2823
2898
  return { otps: this.store.size, cooldowns: this.cooldowns.size };
2824
2899
  }
2825
- /** Collapses the `(tenantId, recipient, purpose)` tuple into one map key. */
2900
+ /**
2901
+ * Collapses the `(tenantId, recipient, purpose)` tuple into one map key.
2902
+ *
2903
+ * The tenant and recipient go through {@link hashTenantRecipient}, which encodes
2904
+ * the pair unambiguously and rejects an empty component. Joining the raw values
2905
+ * around a delimiter would not: `('a::b', 'c', p)` and `('a', 'b::c', p)` produce
2906
+ * the same string. The digest is fixed-length, so appending the purpose after it
2907
+ * stays unambiguous too.
2908
+ */
2826
2909
  key(tenantId, recipient, purpose) {
2827
- return `${tenantId}::${recipient}::${purpose}`;
2910
+ return `${hashTenantRecipient(tenantId, recipient)}::${purpose}`;
2828
2911
  }
2829
2912
  };
2830
2913
  exports.InMemoryOtpStorage = __decorateClass([
2831
2914
  common.Injectable()
2832
2915
  ], exports.InMemoryOtpStorage);
2833
- function hashTenantRecipient(tenantId, recipient) {
2834
- return crypto.createHash("sha256").update(`${tenantId}:${recipient}`).digest("hex");
2835
- }
2836
-
2837
- // src/server/providers/redis-otp.storage.ts
2838
2916
  var MS_PER_SECOND4 = 1e3;
2839
2917
  var _redis;
2840
2918
  exports.RedisOtpStorage = class RedisOtpStorage {
@@ -2988,11 +3066,11 @@ exports.RedisOtpStorage = class RedisOtpStorage {
2988
3066
  async clearCooldown(tenantId, recipient, purpose) {
2989
3067
  await __privateGet(this, _redis).del(this.cooldownKey(tenantId, recipient, purpose));
2990
3068
  }
2991
- /** Builds the OTP entry key: `{namespace}:otp:{purpose}:{sha256(tenantId:recipient)}`. */
3069
+ /** Builds the OTP entry key: `{namespace}:otp:{purpose}:{hashTenantRecipient(...)}`. */
2992
3070
  otpKey(tenantId, recipient, purpose) {
2993
3071
  return `${this.namespace}:otp:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
2994
3072
  }
2995
- /** Builds the cooldown key: `{namespace}:otp_cd:{purpose}:{sha256(tenantId:recipient)}`. */
3073
+ /** Builds the cooldown key: `{namespace}:otp_cd:{purpose}:{hashTenantRecipient(...)}`. */
2996
3074
  cooldownKey(tenantId, recipient, purpose) {
2997
3075
  return `${this.namespace}:otp_cd:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
2998
3076
  }