@bymax-one/nest-notification 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,121 @@ 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
+ ## [1.4.0] - 2026-09-04
9
+
10
+ > ### ⚠️ Read before deploying — the version number does not warn you
11
+ >
12
+ > **Every OTP storage key changes in this release, and nothing in the type system will tell
13
+ > you.** It compiles, the suite passes, and on deploy every OTP and resend cooldown still in
14
+ > flight becomes unreachable. An operator reading `fix(otp)` and a minor version bump will not
15
+ > infer that every code in flight stops working — this paragraph is the only warning there is.
16
+ >
17
+ > **Scope, so this reads as accurate rather than alarming.** The defect it fixes is a
18
+ > cross-tenant key collision that is real in the library and **unreachable in today's only
19
+ > consumer**: `bymax-one` resolves tenants through a host-label guard that rejects both an empty
20
+ > label and a colon, so it provably never emits an identity that could collide. A backend
21
+ > resolving tenants from a database column, a JWT claim or an admin-entered field inherits none
22
+ > of that protection.
23
+ >
24
+ > What to do about it is in [Apply to a derived backend](#-apply-to-a-derived-backend) below.
25
+
26
+ ### Security
27
+
28
+ - **Storage keys no longer collapse two different `(tenantId, recipient)` pairs onto one key.**
29
+ The key was `sha256(`${tenantId}:${recipient}`)` — the two fields joined around a delimiter,
30
+ which does not encode where the boundary falls. `('acme:bob', 'x')` and `('acme', 'bob:x')`
31
+ produced the same input string and therefore the same key, so under a consumer whose tenant
32
+ ids or recipient ids can contain a colon, one tenant's `verify` could consume another tenant's
33
+ OTP. Each component is now hashed to a fixed length before the two are joined:
34
+ `sha256(sha256(tenantId):sha256(recipient))`.
35
+
36
+ This was never a weakness in SHA-256, and the documentation said otherwise — `README.md` and
37
+ `CLAUDE.md` claimed cross-tenant collision was "computationally infeasible (SHA-256 preimage
38
+ resistance)". Preimage resistance is irrelevant to it: the two pairs were the same input, and
39
+ every digest property held perfectly while they collided. Those claims are corrected.
40
+
41
+ `InMemoryOtpStorage` composed its map key the same way, with `::`, and had the same defect.
42
+
43
+ - **New error code `notification.invalid_scope_identifier`** (23 codes, up from 22). The refusal
44
+ below is a `NotificationException` rather than a bare `Error`: it reaches a consumer through
45
+ every `IOtpStorage` method, and this library's contract is that a consumer branches on `code`.
46
+ A raw throw surfaced as an untyped 500 carrying an internal message, where the condition is a
47
+ 400 the caller can act on. `details` names the boundary, the parameter and the reason — never
48
+ the value, which is serialized into the response and is exactly what must not be echoed back.
49
+
50
+ - **A component that identifies nothing is refused rather than hashed** — empty, whitespace-only,
51
+ or not a string at all. An empty component put every caller that omitted it into one shared
52
+ namespace, the same isolation failure reached from the other side. Whitespace produced a
53
+ distinct key and therefore no collision, but named no tenant. The `typeof` check is there
54
+ because the declared `string` is a contract this library states and a consumer may not honour:
55
+ a `null` claim or a numeric database id type-checks at their call site and previously failed
56
+ inside `createHash` with a message naming crypto's `data` argument instead of this rule.
57
+
58
+ - **`NotificationAuditInterceptor` refuses an empty tenant id from `tenantIdResolver`.** An empty
59
+ scope does not identify a tenant, and recording it filed the event under a scope shared with
60
+ every other empty result. The refusal is subject to `audit.swallowErrors` like any other audit
61
+ failure: the entry is skipped rather than written wrong.
62
+
63
+ ### ⚠️ Apply to a derived backend
64
+
65
+ **Every OTP storage key changes with this release, and nothing in the type system will tell you.**
66
+ It compiles, the suite passes, and on deploy every OTP and resend cooldown still in flight becomes
67
+ unreachable — the old keys are never read again. Consequences to plan for:
68
+
69
+ - Users mid-verification get `OTP_NOT_FOUND` and must request a new code.
70
+ - Resend cooldowns reset, so a user who was throttled can request again immediately.
71
+ - Stale entries expire on their own TTL; nothing needs to be purged, but nothing is migrated
72
+ either. There is no dual-read path, deliberately: reading the old construction back would mean
73
+ keeping the colliding key alive.
74
+
75
+ Deploy when a short window of "request your code again" is acceptable, or drain OTP traffic first.
76
+
77
+ **If you implement `IOtpStorage` yourself,** re-run the contract from `@bymax-one/nest-notification/testing`.
78
+ It has two new cases — `keeps the tenant and recipient boundary when composing a key` and the same
79
+ for a cooldown key — which fail any implementation that concatenates the two fields around a
80
+ delimiter. **Both are needed:** the entry key and the cooldown key are composed separately, so a
81
+ storage that fixes one and not the other passes every case that exercises only the first. 21 cases,
82
+ up from 19. A survey
83
+ of the sibling libraries found 108 composite key constructions and 2 that encode their components,
84
+ so this defect is the default rather than the exception.
85
+
86
+ ### Fixed
87
+
88
+ - `loadOptionalPeer` attaches the caught error as `cause` on the "package is not installed" path
89
+ as well, so a resolution failure names the specifier the runtime actually rejected.
90
+
91
+ ## [1.3.1] - 2026-08-18
92
+
93
+ ### Documentation
94
+
95
+ Code is unchanged: the built `dist/` is byte-identical to 1.3.0, verified by unpacking the
96
+ published tarball and diffing it against a fresh build. This release exists because the README
97
+ ships inside the package and one of its security claims described the behaviour of 1.2.2.
98
+
99
+ - **Corrected: what the OTP path writes to its audit entry.** The README said OTP delivery
100
+ "declares the code via `auditRedactValues`, and `EmailService` redacts it from the entry's
101
+ `errorMessage`". That was true until 1.3.0, which made the OTP path set
102
+ `publishProviderText: false` — so the entry now records the fixed label
103
+ `[provider text withheld]` plus the structured reply codes, and the provider's own words never
104
+ reach it. The declaration remains, as precision for the paths that do publish text.
105
+ - **`publishProviderText` is now documented rather than mentioned in passing.** It appeared once,
106
+ inside a paragraph about the ceiling of redaction, despite being the feature 1.3.0 is named
107
+ after. It has its own section: what the failure carries, the structured fields it publishes, a
108
+ worked example, and the three properties worth knowing before relying on it — the codes are
109
+ independent of the secret, ambiguity resolves to silence, and a code colliding with a declared
110
+ value is dropped.
111
+ - **Documented: the two surfaces name the reply codes differently.** The audit entry carries
112
+ `deliveryStatus` / `deliveryEnhancedStatus`; the exception's `details` carries `status` /
113
+ `enhanced`. The README said they were "the same pair", which would have sent a consumer looking
114
+ for keys that are not there — and it contradicted the worked example three lines below it. Both
115
+ shapes are now named, and the example shows the audit entry alongside the exception. (The
116
+ inconsistency itself is API surface shipped in 1.3.0; unifying the names would be a breaking
117
+ change, so it stays a 1.4.0 question rather than something a patch quietly alters.)
118
+ - Internal docs caught up with the fourth subpath: the subpath tables in `CLAUDE.md` and
119
+ `docs/technical_specification.md` listed three, and `AGENTS.md` described neither the storage
120
+ contract nor the withholding flag. None of these ship, so they did not force this release; they
121
+ are here because the sweep that found the README claim found them too.
122
+
8
123
  ## [1.3.0] - 2026-08-17
9
124
 
10
125
  ### Added
@@ -573,7 +688,9 @@ rejected at startup rather than failing on the first send.
573
688
 
574
689
  [1.0.4]: https://github.com/bymaxone/nest-notification/compare/v1.0.3...v1.0.4
575
690
  [1.0.3]: https://github.com/bymaxone/nest-notification/compare/v1.0.2...v1.0.3
576
- [Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.3.0...HEAD
691
+ [Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.4.0...HEAD
692
+ [1.4.0]: https://github.com/bymaxone/nest-notification/compare/v1.3.1...v1.4.0
693
+ [1.3.1]: https://github.com/bymaxone/nest-notification/compare/v1.3.0...v1.3.1
577
694
  [1.3.0]: https://github.com/bymaxone/nest-notification/compare/v1.2.2...v1.3.0
578
695
  [1.2.2]: https://github.com/bymaxone/nest-notification/compare/v1.2.1...v1.2.2
579
696
  [1.2.1]: https://github.com/bymaxone/nest-notification/compare/v1.2.0...v1.2.1
package/README.md CHANGED
@@ -40,7 +40,7 @@ Everything that touches the outside world — the email transport, the OTP store
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.
@@ -71,7 +71,7 @@ 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
@@ -79,7 +79,7 @@ pnpm add @bymax-one/nest-notification
79
79
  ### 🧩 Developer Experience
80
80
 
81
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`
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
 
@@ -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
 
@@ -629,7 +629,7 @@ The library **never** writes a code to a sink that can be read back:
629
629
  - Not to the audit log — an entry is `{ verb, tenantId, recipient, purpose, providerName, … }`, never `code`.
630
630
  - Not to a console or logger line.
631
631
  - Not inside an `errorMessage`, which carries the message only — never a stack trace.
632
- - Not inside a rethrown delivery error: the renderer and the provider both receive the code (template `data`, rendered body), so on a failed delivery every **literal** occurrence of the code — the form it was issued in, which is the form this library's own text carries — is scrubbed to `[redacted]` across the outgoing error chain — message **and** stack at every link, cycle-safe with no depth limit — before the audit write and the rethrow, and a non-`Error` rejection is flattened to a redacted string. The email channel's own `failed` audit entry is covered too: OTP delivery declares the code via `auditRedactValues`, and `EmailService` redacts it from the entry's `errorMessage`. Default V8 stack frames carry only function names and source locations, never argument values; the header line (`Error: <message>`) is where a code could ride a stack, and the scrub covers it.
632
+ - Not inside a rethrown delivery error: the renderer and the provider both receive the code (template `data`, rendered body), so on a failed delivery every **literal** occurrence of the code — the form it was issued in, which is the form this library's own text carries — is scrubbed to `[redacted]` across the outgoing error chain — message **and** stack at every link, cycle-safe with no depth limit — before the audit write and the rethrow, and a non-`Error` rejection is flattened to a redacted string. The email channel's own `failed` audit entry goes further than redaction: OTP delivery sets `publishProviderText: false`, so that entry records the fixed label `[provider text withheld]` plus the SMTP reply codes a fixed grammar can express — never the provider's own words. It also declares the code via `auditRedactValues`, which stays as precision for the paths that do publish text. Default V8 stack frames carry only function names and source locations, never argument values; the header line (`Error: <message>`) is where a code could ride a stack, and the scrub covers it.
633
633
 
634
634
  Within this library, codes exist only inside the OTP store, under a TTL, and in process memory for the duration of the request — a provider that quotes the body back is outside that boundary, and its ceiling is documented under [Errors](#errors). `audit.maskRecipient` minimizes the recipient before it is persisted (`jane@acme.com` → `j***@acme.com`). A regression test asserts the invariant directly rather than trusting review: `JSON.stringify(auditEntry).includes(code) === false`.
635
635
 
@@ -656,7 +656,7 @@ When integrating `@bymax-one/nest-notification` in production, verify each of th
656
656
  | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
657
657
  | Code Generation | `crypto.randomInt` per character over the configured alphabet — uniform at every position, no modulo bias |
658
658
  | Code Comparison | `crypto.timingSafeEqual` (constant-time), never `===` |
659
- | Storage Keys | `sha256(tenantId:recipient)` — no recipient PII, no cross-tenant collision |
659
+ | 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
660
  | Attempt Ceiling | Counter spent atomically inside the storage (Redis Lua) — never a service-side read-then-write |
661
661
  | Resend Cooldown | `SET NX EX` acquire, released only on delivery failure — two concurrent resends cannot both win |
662
662
  | Code Lifetime | TTL-bound in the store; expiry and absence are reported identically so neither leaks the other |
@@ -757,7 +757,7 @@ pnpm mutation # Stryker mutation testing
757
757
  | -------------------------------- | -------------------------------------------------------------------------- |
758
758
  | `NotificationException` | `HttpException` carrying a stable `code`, a status, and optional `details` |
759
759
  | `NotificationExceptionOptions` | Constructor options bag: `{ status?, message?, cause? }` |
760
- | `NOTIFICATION_ERROR_CODES` | The 22 stable `notification.*` codes — branch on these, not on messages |
760
+ | `NOTIFICATION_ERROR_CODES` | The 23 stable `notification.*` codes — branch on these, not on messages |
761
761
  | `NOTIFICATION_ERROR_DEFINITIONS` | Server-side code → HTTP status + default English message |
762
762
 
763
763
  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`.
@@ -766,6 +766,29 @@ Failures raised by the library carry the underlying error as the native `Error.c
766
766
 
767
767
  **If you send a secret through `EmailService` yourself — declare it, and treat the provider's error text as untrusted anyway.** A relay or DLP filter that quotes the rejected content puts the rendered body (and any secret inside it) into the provider error, which rides the `cause` into your logs. Pass `auditRedactValues: [code]` on the send input: the value is scrubbed from the attached `cause`, from the failed-audit `errorMessage`, and — forwarded as `EmailSendOptions.redactValues` — from the provider's own error logging. As defense-in-depth for the undeclared case, any run of 16+ characters of the rendered body detected inside a provider error is redacted automatically.
768
768
 
769
+ **Withholding provider text — `publishProviderText: false`.** For a message whose body carries a credential, set it on the send input (`EmailService.send` or `sendTemplate`); the built-in OTP delivery already does. The failure then carries **no byte the provider wrote**: no `cause`, and the audit entry's `errorMessage` is the fixed label `[provider text withheld]`.
770
+
771
+ What it publishes instead is what a fixed grammar can express — the basic SMTP reply code and, when present, the RFC 3463 enhanced code — as structured fields. The two surfaces name them differently, so read the right keys: the audit entry carries `deliveryStatus` and `deliveryEnhancedStatus`, while the exception's `details` carries `status` and `enhanced`.
772
+
773
+ ```ts
774
+ await emailService.send({
775
+ tenantId,
776
+ to: user.email,
777
+ subject: 'Your code',
778
+ html: rendered,
779
+ publishProviderText: false // this body carries a credential
780
+ })
781
+ // On failure: NotificationException('notification.email_send_failed')
782
+ // details → { providerName: 'smtp', status: 550, enhanced: '5.7.1' }
783
+ // cause → absent
784
+ // Audit entry: { verb: 'failed', errorMessage: '[provider text withheld]',
785
+ // deliveryStatus: 550, deliveryEnhancedStatus: '5.7.1', … }
786
+ ```
787
+
788
+ Three properties worth knowing before you rely on it. The published codes are **independent of the secret** — the same reply publishes `550 5.7.1` whether the code was `550571`, `123456` or absent — which is why they are safe to log while the prose is not. **Ambiguity resolves to silence**: a text carrying two different replies publishes neither, so a cause chain cannot have `424` and `242` read as one value. And a code that would carry a **declared** secret is dropped, since this library's invariant is that a code's characters never reach an audit entry.
789
+
790
+ The default is `true`, and deliberately so: for a receipt or a marketing send the provider's message is often the only diagnosis available. The flag is **per send, never global** — one setting cannot serve an OTP path and a marketing path in the same application.
791
+
769
792
  **Know the ceiling of both guards.** They remove the shapes they can predict, and a relay quotes what it _transmitted_, not what you handed it — a MIME body travels raw, quoted-printable or base64. A declared `123456` cannot match `MTIzNDU2`, and echo detection compares the error against the rendered body it holds, not against the encoding the relay chose; measured, an error quoting the base64 of the body survives both. No list of values closes an encoding gap. So control whether provider error text reaches your logs at all for secret-bearing sends — pass `publishProviderText: false` on the send input, which withholds every provider-authored byte and publishes only the SMTP reply codes a fixed grammar can express — and use declared values as precision on top of that rather than as the barrier. If you consume `@bymax-one/nest-auth` and bind its bundled `DefaultAuthEmailProvider`, that provider is the call site, so the declaration belongs there rather than in your application code; if you implement `nest-auth`'s email port yourself, your adapter is the call site and the declaration is yours to make.
770
793
 
771
794
  ### Reference adapters
@@ -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(
@@ -1835,6 +1847,26 @@ function instantiate(valueOrClass) {
1835
1847
  }
1836
1848
  return new ctor();
1837
1849
  }
1850
+
1851
+ // src/server/utils/tenant-scope.ts
1852
+ function refuse(owner, label, reason) {
1853
+ return new NotificationException(
1854
+ "INVALID_SCOPE_IDENTIFIER",
1855
+ { boundary: owner, parameter: label, reason },
1856
+ { message: `[${owner}] ${label} ${reason}` }
1857
+ );
1858
+ }
1859
+ function assertIdentifies(owner, label, value) {
1860
+ if (typeof value !== "string") {
1861
+ throw refuse(owner, label, `expected a string, received ${typeof value}`);
1862
+ }
1863
+ if (value.trim() === "") {
1864
+ throw refuse(owner, label, "empty or whitespace-only");
1865
+ }
1866
+ }
1867
+
1868
+ // src/server/interceptors/notification-audit.interceptor.ts
1869
+ var INTERCEPTOR_NAME = "NotificationAuditInterceptor";
1838
1870
  var INTERCEPTOR_PROVIDER_NAME = "__interceptor__";
1839
1871
  function toErrorMessage(error) {
1840
1872
  return error instanceof Error ? error.message : String(error);
@@ -1910,19 +1942,36 @@ exports.NotificationAuditInterceptor = class NotificationAuditInterceptor {
1910
1942
  return typeof candidate.payload === "object" && candidate.payload !== null;
1911
1943
  }
1912
1944
  /**
1913
- * Resolves the trusted tenant id: `tenantIdResolver(request)` when configured and
1914
- * a request is available, otherwise the payload-supplied `fallback`.
1945
+ * Resolves the trusted tenant id from `tenantIdResolver(request)`.
1946
+ *
1947
+ * Falls back to the payload-supplied value only when no resolver is configured or
1948
+ * no request is available — the payload reaches the handler from the caller, so
1949
+ * that value is asserted rather than authenticated, and an entry built from it
1950
+ * attributes the event to whichever tenant the caller named. Configure a resolver
1951
+ * whenever this interceptor runs on an HTTP boundary.
1952
+ *
1953
+ * A value that identifies nobody is refused rather than recorded, on BOTH paths:
1954
+ * the resolver's answer and the payload fallback. The fallback is the default path
1955
+ * — most consumers configure no resolver — so guarding only the resolver would
1956
+ * leave the common case unchecked, which is where a blank tenant actually arrives.
1957
+ *
1958
+ * @throws Error When either the resolved or the fallback tenant id is not a
1959
+ * string, or is blank.
1915
1960
  */
1916
1961
  async resolveTenantId(context, fallback) {
1917
1962
  const resolver = this.options.global.tenantIdResolver;
1918
1963
  if (resolver === void 0) {
1964
+ assertIdentifies(INTERCEPTOR_NAME, "the payload tenant id", fallback);
1919
1965
  return fallback;
1920
1966
  }
1921
1967
  const request = this.extractRequest(context);
1922
1968
  if (request === null) {
1969
+ assertIdentifies(INTERCEPTOR_NAME, "the payload tenant id", fallback);
1923
1970
  return fallback;
1924
1971
  }
1925
- return resolver(request);
1972
+ const resolved = await resolver(request);
1973
+ assertIdentifies(INTERCEPTOR_NAME, "the resolved tenant id", resolved);
1974
+ return resolved;
1926
1975
  }
1927
1976
  /** Reads the HTTP request from the context, returning `null` outside an HTTP context. */
1928
1977
  extractRequest(context) {
@@ -2050,7 +2099,8 @@ async function loadOptionalPeer(moduleName) {
2050
2099
  } catch (error) {
2051
2100
  if (isModuleNotFound(error, moduleName)) {
2052
2101
  throw new Error(
2053
- `\`${moduleName}\` package is not installed. Run \`pnpm add ${moduleName}\` in the consumer app.`
2102
+ `\`${moduleName}\` package is not installed. Run \`pnpm add ${moduleName}\` in the consumer app.`,
2103
+ { cause: error }
2054
2104
  );
2055
2105
  }
2056
2106
  const reason = error instanceof Error ? error.message : String(error);
@@ -2659,11 +2709,21 @@ _options2 = new WeakMap();
2659
2709
  exports.SmtpEmailProvider = __decorateClass([
2660
2710
  common.Injectable()
2661
2711
  ], exports.SmtpEmailProvider);
2712
+ function sha256(value) {
2713
+ return crypto.createHash("sha256").update(value).digest("hex");
2714
+ }
2715
+ function hashTenantRecipient(tenantId, recipient) {
2716
+ assertIdentifies("hashTenantRecipient", "tenantId", tenantId);
2717
+ assertIdentifies("hashTenantRecipient", "recipient", recipient);
2718
+ return crypto.createHash("sha256").update(`${sha256(tenantId)}:${sha256(recipient)}`).digest("hex");
2719
+ }
2720
+
2721
+ // src/server/providers/in-memory-otp.storage.ts
2662
2722
  var MS_PER_SECOND3 = 1e3;
2663
2723
  exports.InMemoryOtpStorage = class InMemoryOtpStorage {
2664
2724
  constructor() {
2665
2725
  this.name = "memory";
2666
- /** OTP entries keyed by `${tenantId}::${recipient}::${purpose}`. */
2726
+ /** OTP entries keyed by `${hashTenantRecipient(tenantId, recipient)}::${purpose}`. */
2667
2727
  this.store = /* @__PURE__ */ new Map();
2668
2728
  /** Cooldown expiries (epoch ms) keyed by the same composite key. */
2669
2729
  this.cooldowns = /* @__PURE__ */ new Map();
@@ -2822,19 +2882,22 @@ exports.InMemoryOtpStorage = class InMemoryOtpStorage {
2822
2882
  size() {
2823
2883
  return { otps: this.store.size, cooldowns: this.cooldowns.size };
2824
2884
  }
2825
- /** Collapses the `(tenantId, recipient, purpose)` tuple into one map key. */
2885
+ /**
2886
+ * Collapses the `(tenantId, recipient, purpose)` tuple into one map key.
2887
+ *
2888
+ * The tenant and recipient go through {@link hashTenantRecipient}, which encodes
2889
+ * the pair unambiguously and rejects an empty component. Joining the raw values
2890
+ * around a delimiter would not: `('a::b', 'c', p)` and `('a', 'b::c', p)` produce
2891
+ * the same string. The digest is fixed-length, so appending the purpose after it
2892
+ * stays unambiguous too.
2893
+ */
2826
2894
  key(tenantId, recipient, purpose) {
2827
- return `${tenantId}::${recipient}::${purpose}`;
2895
+ return `${hashTenantRecipient(tenantId, recipient)}::${purpose}`;
2828
2896
  }
2829
2897
  };
2830
2898
  exports.InMemoryOtpStorage = __decorateClass([
2831
2899
  common.Injectable()
2832
2900
  ], 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
2901
  var MS_PER_SECOND4 = 1e3;
2839
2902
  var _redis;
2840
2903
  exports.RedisOtpStorage = class RedisOtpStorage {
@@ -2988,11 +3051,11 @@ exports.RedisOtpStorage = class RedisOtpStorage {
2988
3051
  async clearCooldown(tenantId, recipient, purpose) {
2989
3052
  await __privateGet(this, _redis).del(this.cooldownKey(tenantId, recipient, purpose));
2990
3053
  }
2991
- /** Builds the OTP entry key: `{namespace}:otp:{purpose}:{sha256(tenantId:recipient)}`. */
3054
+ /** Builds the OTP entry key: `{namespace}:otp:{purpose}:{hashTenantRecipient(...)}`. */
2992
3055
  otpKey(tenantId, recipient, purpose) {
2993
3056
  return `${this.namespace}:otp:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
2994
3057
  }
2995
- /** Builds the cooldown key: `{namespace}:otp_cd:{purpose}:{sha256(tenantId:recipient)}`. */
3058
+ /** Builds the cooldown key: `{namespace}:otp_cd:{purpose}:{hashTenantRecipient(...)}`. */
2996
3059
  cooldownKey(tenantId, recipient, purpose) {
2997
3060
  return `${this.namespace}:otp_cd:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
2998
3061
  }
@@ -1253,8 +1253,21 @@ declare class NotificationAuditInterceptor implements NestInterceptor {
1253
1253
  /** Narrows an unknown argument to a {@link DispatchInput} by structural shape. */
1254
1254
  private isDispatchInput;
1255
1255
  /**
1256
- * Resolves the trusted tenant id: `tenantIdResolver(request)` when configured and
1257
- * a request is available, otherwise the payload-supplied `fallback`.
1256
+ * Resolves the trusted tenant id from `tenantIdResolver(request)`.
1257
+ *
1258
+ * Falls back to the payload-supplied value only when no resolver is configured or
1259
+ * no request is available — the payload reaches the handler from the caller, so
1260
+ * that value is asserted rather than authenticated, and an entry built from it
1261
+ * attributes the event to whichever tenant the caller named. Configure a resolver
1262
+ * whenever this interceptor runs on an HTTP boundary.
1263
+ *
1264
+ * A value that identifies nobody is refused rather than recorded, on BOTH paths:
1265
+ * the resolver's answer and the payload fallback. The fallback is the default path
1266
+ * — most consumers configure no resolver — so guarding only the resolver would
1267
+ * leave the common case unchecked, which is where a blank tenant actually arrives.
1268
+ *
1269
+ * @throws Error When either the resolved or the fallback tenant id is not a
1270
+ * string, or is blank.
1258
1271
  */
1259
1272
  private resolveTenantId;
1260
1273
  /** Reads the HTTP request from the context, returning `null` outside an HTTP context. */
@@ -1974,7 +1987,7 @@ interface InMemoryStorageSize {
1974
1987
  /** Process-local `IOtpStorage` for dev/test. */
1975
1988
  declare class InMemoryOtpStorage implements IOtpStorage {
1976
1989
  readonly name = "memory";
1977
- /** OTP entries keyed by `${tenantId}::${recipient}::${purpose}`. */
1990
+ /** OTP entries keyed by `${hashTenantRecipient(tenantId, recipient)}::${purpose}`. */
1978
1991
  private readonly store;
1979
1992
  /** Cooldown expiries (epoch ms) keyed by the same composite key. */
1980
1993
  private readonly cooldowns;
@@ -2066,7 +2079,15 @@ declare class InMemoryOtpStorage implements IOtpStorage {
2066
2079
  * @returns The number of stored OTP entries and active cooldowns.
2067
2080
  */
2068
2081
  size(): InMemoryStorageSize;
2069
- /** Collapses the `(tenantId, recipient, purpose)` tuple into one map key. */
2082
+ /**
2083
+ * Collapses the `(tenantId, recipient, purpose)` tuple into one map key.
2084
+ *
2085
+ * The tenant and recipient go through {@link hashTenantRecipient}, which encodes
2086
+ * the pair unambiguously and rejects an empty component. Joining the raw values
2087
+ * around a delimiter would not: `('a::b', 'c', p)` and `('a', 'b::c', p)` produce
2088
+ * the same string. The digest is fixed-length, so appending the purpose after it
2089
+ * stays unambiguous too.
2090
+ */
2070
2091
  private key;
2071
2092
  }
2072
2093
 
@@ -2081,9 +2102,11 @@ declare class InMemoryOtpStorage implements IOtpStorage {
2081
2102
  * read → expiry/max check → increment → write sequence inside ONE Lua script
2082
2103
  * (`EVAL`), so concurrent verifications cannot interleave and overshoot
2083
2104
  * `maxAttempts`.
2084
- * 2. **PII-free keys** — every key carries `sha256(tenantId:recipient)`, never the
2085
- * plaintext email/phone, so an operator with `KEYS` access cannot enumerate
2086
- * recipients, and a cross-tenant key collision is computationally infeasible.
2105
+ * 2. **PII-free keys** — every key carries `sha256(sha256(tenantId):sha256(recipient))`,
2106
+ * never the plaintext email/phone, so an operator with `KEYS` access cannot
2107
+ * enumerate recipients. Each component is hashed before the join so the encoding
2108
+ * itself admits no ambiguity: joining the raw values would map `('a:b', 'c')` and
2109
+ * `('a', 'b:c')` onto one key, which no digest strength repairs.
2087
2110
  *
2088
2111
  * `ioredis` is an OPTIONAL peer dependency: this class forward-declares the slim
2089
2112
  * {@link RedisLike} surface it needs (including `eval`/`pttl`) instead of importing
@@ -2206,9 +2229,9 @@ declare class RedisOtpStorage implements IOtpStorage {
2206
2229
  * @param purpose - OTP purpose.
2207
2230
  */
2208
2231
  clearCooldown(tenantId: string, recipient: string, purpose: string): Promise<void>;
2209
- /** Builds the OTP entry key: `{namespace}:otp:{purpose}:{sha256(tenantId:recipient)}`. */
2232
+ /** Builds the OTP entry key: `{namespace}:otp:{purpose}:{hashTenantRecipient(...)}`. */
2210
2233
  private otpKey;
2211
- /** Builds the cooldown key: `{namespace}:otp_cd:{purpose}:{sha256(tenantId:recipient)}`. */
2234
+ /** Builds the cooldown key: `{namespace}:otp_cd:{purpose}:{hashTenantRecipient(...)}`. */
2212
2235
  private cooldownKey;
2213
2236
  }
2214
2237
 
@@ -2216,18 +2239,38 @@ declare class RedisOtpStorage implements IOtpStorage {
2216
2239
  * @fileoverview SHA-256 hashing of `(tenantId, recipient)` for storage keys.
2217
2240
  * @layer infrastructure
2218
2241
  *
2219
- * Storage keys are `sha256(`${tenantId}:${recipient}`)` for two reasons:
2242
+ * Storage keys are `sha256(sha256(tenantId):sha256(recipient))` for two reasons:
2220
2243
  * 1. Privacy — an operator with `KEYS`-level access to the store cannot enumerate
2221
2244
  * the email/phone of every recipient with a pending OTP.
2222
- * 2. Multi-tenancy — SHA-256 preimage resistance makes a cross-tenant key
2223
- * collision computationally infeasible.
2245
+ * 2. Multi-tenancy — each component is hashed to a fixed length BEFORE the two are
2246
+ * joined, so no two distinct pairs can produce the same input string.
2247
+ *
2248
+ * The second point is about the encoding, not about the digest, and no property of
2249
+ * SHA-256 substitutes for it. Joining the raw values around a delimiter makes
2250
+ * `('acme:bob', 'x')` and `('acme', 'bob:x')` produce the same input string — and
2251
+ * therefore the same key — while preimage and collision resistance hold perfectly.
2252
+ *
2253
+ * What that buys is precise, and overclaiming it would repeat the mistake it fixes:
2254
+ * distinct pairs are no longer *constructibly* mapped onto one key, because the
2255
+ * ambiguity was in the encoding and the encoding is now unique. The key itself stays
2256
+ * collision-RESISTANT rather than collision-free — an unbounded domain cannot map
2257
+ * injectively into 256 bits, and no construction changes that.
2258
+ *
2259
+ * A component that names no tenant and no recipient is refused rather than hashed:
2260
+ * empty, whitespace-only, or not a string at all. `('', r)` would put every caller
2261
+ * that omits a tenant into one shared namespace — the same isolation failure arrived
2262
+ * at from the other side.
2224
2263
  */
2225
2264
  /**
2226
2265
  * Derives a deterministic, PII-free storage key fragment from a tenant and recipient.
2227
2266
  *
2228
- * @param tenantId - Tenant isolation scope.
2229
- * @param recipient - Pre-normalized recipient identifier.
2230
- * @returns A 64-character lowercase hex SHA-256 digest. Order-sensitive.
2267
+ * @param tenantId - Tenant isolation scope. Must be a non-blank string.
2268
+ * @param recipient - Pre-normalized recipient identifier. Must be a non-blank string.
2269
+ * @returns A 64-character lowercase hex SHA-256 digest. Order-sensitive, and unique
2270
+ * per pair up to SHA-256's collision resistance — the encoding contributes no
2271
+ * ambiguity of its own, so two distinct pairs never map onto one key by
2272
+ * construction.
2273
+ * @throws Error When either component is not a string, or is empty or whitespace-only.
2231
2274
  */
2232
2275
  declare function hashTenantRecipient(tenantId: string, recipient: string): string;
2233
2276
 
@@ -2336,8 +2379,8 @@ declare function formatCooldown(remainingSeconds: number): string;
2336
2379
  * Stable error-code identifiers, keyed by their symbolic name.
2337
2380
  *
2338
2381
  * Values are namespaced under `notification.*` and never change once published —
2339
- * consumers branch on them to localize messages. The 22 entries cover the email,
2340
- * template, OTP, SMS, push, audit, and channel-config failure surfaces.
2382
+ * consumers branch on them to localize messages. The 23 entries cover the email,
2383
+ * template, OTP, SMS, push, audit, channel-config and scoping failure surfaces.
2341
2384
  */
2342
2385
  declare const NOTIFICATION_ERROR_CODES: {
2343
2386
  readonly EMAIL_PROVIDER_NOT_CONFIGURED: "notification.email_provider_not_configured";
@@ -2363,6 +2406,13 @@ declare const NOTIFICATION_ERROR_CODES: {
2363
2406
  readonly PUSH_SEND_FAILED: "notification.push_send_failed";
2364
2407
  readonly AUDIT_LOG_FAILED: "notification.audit_log_failed";
2365
2408
  readonly CHANNEL_DISABLED: "notification.channel_disabled";
2409
+ /**
2410
+ * A `tenantId` or `recipient` that identifies nobody reached a scoping
2411
+ * boundary — empty, whitespace-only, or not a string at all. Distinct from
2412
+ * {@link EMAIL_INVALID_RECIPIENT}, which is about a malformed address rather
2413
+ * than a value that cannot scope anything.
2414
+ */
2415
+ readonly INVALID_SCOPE_IDENTIFIER: "notification.invalid_scope_identifier";
2366
2416
  };
2367
2417
  /**
2368
2418
  * The literal-union type of every value in {@link NOTIFICATION_ERROR_CODES}.
@@ -2500,6 +2550,11 @@ declare const NOTIFICATION_ERROR_DEFINITIONS: {
2500
2550
  readonly status: HttpStatus.NOT_IMPLEMENTED;
2501
2551
  readonly message: "Channel not enabled in module config";
2502
2552
  };
2553
+ readonly INVALID_SCOPE_IDENTIFIER: {
2554
+ readonly code: "notification.invalid_scope_identifier";
2555
+ readonly status: HttpStatus.BAD_REQUEST;
2556
+ readonly message: "Tenant or recipient identifier does not identify anybody";
2557
+ };
2503
2558
  };
2504
2559
  /** The symbolic key of any entry in {@link NOTIFICATION_ERROR_DEFINITIONS}. */
2505
2560
  type NotificationErrorKey = keyof typeof NOTIFICATION_ERROR_DEFINITIONS;
@@ -1253,8 +1253,21 @@ declare class NotificationAuditInterceptor implements NestInterceptor {
1253
1253
  /** Narrows an unknown argument to a {@link DispatchInput} by structural shape. */
1254
1254
  private isDispatchInput;
1255
1255
  /**
1256
- * Resolves the trusted tenant id: `tenantIdResolver(request)` when configured and
1257
- * a request is available, otherwise the payload-supplied `fallback`.
1256
+ * Resolves the trusted tenant id from `tenantIdResolver(request)`.
1257
+ *
1258
+ * Falls back to the payload-supplied value only when no resolver is configured or
1259
+ * no request is available — the payload reaches the handler from the caller, so
1260
+ * that value is asserted rather than authenticated, and an entry built from it
1261
+ * attributes the event to whichever tenant the caller named. Configure a resolver
1262
+ * whenever this interceptor runs on an HTTP boundary.
1263
+ *
1264
+ * A value that identifies nobody is refused rather than recorded, on BOTH paths:
1265
+ * the resolver's answer and the payload fallback. The fallback is the default path
1266
+ * — most consumers configure no resolver — so guarding only the resolver would
1267
+ * leave the common case unchecked, which is where a blank tenant actually arrives.
1268
+ *
1269
+ * @throws Error When either the resolved or the fallback tenant id is not a
1270
+ * string, or is blank.
1258
1271
  */
1259
1272
  private resolveTenantId;
1260
1273
  /** Reads the HTTP request from the context, returning `null` outside an HTTP context. */
@@ -1974,7 +1987,7 @@ interface InMemoryStorageSize {
1974
1987
  /** Process-local `IOtpStorage` for dev/test. */
1975
1988
  declare class InMemoryOtpStorage implements IOtpStorage {
1976
1989
  readonly name = "memory";
1977
- /** OTP entries keyed by `${tenantId}::${recipient}::${purpose}`. */
1990
+ /** OTP entries keyed by `${hashTenantRecipient(tenantId, recipient)}::${purpose}`. */
1978
1991
  private readonly store;
1979
1992
  /** Cooldown expiries (epoch ms) keyed by the same composite key. */
1980
1993
  private readonly cooldowns;
@@ -2066,7 +2079,15 @@ declare class InMemoryOtpStorage implements IOtpStorage {
2066
2079
  * @returns The number of stored OTP entries and active cooldowns.
2067
2080
  */
2068
2081
  size(): InMemoryStorageSize;
2069
- /** Collapses the `(tenantId, recipient, purpose)` tuple into one map key. */
2082
+ /**
2083
+ * Collapses the `(tenantId, recipient, purpose)` tuple into one map key.
2084
+ *
2085
+ * The tenant and recipient go through {@link hashTenantRecipient}, which encodes
2086
+ * the pair unambiguously and rejects an empty component. Joining the raw values
2087
+ * around a delimiter would not: `('a::b', 'c', p)` and `('a', 'b::c', p)` produce
2088
+ * the same string. The digest is fixed-length, so appending the purpose after it
2089
+ * stays unambiguous too.
2090
+ */
2070
2091
  private key;
2071
2092
  }
2072
2093
 
@@ -2081,9 +2102,11 @@ declare class InMemoryOtpStorage implements IOtpStorage {
2081
2102
  * read → expiry/max check → increment → write sequence inside ONE Lua script
2082
2103
  * (`EVAL`), so concurrent verifications cannot interleave and overshoot
2083
2104
  * `maxAttempts`.
2084
- * 2. **PII-free keys** — every key carries `sha256(tenantId:recipient)`, never the
2085
- * plaintext email/phone, so an operator with `KEYS` access cannot enumerate
2086
- * recipients, and a cross-tenant key collision is computationally infeasible.
2105
+ * 2. **PII-free keys** — every key carries `sha256(sha256(tenantId):sha256(recipient))`,
2106
+ * never the plaintext email/phone, so an operator with `KEYS` access cannot
2107
+ * enumerate recipients. Each component is hashed before the join so the encoding
2108
+ * itself admits no ambiguity: joining the raw values would map `('a:b', 'c')` and
2109
+ * `('a', 'b:c')` onto one key, which no digest strength repairs.
2087
2110
  *
2088
2111
  * `ioredis` is an OPTIONAL peer dependency: this class forward-declares the slim
2089
2112
  * {@link RedisLike} surface it needs (including `eval`/`pttl`) instead of importing
@@ -2206,9 +2229,9 @@ declare class RedisOtpStorage implements IOtpStorage {
2206
2229
  * @param purpose - OTP purpose.
2207
2230
  */
2208
2231
  clearCooldown(tenantId: string, recipient: string, purpose: string): Promise<void>;
2209
- /** Builds the OTP entry key: `{namespace}:otp:{purpose}:{sha256(tenantId:recipient)}`. */
2232
+ /** Builds the OTP entry key: `{namespace}:otp:{purpose}:{hashTenantRecipient(...)}`. */
2210
2233
  private otpKey;
2211
- /** Builds the cooldown key: `{namespace}:otp_cd:{purpose}:{sha256(tenantId:recipient)}`. */
2234
+ /** Builds the cooldown key: `{namespace}:otp_cd:{purpose}:{hashTenantRecipient(...)}`. */
2212
2235
  private cooldownKey;
2213
2236
  }
2214
2237
 
@@ -2216,18 +2239,38 @@ declare class RedisOtpStorage implements IOtpStorage {
2216
2239
  * @fileoverview SHA-256 hashing of `(tenantId, recipient)` for storage keys.
2217
2240
  * @layer infrastructure
2218
2241
  *
2219
- * Storage keys are `sha256(`${tenantId}:${recipient}`)` for two reasons:
2242
+ * Storage keys are `sha256(sha256(tenantId):sha256(recipient))` for two reasons:
2220
2243
  * 1. Privacy — an operator with `KEYS`-level access to the store cannot enumerate
2221
2244
  * the email/phone of every recipient with a pending OTP.
2222
- * 2. Multi-tenancy — SHA-256 preimage resistance makes a cross-tenant key
2223
- * collision computationally infeasible.
2245
+ * 2. Multi-tenancy — each component is hashed to a fixed length BEFORE the two are
2246
+ * joined, so no two distinct pairs can produce the same input string.
2247
+ *
2248
+ * The second point is about the encoding, not about the digest, and no property of
2249
+ * SHA-256 substitutes for it. Joining the raw values around a delimiter makes
2250
+ * `('acme:bob', 'x')` and `('acme', 'bob:x')` produce the same input string — and
2251
+ * therefore the same key — while preimage and collision resistance hold perfectly.
2252
+ *
2253
+ * What that buys is precise, and overclaiming it would repeat the mistake it fixes:
2254
+ * distinct pairs are no longer *constructibly* mapped onto one key, because the
2255
+ * ambiguity was in the encoding and the encoding is now unique. The key itself stays
2256
+ * collision-RESISTANT rather than collision-free — an unbounded domain cannot map
2257
+ * injectively into 256 bits, and no construction changes that.
2258
+ *
2259
+ * A component that names no tenant and no recipient is refused rather than hashed:
2260
+ * empty, whitespace-only, or not a string at all. `('', r)` would put every caller
2261
+ * that omits a tenant into one shared namespace — the same isolation failure arrived
2262
+ * at from the other side.
2224
2263
  */
2225
2264
  /**
2226
2265
  * Derives a deterministic, PII-free storage key fragment from a tenant and recipient.
2227
2266
  *
2228
- * @param tenantId - Tenant isolation scope.
2229
- * @param recipient - Pre-normalized recipient identifier.
2230
- * @returns A 64-character lowercase hex SHA-256 digest. Order-sensitive.
2267
+ * @param tenantId - Tenant isolation scope. Must be a non-blank string.
2268
+ * @param recipient - Pre-normalized recipient identifier. Must be a non-blank string.
2269
+ * @returns A 64-character lowercase hex SHA-256 digest. Order-sensitive, and unique
2270
+ * per pair up to SHA-256's collision resistance — the encoding contributes no
2271
+ * ambiguity of its own, so two distinct pairs never map onto one key by
2272
+ * construction.
2273
+ * @throws Error When either component is not a string, or is empty or whitespace-only.
2231
2274
  */
2232
2275
  declare function hashTenantRecipient(tenantId: string, recipient: string): string;
2233
2276
 
@@ -2336,8 +2379,8 @@ declare function formatCooldown(remainingSeconds: number): string;
2336
2379
  * Stable error-code identifiers, keyed by their symbolic name.
2337
2380
  *
2338
2381
  * Values are namespaced under `notification.*` and never change once published —
2339
- * consumers branch on them to localize messages. The 22 entries cover the email,
2340
- * template, OTP, SMS, push, audit, and channel-config failure surfaces.
2382
+ * consumers branch on them to localize messages. The 23 entries cover the email,
2383
+ * template, OTP, SMS, push, audit, channel-config and scoping failure surfaces.
2341
2384
  */
2342
2385
  declare const NOTIFICATION_ERROR_CODES: {
2343
2386
  readonly EMAIL_PROVIDER_NOT_CONFIGURED: "notification.email_provider_not_configured";
@@ -2363,6 +2406,13 @@ declare const NOTIFICATION_ERROR_CODES: {
2363
2406
  readonly PUSH_SEND_FAILED: "notification.push_send_failed";
2364
2407
  readonly AUDIT_LOG_FAILED: "notification.audit_log_failed";
2365
2408
  readonly CHANNEL_DISABLED: "notification.channel_disabled";
2409
+ /**
2410
+ * A `tenantId` or `recipient` that identifies nobody reached a scoping
2411
+ * boundary — empty, whitespace-only, or not a string at all. Distinct from
2412
+ * {@link EMAIL_INVALID_RECIPIENT}, which is about a malformed address rather
2413
+ * than a value that cannot scope anything.
2414
+ */
2415
+ readonly INVALID_SCOPE_IDENTIFIER: "notification.invalid_scope_identifier";
2366
2416
  };
2367
2417
  /**
2368
2418
  * The literal-union type of every value in {@link NOTIFICATION_ERROR_CODES}.
@@ -2500,6 +2550,11 @@ declare const NOTIFICATION_ERROR_DEFINITIONS: {
2500
2550
  readonly status: HttpStatus.NOT_IMPLEMENTED;
2501
2551
  readonly message: "Channel not enabled in module config";
2502
2552
  };
2553
+ readonly INVALID_SCOPE_IDENTIFIER: {
2554
+ readonly code: "notification.invalid_scope_identifier";
2555
+ readonly status: HttpStatus.BAD_REQUEST;
2556
+ readonly message: "Tenant or recipient identifier does not identify anybody";
2557
+ };
2503
2558
  };
2504
2559
  /** The symbolic key of any entry in {@link NOTIFICATION_ERROR_DEFINITIONS}. */
2505
2560
  type NotificationErrorKey = keyof typeof NOTIFICATION_ERROR_DEFINITIONS;
@@ -144,7 +144,14 @@ var NOTIFICATION_ERROR_CODES = {
144
144
  PUSH_PROVIDER_NOT_CONFIGURED: "notification.push_provider_not_configured",
145
145
  PUSH_SEND_FAILED: "notification.push_send_failed",
146
146
  AUDIT_LOG_FAILED: "notification.audit_log_failed",
147
- CHANNEL_DISABLED: "notification.channel_disabled"
147
+ CHANNEL_DISABLED: "notification.channel_disabled",
148
+ /**
149
+ * A `tenantId` or `recipient` that identifies nobody reached a scoping
150
+ * boundary — empty, whitespace-only, or not a string at all. Distinct from
151
+ * {@link EMAIL_INVALID_RECIPIENT}, which is about a malformed address rather
152
+ * than a value that cannot scope anything.
153
+ */
154
+ INVALID_SCOPE_IDENTIFIER: "notification.invalid_scope_identifier"
148
155
  };
149
156
 
150
157
  // src/server/errors/notification-error-codes.ts
@@ -258,6 +265,11 @@ var NOTIFICATION_ERROR_DEFINITIONS = {
258
265
  code: NOTIFICATION_ERROR_CODES.CHANNEL_DISABLED,
259
266
  status: HttpStatus.NOT_IMPLEMENTED,
260
267
  message: "Channel not enabled in module config"
268
+ },
269
+ INVALID_SCOPE_IDENTIFIER: {
270
+ code: NOTIFICATION_ERROR_CODES.INVALID_SCOPE_IDENTIFIER,
271
+ status: HttpStatus.BAD_REQUEST,
272
+ message: "Tenant or recipient identifier does not identify anybody"
261
273
  }
262
274
  };
263
275
  var NOTIFICATION_ERROR_DEFINITION_MAP = new Map(
@@ -1833,6 +1845,26 @@ function instantiate(valueOrClass) {
1833
1845
  }
1834
1846
  return new ctor();
1835
1847
  }
1848
+
1849
+ // src/server/utils/tenant-scope.ts
1850
+ function refuse(owner, label, reason) {
1851
+ return new NotificationException(
1852
+ "INVALID_SCOPE_IDENTIFIER",
1853
+ { boundary: owner, parameter: label, reason },
1854
+ { message: `[${owner}] ${label} ${reason}` }
1855
+ );
1856
+ }
1857
+ function assertIdentifies(owner, label, value) {
1858
+ if (typeof value !== "string") {
1859
+ throw refuse(owner, label, `expected a string, received ${typeof value}`);
1860
+ }
1861
+ if (value.trim() === "") {
1862
+ throw refuse(owner, label, "empty or whitespace-only");
1863
+ }
1864
+ }
1865
+
1866
+ // src/server/interceptors/notification-audit.interceptor.ts
1867
+ var INTERCEPTOR_NAME = "NotificationAuditInterceptor";
1836
1868
  var INTERCEPTOR_PROVIDER_NAME = "__interceptor__";
1837
1869
  function toErrorMessage(error) {
1838
1870
  return error instanceof Error ? error.message : String(error);
@@ -1908,19 +1940,36 @@ var NotificationAuditInterceptor = class {
1908
1940
  return typeof candidate.payload === "object" && candidate.payload !== null;
1909
1941
  }
1910
1942
  /**
1911
- * Resolves the trusted tenant id: `tenantIdResolver(request)` when configured and
1912
- * a request is available, otherwise the payload-supplied `fallback`.
1943
+ * Resolves the trusted tenant id from `tenantIdResolver(request)`.
1944
+ *
1945
+ * Falls back to the payload-supplied value only when no resolver is configured or
1946
+ * no request is available — the payload reaches the handler from the caller, so
1947
+ * that value is asserted rather than authenticated, and an entry built from it
1948
+ * attributes the event to whichever tenant the caller named. Configure a resolver
1949
+ * whenever this interceptor runs on an HTTP boundary.
1950
+ *
1951
+ * A value that identifies nobody is refused rather than recorded, on BOTH paths:
1952
+ * the resolver's answer and the payload fallback. The fallback is the default path
1953
+ * — most consumers configure no resolver — so guarding only the resolver would
1954
+ * leave the common case unchecked, which is where a blank tenant actually arrives.
1955
+ *
1956
+ * @throws Error When either the resolved or the fallback tenant id is not a
1957
+ * string, or is blank.
1913
1958
  */
1914
1959
  async resolveTenantId(context, fallback) {
1915
1960
  const resolver = this.options.global.tenantIdResolver;
1916
1961
  if (resolver === void 0) {
1962
+ assertIdentifies(INTERCEPTOR_NAME, "the payload tenant id", fallback);
1917
1963
  return fallback;
1918
1964
  }
1919
1965
  const request = this.extractRequest(context);
1920
1966
  if (request === null) {
1967
+ assertIdentifies(INTERCEPTOR_NAME, "the payload tenant id", fallback);
1921
1968
  return fallback;
1922
1969
  }
1923
- return resolver(request);
1970
+ const resolved = await resolver(request);
1971
+ assertIdentifies(INTERCEPTOR_NAME, "the resolved tenant id", resolved);
1972
+ return resolved;
1924
1973
  }
1925
1974
  /** Reads the HTTP request from the context, returning `null` outside an HTTP context. */
1926
1975
  extractRequest(context) {
@@ -2048,7 +2097,8 @@ async function loadOptionalPeer(moduleName) {
2048
2097
  } catch (error) {
2049
2098
  if (isModuleNotFound(error, moduleName)) {
2050
2099
  throw new Error(
2051
- `\`${moduleName}\` package is not installed. Run \`pnpm add ${moduleName}\` in the consumer app.`
2100
+ `\`${moduleName}\` package is not installed. Run \`pnpm add ${moduleName}\` in the consumer app.`,
2101
+ { cause: error }
2052
2102
  );
2053
2103
  }
2054
2104
  const reason = error instanceof Error ? error.message : String(error);
@@ -2657,11 +2707,21 @@ _options2 = new WeakMap();
2657
2707
  SmtpEmailProvider = __decorateClass([
2658
2708
  Injectable()
2659
2709
  ], SmtpEmailProvider);
2710
+ function sha256(value) {
2711
+ return createHash("sha256").update(value).digest("hex");
2712
+ }
2713
+ function hashTenantRecipient(tenantId, recipient) {
2714
+ assertIdentifies("hashTenantRecipient", "tenantId", tenantId);
2715
+ assertIdentifies("hashTenantRecipient", "recipient", recipient);
2716
+ return createHash("sha256").update(`${sha256(tenantId)}:${sha256(recipient)}`).digest("hex");
2717
+ }
2718
+
2719
+ // src/server/providers/in-memory-otp.storage.ts
2660
2720
  var MS_PER_SECOND3 = 1e3;
2661
2721
  var InMemoryOtpStorage = class {
2662
2722
  constructor() {
2663
2723
  this.name = "memory";
2664
- /** OTP entries keyed by `${tenantId}::${recipient}::${purpose}`. */
2724
+ /** OTP entries keyed by `${hashTenantRecipient(tenantId, recipient)}::${purpose}`. */
2665
2725
  this.store = /* @__PURE__ */ new Map();
2666
2726
  /** Cooldown expiries (epoch ms) keyed by the same composite key. */
2667
2727
  this.cooldowns = /* @__PURE__ */ new Map();
@@ -2820,19 +2880,22 @@ var InMemoryOtpStorage = class {
2820
2880
  size() {
2821
2881
  return { otps: this.store.size, cooldowns: this.cooldowns.size };
2822
2882
  }
2823
- /** Collapses the `(tenantId, recipient, purpose)` tuple into one map key. */
2883
+ /**
2884
+ * Collapses the `(tenantId, recipient, purpose)` tuple into one map key.
2885
+ *
2886
+ * The tenant and recipient go through {@link hashTenantRecipient}, which encodes
2887
+ * the pair unambiguously and rejects an empty component. Joining the raw values
2888
+ * around a delimiter would not: `('a::b', 'c', p)` and `('a', 'b::c', p)` produce
2889
+ * the same string. The digest is fixed-length, so appending the purpose after it
2890
+ * stays unambiguous too.
2891
+ */
2824
2892
  key(tenantId, recipient, purpose) {
2825
- return `${tenantId}::${recipient}::${purpose}`;
2893
+ return `${hashTenantRecipient(tenantId, recipient)}::${purpose}`;
2826
2894
  }
2827
2895
  };
2828
2896
  InMemoryOtpStorage = __decorateClass([
2829
2897
  Injectable()
2830
2898
  ], InMemoryOtpStorage);
2831
- function hashTenantRecipient(tenantId, recipient) {
2832
- return createHash("sha256").update(`${tenantId}:${recipient}`).digest("hex");
2833
- }
2834
-
2835
- // src/server/providers/redis-otp.storage.ts
2836
2899
  var MS_PER_SECOND4 = 1e3;
2837
2900
  var _redis;
2838
2901
  var RedisOtpStorage = class {
@@ -2986,11 +3049,11 @@ var RedisOtpStorage = class {
2986
3049
  async clearCooldown(tenantId, recipient, purpose) {
2987
3050
  await __privateGet(this, _redis).del(this.cooldownKey(tenantId, recipient, purpose));
2988
3051
  }
2989
- /** Builds the OTP entry key: `{namespace}:otp:{purpose}:{sha256(tenantId:recipient)}`. */
3052
+ /** Builds the OTP entry key: `{namespace}:otp:{purpose}:{hashTenantRecipient(...)}`. */
2990
3053
  otpKey(tenantId, recipient, purpose) {
2991
3054
  return `${this.namespace}:otp:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
2992
3055
  }
2993
- /** Builds the cooldown key: `{namespace}:otp_cd:{purpose}:{sha256(tenantId:recipient)}`. */
3056
+ /** Builds the cooldown key: `{namespace}:otp_cd:{purpose}:{hashTenantRecipient(...)}`. */
2994
3057
  cooldownKey(tenantId, recipient, purpose) {
2995
3058
  return `${this.namespace}:otp_cd:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
2996
3059
  }
@@ -24,7 +24,14 @@ var NOTIFICATION_ERROR_CODES = {
24
24
  PUSH_PROVIDER_NOT_CONFIGURED: "notification.push_provider_not_configured",
25
25
  PUSH_SEND_FAILED: "notification.push_send_failed",
26
26
  AUDIT_LOG_FAILED: "notification.audit_log_failed",
27
- CHANNEL_DISABLED: "notification.channel_disabled"
27
+ CHANNEL_DISABLED: "notification.channel_disabled",
28
+ /**
29
+ * A `tenantId` or `recipient` that identifies nobody reached a scoping
30
+ * boundary — empty, whitespace-only, or not a string at all. Distinct from
31
+ * {@link EMAIL_INVALID_RECIPIENT}, which is about a malformed address rather
32
+ * than a value that cannot scope anything.
33
+ */
34
+ INVALID_SCOPE_IDENTIFIER: "notification.invalid_scope_identifier"
28
35
  };
29
36
 
30
37
  // src/shared/constants/default-ttls.ts
@@ -74,8 +74,8 @@ interface NotificationErrorResponse {
74
74
  * Stable error-code identifiers, keyed by their symbolic name.
75
75
  *
76
76
  * Values are namespaced under `notification.*` and never change once published —
77
- * consumers branch on them to localize messages. The 22 entries cover the email,
78
- * template, OTP, SMS, push, audit, and channel-config failure surfaces.
77
+ * consumers branch on them to localize messages. The 23 entries cover the email,
78
+ * template, OTP, SMS, push, audit, channel-config and scoping failure surfaces.
79
79
  */
80
80
  declare const NOTIFICATION_ERROR_CODES: {
81
81
  readonly EMAIL_PROVIDER_NOT_CONFIGURED: "notification.email_provider_not_configured";
@@ -101,6 +101,13 @@ declare const NOTIFICATION_ERROR_CODES: {
101
101
  readonly PUSH_SEND_FAILED: "notification.push_send_failed";
102
102
  readonly AUDIT_LOG_FAILED: "notification.audit_log_failed";
103
103
  readonly CHANNEL_DISABLED: "notification.channel_disabled";
104
+ /**
105
+ * A `tenantId` or `recipient` that identifies nobody reached a scoping
106
+ * boundary — empty, whitespace-only, or not a string at all. Distinct from
107
+ * {@link EMAIL_INVALID_RECIPIENT}, which is about a malformed address rather
108
+ * than a value that cannot scope anything.
109
+ */
110
+ readonly INVALID_SCOPE_IDENTIFIER: "notification.invalid_scope_identifier";
104
111
  };
105
112
  /**
106
113
  * The literal-union type of every value in {@link NOTIFICATION_ERROR_CODES}.
@@ -74,8 +74,8 @@ interface NotificationErrorResponse {
74
74
  * Stable error-code identifiers, keyed by their symbolic name.
75
75
  *
76
76
  * Values are namespaced under `notification.*` and never change once published —
77
- * consumers branch on them to localize messages. The 22 entries cover the email,
78
- * template, OTP, SMS, push, audit, and channel-config failure surfaces.
77
+ * consumers branch on them to localize messages. The 23 entries cover the email,
78
+ * template, OTP, SMS, push, audit, channel-config and scoping failure surfaces.
79
79
  */
80
80
  declare const NOTIFICATION_ERROR_CODES: {
81
81
  readonly EMAIL_PROVIDER_NOT_CONFIGURED: "notification.email_provider_not_configured";
@@ -101,6 +101,13 @@ declare const NOTIFICATION_ERROR_CODES: {
101
101
  readonly PUSH_SEND_FAILED: "notification.push_send_failed";
102
102
  readonly AUDIT_LOG_FAILED: "notification.audit_log_failed";
103
103
  readonly CHANNEL_DISABLED: "notification.channel_disabled";
104
+ /**
105
+ * A `tenantId` or `recipient` that identifies nobody reached a scoping
106
+ * boundary — empty, whitespace-only, or not a string at all. Distinct from
107
+ * {@link EMAIL_INVALID_RECIPIENT}, which is about a malformed address rather
108
+ * than a value that cannot scope anything.
109
+ */
110
+ readonly INVALID_SCOPE_IDENTIFIER: "notification.invalid_scope_identifier";
104
111
  };
105
112
  /**
106
113
  * The literal-union type of every value in {@link NOTIFICATION_ERROR_CODES}.
@@ -22,7 +22,14 @@ var NOTIFICATION_ERROR_CODES = {
22
22
  PUSH_PROVIDER_NOT_CONFIGURED: "notification.push_provider_not_configured",
23
23
  PUSH_SEND_FAILED: "notification.push_send_failed",
24
24
  AUDIT_LOG_FAILED: "notification.audit_log_failed",
25
- CHANNEL_DISABLED: "notification.channel_disabled"
25
+ CHANNEL_DISABLED: "notification.channel_disabled",
26
+ /**
27
+ * A `tenantId` or `recipient` that identifies nobody reached a scoping
28
+ * boundary — empty, whitespace-only, or not a string at all. Distinct from
29
+ * {@link EMAIL_INVALID_RECIPIENT}, which is about a malformed address rather
30
+ * than a value that cannot scope anything.
31
+ */
32
+ INVALID_SCOPE_IDENTIFIER: "notification.invalid_scope_identifier"
26
33
  };
27
34
 
28
35
  // src/shared/constants/default-ttls.ts
@@ -20,7 +20,11 @@ function makeScope() {
20
20
  recipient: `${run}_${RECIPIENT_LOCAL}`,
21
21
  absentRecipient: `${run}_${ABSENT_LOCAL}`,
22
22
  purpose: `${KEY_PREFIX}_${run}_${PURPOSE_MAIN}`,
23
- otherPurpose: `${KEY_PREFIX}_${run}_${PURPOSE_OTHER}`
23
+ otherPurpose: `${KEY_PREFIX}_${run}_${PURPOSE_OTHER}`,
24
+ // Same characters, two different (tenant, recipient) splits. A key built by
25
+ // joining the raw values around `:` maps both onto one string.
26
+ shiftedLeft: [`${KEY_PREFIX}_${run}_x:y`, "z"],
27
+ shiftedRight: [`${KEY_PREFIX}_${run}_x`, "y:z"]
24
28
  };
25
29
  }
26
30
  var DEFAULT_EXPIRY_WAIT_MS = 1500;
@@ -50,6 +54,10 @@ async function cleanUp(storage, scope) {
50
54
  await storage.delete(tenant, scope.absentRecipient, purpose);
51
55
  await storage.clearCooldown(tenant, scope.absentRecipient, purpose);
52
56
  }
57
+ for (const [tenant, recipient] of [scope.shiftedLeft, scope.shiftedRight]) {
58
+ await storage.delete(tenant, recipient, scope.purpose);
59
+ await storage.clearCooldown(tenant, recipient, scope.purpose);
60
+ }
53
61
  }
54
62
  function roundTripCase({ scope, withStorage }) {
55
63
  return {
@@ -370,6 +378,45 @@ function cooldownAtomicCase({ scope, withStorage }) {
370
378
  })
371
379
  };
372
380
  }
381
+ function keyBoundaryCase({ scope, withStorage }) {
382
+ return {
383
+ name: "keeps the tenant and recipient boundary when composing a key",
384
+ run: () => withStorage(async (storage) => {
385
+ const [leftTenant, leftRecipient] = scope.shiftedLeft;
386
+ const [rightTenant, rightRecipient] = scope.shiftedRight;
387
+ await storage.set(leftTenant, leftRecipient, scope.purpose, makeEntry(6e4));
388
+ const bled = await storage.get(rightTenant, rightRecipient, scope.purpose);
389
+ check(
390
+ bled === null,
391
+ "an entry written for one tenant was readable by another whose id and recipient differ only in where the boundary falls \u2014 the key concatenates the two fields without encoding the split, so one tenant can read and consume another OTP. Hash or length-prefix each field before joining; no digest strength repairs it"
392
+ );
393
+ })
394
+ };
395
+ }
396
+ function cooldownKeyBoundaryCase({ scope, withStorage }) {
397
+ return {
398
+ name: "keeps the tenant and recipient boundary when composing a cooldown key",
399
+ run: () => withStorage(async (storage) => {
400
+ const [leftTenant, leftRecipient] = scope.shiftedLeft;
401
+ const [rightTenant, rightRecipient] = scope.shiftedRight;
402
+ const held = await storage.tryAcquireCooldown(leftTenant, leftRecipient, scope.purpose, 60);
403
+ check(
404
+ held,
405
+ "the first cooldown could not be acquired, so this case proves nothing about boundary encoding \u2014 a case that cannot fail is decoration"
406
+ );
407
+ const other = await storage.tryAcquireCooldown(
408
+ rightTenant,
409
+ rightRecipient,
410
+ scope.purpose,
411
+ 60
412
+ );
413
+ check(
414
+ other,
415
+ "a cooldown held for one tenant blocked another whose id and recipient differ only in where the boundary falls \u2014 the cooldown key concatenates the two fields without encoding the split, so one tenant can suppress another resends. The entry key and the cooldown key are composed separately and both need this"
416
+ );
417
+ })
418
+ };
419
+ }
373
420
  var CASE_BUILDERS = [
374
421
  roundTripCase,
375
422
  absentCase,
@@ -389,7 +436,9 @@ var CASE_BUILDERS = [
389
436
  cooldownTenantScopeCase,
390
437
  cooldownRecipientScopeCase,
391
438
  cooldownPurposeScopeCase,
392
- cooldownAtomicCase
439
+ cooldownAtomicCase,
440
+ keyBoundaryCase,
441
+ cooldownKeyBoundaryCase
393
442
  ];
394
443
  function otpStorageContract(factory, options = {}) {
395
444
  const scope = makeScope();
@@ -18,7 +18,11 @@ function makeScope() {
18
18
  recipient: `${run}_${RECIPIENT_LOCAL}`,
19
19
  absentRecipient: `${run}_${ABSENT_LOCAL}`,
20
20
  purpose: `${KEY_PREFIX}_${run}_${PURPOSE_MAIN}`,
21
- otherPurpose: `${KEY_PREFIX}_${run}_${PURPOSE_OTHER}`
21
+ otherPurpose: `${KEY_PREFIX}_${run}_${PURPOSE_OTHER}`,
22
+ // Same characters, two different (tenant, recipient) splits. A key built by
23
+ // joining the raw values around `:` maps both onto one string.
24
+ shiftedLeft: [`${KEY_PREFIX}_${run}_x:y`, "z"],
25
+ shiftedRight: [`${KEY_PREFIX}_${run}_x`, "y:z"]
22
26
  };
23
27
  }
24
28
  var DEFAULT_EXPIRY_WAIT_MS = 1500;
@@ -48,6 +52,10 @@ async function cleanUp(storage, scope) {
48
52
  await storage.delete(tenant, scope.absentRecipient, purpose);
49
53
  await storage.clearCooldown(tenant, scope.absentRecipient, purpose);
50
54
  }
55
+ for (const [tenant, recipient] of [scope.shiftedLeft, scope.shiftedRight]) {
56
+ await storage.delete(tenant, recipient, scope.purpose);
57
+ await storage.clearCooldown(tenant, recipient, scope.purpose);
58
+ }
51
59
  }
52
60
  function roundTripCase({ scope, withStorage }) {
53
61
  return {
@@ -368,6 +376,45 @@ function cooldownAtomicCase({ scope, withStorage }) {
368
376
  })
369
377
  };
370
378
  }
379
+ function keyBoundaryCase({ scope, withStorage }) {
380
+ return {
381
+ name: "keeps the tenant and recipient boundary when composing a key",
382
+ run: () => withStorage(async (storage) => {
383
+ const [leftTenant, leftRecipient] = scope.shiftedLeft;
384
+ const [rightTenant, rightRecipient] = scope.shiftedRight;
385
+ await storage.set(leftTenant, leftRecipient, scope.purpose, makeEntry(6e4));
386
+ const bled = await storage.get(rightTenant, rightRecipient, scope.purpose);
387
+ check(
388
+ bled === null,
389
+ "an entry written for one tenant was readable by another whose id and recipient differ only in where the boundary falls \u2014 the key concatenates the two fields without encoding the split, so one tenant can read and consume another OTP. Hash or length-prefix each field before joining; no digest strength repairs it"
390
+ );
391
+ })
392
+ };
393
+ }
394
+ function cooldownKeyBoundaryCase({ scope, withStorage }) {
395
+ return {
396
+ name: "keeps the tenant and recipient boundary when composing a cooldown key",
397
+ run: () => withStorage(async (storage) => {
398
+ const [leftTenant, leftRecipient] = scope.shiftedLeft;
399
+ const [rightTenant, rightRecipient] = scope.shiftedRight;
400
+ const held = await storage.tryAcquireCooldown(leftTenant, leftRecipient, scope.purpose, 60);
401
+ check(
402
+ held,
403
+ "the first cooldown could not be acquired, so this case proves nothing about boundary encoding \u2014 a case that cannot fail is decoration"
404
+ );
405
+ const other = await storage.tryAcquireCooldown(
406
+ rightTenant,
407
+ rightRecipient,
408
+ scope.purpose,
409
+ 60
410
+ );
411
+ check(
412
+ other,
413
+ "a cooldown held for one tenant blocked another whose id and recipient differ only in where the boundary falls \u2014 the cooldown key concatenates the two fields without encoding the split, so one tenant can suppress another resends. The entry key and the cooldown key are composed separately and both need this"
414
+ );
415
+ })
416
+ };
417
+ }
371
418
  var CASE_BUILDERS = [
372
419
  roundTripCase,
373
420
  absentCase,
@@ -387,7 +434,9 @@ var CASE_BUILDERS = [
387
434
  cooldownTenantScopeCase,
388
435
  cooldownRecipientScopeCase,
389
436
  cooldownPurposeScopeCase,
390
- cooldownAtomicCase
437
+ cooldownAtomicCase,
438
+ keyBoundaryCase,
439
+ cooldownKeyBoundaryCase
391
440
  ];
392
441
  function otpStorageContract(factory, options = {}) {
393
442
  const scope = makeScope();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-notification",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "Multi-channel notification library for NestJS — email, OTP, SMS, push — with pluggable providers and storage, multi-tenant by design, zero runtime dependencies.",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",
@@ -86,8 +86,8 @@
86
86
  "check:no-prisma": "grep -rq '@prisma/client' src; s=$?; [ $s -eq 1 ] && exit 0; [ $s -eq 0 ] && { echo check:no-prisma: found @prisma/client import in src/; exit 1; }; echo check:no-prisma: grep failed with exit $s; exit $s",
87
87
  "check:published": "node scripts/check-published-surface.mjs",
88
88
  "clean": "rm -rf dist coverage",
89
- "lint": "eslint src scripts test",
90
- "lint:fix": "eslint src scripts test --fix",
89
+ "lint": "eslint src scripts test --max-warnings 0",
90
+ "lint:fix": "eslint src scripts test --fix --max-warnings 0",
91
91
  "mutation": "stryker run",
92
92
  "mutation:full": "node -e \"require('node:fs').rmSync('reports/stryker-incremental.json',{force:true,recursive:true})\" && stryker run",
93
93
  "mutation:dry-run": "stryker run --dryRunOnly",
@@ -190,7 +190,7 @@
190
190
  "@arethetypeswrong/cli": "^0.18.5",
191
191
  "@commitlint/cli": "^21.2.1",
192
192
  "@commitlint/config-conventional": "^21.2.0",
193
- "@eslint/js": "^9.39.4",
193
+ "@eslint/js": "^10.0.1",
194
194
  "@nestjs/common": "^11.1.20",
195
195
  "@nestjs/core": "^11.1.20",
196
196
  "@nestjs/testing": "^11.1.20",
@@ -204,10 +204,10 @@
204
204
  "@types/react": "^19",
205
205
  "@typescript-eslint/eslint-plugin": "^8.59.3",
206
206
  "@typescript-eslint/parser": "^8.59.3",
207
- "eslint": "^9.39.4",
207
+ "eslint": "^10.9.1",
208
208
  "eslint-config-prettier": "^10.1.8",
209
209
  "eslint-import-resolver-typescript": "^4.4.4",
210
- "eslint-plugin-import": "^2.32.0",
210
+ "eslint-plugin-import-x": "^4.17.1",
211
211
  "eslint-plugin-prettier": "^5.5.5",
212
212
  "eslint-plugin-security": "^4.0.0",
213
213
  "globals": "^17.6.0",