@bymax-one/nest-notification 1.4.0 → 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,90 @@ 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
+
8
92
  ## [1.4.0] - 2026-09-04
9
93
 
10
94
  > ### ⚠️ Read before deploying — the version number does not warn you
@@ -688,7 +772,8 @@ rejected at startup rather than failing on the first send.
688
772
 
689
773
  [1.0.4]: https://github.com/bymaxone/nest-notification/compare/v1.0.3...v1.0.4
690
774
  [1.0.3]: https://github.com/bymaxone/nest-notification/compare/v1.0.2...v1.0.3
691
- [Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.4.0...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
692
777
  [1.4.0]: https://github.com/bymaxone/nest-notification/compare/v1.3.1...v1.4.0
693
778
  [1.3.1]: https://github.com/bymaxone/nest-notification/compare/v1.3.0...v1.3.1
694
779
  [1.3.0]: https://github.com/bymaxone/nest-notification/compare/v1.2.2...v1.3.0
package/README.md CHANGED
@@ -35,7 +35,7 @@
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
 
@@ -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
@@ -78,7 +78,7 @@ pnpm add @bymax-one/nest-notification
78
78
 
79
79
  ### 🧩 Developer Experience
80
80
 
81
- - ✅ **Three subpaths** — server, zero-dependency shared types, and React hooks
81
+ - ✅ **Subpaths** — server, zero-dependency shared types, React hooks, and a `testing` storage contract
82
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`
@@ -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'
@@ -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
 
@@ -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
@@ -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 };
@@ -1198,6 +1198,23 @@ function formatCooldown(remainingSeconds) {
1198
1198
  }
1199
1199
  return parts.join(" ");
1200
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
+ }
1201
1218
  function safeCompare(expected, actual) {
1202
1219
  const expectedBytes = Buffer.from(expected, "utf8");
1203
1220
  const actualBytes = Buffer.from(actual, "utf8");
@@ -1243,6 +1260,7 @@ exports.OtpService = class OtpService {
1243
1260
  */
1244
1261
  async generate(input) {
1245
1262
  const otp = this.requireOtpOptions();
1263
+ this.assertScope(input);
1246
1264
  const cfg = otp.resolveForPurpose(input.purpose);
1247
1265
  await this.acquireCooldownOrThrow(input, cfg.resendCooldownSeconds);
1248
1266
  const code = generateOtpCode(cfg.length, cfg.codeType);
@@ -1260,6 +1278,7 @@ exports.OtpService = class OtpService {
1260
1278
  */
1261
1279
  async verify(input) {
1262
1280
  const otp = this.requireOtpOptions();
1281
+ this.assertScope(input);
1263
1282
  const result = await this.storage.consumeAttempt(input.tenantId, input.recipient, input.purpose);
1264
1283
  if (result.status === "not_found") {
1265
1284
  await this.audit(this.otpAuditEntry("failed", input, { reason: "not_found" }));
@@ -1291,6 +1310,7 @@ exports.OtpService = class OtpService {
1291
1310
  */
1292
1311
  async consume(input) {
1293
1312
  this.requireOtpOptions();
1313
+ this.assertScope(input);
1294
1314
  await this.storage.delete(input.tenantId, input.recipient, input.purpose);
1295
1315
  await this.storage.clearCooldown(input.tenantId, input.recipient, input.purpose);
1296
1316
  }
@@ -1310,6 +1330,7 @@ exports.OtpService = class OtpService {
1310
1330
  * @returns Existence, expiry, attempt counters, validation flag, and cooldown.
1311
1331
  */
1312
1332
  async getStatus(input) {
1333
+ this.assertScope(input);
1313
1334
  const [entry, cooldownSeconds] = await Promise.all([
1314
1335
  this.storage.get(input.tenantId, input.recipient, input.purpose),
1315
1336
  this.storage.getCooldown(input.tenantId, input.recipient, input.purpose)
@@ -1431,6 +1452,19 @@ exports.OtpService = class OtpService {
1431
1452
  }
1432
1453
  await this.audit(this.otpAuditEntry("verified", input, void 0));
1433
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
+ }
1434
1468
  /** Returns the resolved OTP options or throws `OTP_STORAGE_NOT_CONFIGURED`. */
1435
1469
  requireOtpOptions() {
1436
1470
  if (!this.options.otp) {
@@ -1847,25 +1881,6 @@ function instantiate(valueOrClass) {
1847
1881
  }
1848
1882
  return new ctor();
1849
1883
  }
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
1884
  var INTERCEPTOR_NAME = "NotificationAuditInterceptor";
1870
1885
  var INTERCEPTOR_PROVIDER_NAME = "__interceptor__";
1871
1886
  function toErrorMessage(error) {
@@ -483,6 +483,10 @@ interface GlobalOptions {
483
483
  * Resolves the tenant id from the request. When provided, the module prefers
484
484
  * this source over a tenant id passed in the body/argument — preventing tenant
485
485
  * spoofing.
486
+ *
487
+ * What it returns must identify a tenant: a value that is not a string, is empty or
488
+ * is whitespace-only is refused by the audit interceptor rather than recorded (see
489
+ * `audit.swallowErrors` for what the caller then sees).
486
490
  */
487
491
  tenantIdResolver?: (req: NotificationRequest) => string | Promise<string>;
488
492
  }
@@ -1074,6 +1078,16 @@ declare class OtpService {
1074
1078
  private buildOtpEmail;
1075
1079
  /** Finalizes a correct verification: consume-and-clear, or mark `validated`. */
1076
1080
  private finalizeVerifySuccess;
1081
+ /**
1082
+ * Refuses a tenant id or recipient that identifies nobody, before any storage call.
1083
+ *
1084
+ * The reference storage already refuses these through `hashTenantRecipient`, but a
1085
+ * consumer-supplied {@link IOtpStorage} is not required to, and a blank scope would
1086
+ * then be shared by every caller that sent one.
1087
+ *
1088
+ * @throws NotificationException `INVALID_SCOPE_IDENTIFIER` when either is blank.
1089
+ */
1090
+ private assertScope;
1077
1091
  /** Returns the resolved OTP options or throws `OTP_STORAGE_NOT_CONFIGURED`. */
1078
1092
  private requireOtpOptions;
1079
1093
  /** Builds an OTP audit entry with the recipient masked and never the code. */
@@ -1204,6 +1218,10 @@ declare class NotificationService {
1204
1218
  * tenant id is taken from `global.tenantIdResolver(request)` when configured,
1205
1219
  * which OVERRIDES any `tenantId` carried in the dispatch payload — closing the
1206
1220
  * tenant-spoofing vector where a caller forges another tenant's id in the body.
1221
+ * A tenant id that is not a string, is empty or is whitespace-only is refused on every
1222
+ * path that produces it (the resolver, the payload with no resolver, the payload when
1223
+ * there is no HTTP request) instead of being recorded; a dispatch-shaped argument whose
1224
+ * payload `tenantId` is not a string is not recognised as a dispatch and is skipped.
1207
1225
  *
1208
1226
  * The entry NEVER carries the dispatched payload (an OTP `verify` payload holds a
1209
1227
  * guessed code) — only the channel, the masked recipient, the purpose/template,
@@ -2687,4 +2705,5 @@ declare const DEFAULT_TTLS: {
2687
2705
  readonly OTP_GENERIC_SECONDS: 600;
2688
2706
  };
2689
2707
 
2690
- export { type AuditOptions, BYMAX_NOTIFICATION_EMAIL_PROVIDER, BYMAX_NOTIFICATION_LOG_REPOSITORY, BYMAX_NOTIFICATION_OPTIONS, BYMAX_NOTIFICATION_OTP_STORAGE, BYMAX_NOTIFICATION_PUSH_PROVIDER, BYMAX_NOTIFICATION_SMS_PROVIDER, BYMAX_NOTIFICATION_TEMPLATE_RENDERER, BymaxNotificationModule, type BymaxNotificationModuleAsyncOptions, type BymaxNotificationModuleOptions, type BymaxNotificationModuleOptionsFactory, CANONICAL_EMAIL_TEMPLATES, type CanonicalEmailTemplate, type CanonicalNotificationPurpose, type ConsumeAttemptResult, DEFAULT_TTLS, DefaultTemplateRenderer, type DefaultTemplateRendererOptions, type DispatchInput, type DispatchResult, type EmailAttachment, type EmailChannelOptions, type EmailDispatchPayload, type EmailSendInput, type EmailSendOptions, type EmailSendResult, type EmailSendTemplateInput, EmailService, type GlobalOptions, type IEmailProvider, type IEmailTemplateRenderer, type INotificationLogRepository, type IOtpStorage, type IPushProvider, type ISmsProvider, InMemoryOtpStorage, type InMemoryStorageSize, type MissingVariableMode, NOTIFICATION_ERROR_CODES, NOTIFICATION_ERROR_DEFINITIONS, NOTIFICATION_PURPOSES, NoOpEmailProvider, NoOpNotificationLogRepository, NotificationAuditInterceptor, type NotificationChannel, type NotificationErrorCode, type NotificationErrorDefinition, type NotificationErrorKey, type NotificationErrorResponse, NotificationException, type NotificationExceptionOptions, type NotificationLogEntry, type NotificationLogVerb, type NotificationRequest, NotificationService, type OtpChannelOptions, type OtpConsumeInput, type OtpDispatchPayload, type OtpEntry, type OtpGenerateInput, type OtpGenerateResult, type OtpPurpose, type OtpPurposeConfig, OtpService, type OtpStatusInput, type OtpStatusResult, type OtpVerifyInput, type OtpVerifyResult, type PushChannelOptions, type PushSendOptions, type PushSendResult, type RedisLike, RedisOtpStorage, type RedisOtpStorageOptions, type RenderedEmail, ResendEmailProvider, type ResendEmailProviderOptions, type ResolvedAuditOptions, type ResolvedEmailOptions, type ResolvedGlobalOptions, type ResolvedNotificationOptions, type ResolvedOtpOptions, type SmsChannelOptions, type SmsSendOptions, type SmsSendResult, type SmtpCredentials, SmtpEmailProvider, type SmtpEmailProviderOptions, type SmtpTlsOptions, type TemplateDefinition, cooldownExpiresAt, formatCooldown, generateOtpCode, hashTenantRecipient, safeCompare, toRetryAfterHeader };
2708
+ export { BYMAX_NOTIFICATION_EMAIL_PROVIDER, BYMAX_NOTIFICATION_LOG_REPOSITORY, BYMAX_NOTIFICATION_OPTIONS, BYMAX_NOTIFICATION_OTP_STORAGE, BYMAX_NOTIFICATION_PUSH_PROVIDER, BYMAX_NOTIFICATION_SMS_PROVIDER, BYMAX_NOTIFICATION_TEMPLATE_RENDERER, BymaxNotificationModule, CANONICAL_EMAIL_TEMPLATES, DEFAULT_TTLS, DefaultTemplateRenderer, EmailService, InMemoryOtpStorage, NOTIFICATION_ERROR_CODES, NOTIFICATION_ERROR_DEFINITIONS, NOTIFICATION_PURPOSES, NoOpEmailProvider, NoOpNotificationLogRepository, NotificationAuditInterceptor, NotificationException, NotificationService, OtpService, RedisOtpStorage, ResendEmailProvider, SmtpEmailProvider, cooldownExpiresAt, formatCooldown, generateOtpCode, hashTenantRecipient, safeCompare, toRetryAfterHeader };
2709
+ export type { AuditOptions, BymaxNotificationModuleAsyncOptions, BymaxNotificationModuleOptions, BymaxNotificationModuleOptionsFactory, CanonicalEmailTemplate, CanonicalNotificationPurpose, ConsumeAttemptResult, DefaultTemplateRendererOptions, DispatchInput, DispatchResult, EmailAttachment, EmailChannelOptions, EmailDispatchPayload, EmailSendInput, EmailSendOptions, EmailSendResult, EmailSendTemplateInput, GlobalOptions, IEmailProvider, IEmailTemplateRenderer, INotificationLogRepository, IOtpStorage, IPushProvider, ISmsProvider, InMemoryStorageSize, MissingVariableMode, NotificationChannel, NotificationErrorCode, NotificationErrorDefinition, NotificationErrorKey, NotificationErrorResponse, NotificationExceptionOptions, NotificationLogEntry, NotificationLogVerb, NotificationRequest, OtpChannelOptions, OtpConsumeInput, OtpDispatchPayload, OtpEntry, OtpGenerateInput, OtpGenerateResult, OtpPurpose, OtpPurposeConfig, OtpStatusInput, OtpStatusResult, OtpVerifyInput, OtpVerifyResult, PushChannelOptions, PushSendOptions, PushSendResult, RedisLike, RedisOtpStorageOptions, RenderedEmail, ResendEmailProviderOptions, ResolvedAuditOptions, ResolvedEmailOptions, ResolvedGlobalOptions, ResolvedNotificationOptions, ResolvedOtpOptions, SmsChannelOptions, SmsSendOptions, SmsSendResult, SmtpCredentials, SmtpEmailProviderOptions, SmtpTlsOptions, TemplateDefinition };
@@ -483,6 +483,10 @@ interface GlobalOptions {
483
483
  * Resolves the tenant id from the request. When provided, the module prefers
484
484
  * this source over a tenant id passed in the body/argument — preventing tenant
485
485
  * spoofing.
486
+ *
487
+ * What it returns must identify a tenant: a value that is not a string, is empty or
488
+ * is whitespace-only is refused by the audit interceptor rather than recorded (see
489
+ * `audit.swallowErrors` for what the caller then sees).
486
490
  */
487
491
  tenantIdResolver?: (req: NotificationRequest) => string | Promise<string>;
488
492
  }
@@ -1074,6 +1078,16 @@ declare class OtpService {
1074
1078
  private buildOtpEmail;
1075
1079
  /** Finalizes a correct verification: consume-and-clear, or mark `validated`. */
1076
1080
  private finalizeVerifySuccess;
1081
+ /**
1082
+ * Refuses a tenant id or recipient that identifies nobody, before any storage call.
1083
+ *
1084
+ * The reference storage already refuses these through `hashTenantRecipient`, but a
1085
+ * consumer-supplied {@link IOtpStorage} is not required to, and a blank scope would
1086
+ * then be shared by every caller that sent one.
1087
+ *
1088
+ * @throws NotificationException `INVALID_SCOPE_IDENTIFIER` when either is blank.
1089
+ */
1090
+ private assertScope;
1077
1091
  /** Returns the resolved OTP options or throws `OTP_STORAGE_NOT_CONFIGURED`. */
1078
1092
  private requireOtpOptions;
1079
1093
  /** Builds an OTP audit entry with the recipient masked and never the code. */
@@ -1204,6 +1218,10 @@ declare class NotificationService {
1204
1218
  * tenant id is taken from `global.tenantIdResolver(request)` when configured,
1205
1219
  * which OVERRIDES any `tenantId` carried in the dispatch payload — closing the
1206
1220
  * tenant-spoofing vector where a caller forges another tenant's id in the body.
1221
+ * A tenant id that is not a string, is empty or is whitespace-only is refused on every
1222
+ * path that produces it (the resolver, the payload with no resolver, the payload when
1223
+ * there is no HTTP request) instead of being recorded; a dispatch-shaped argument whose
1224
+ * payload `tenantId` is not a string is not recognised as a dispatch and is skipped.
1207
1225
  *
1208
1226
  * The entry NEVER carries the dispatched payload (an OTP `verify` payload holds a
1209
1227
  * guessed code) — only the channel, the masked recipient, the purpose/template,
@@ -2687,4 +2705,5 @@ declare const DEFAULT_TTLS: {
2687
2705
  readonly OTP_GENERIC_SECONDS: 600;
2688
2706
  };
2689
2707
 
2690
- export { type AuditOptions, BYMAX_NOTIFICATION_EMAIL_PROVIDER, BYMAX_NOTIFICATION_LOG_REPOSITORY, BYMAX_NOTIFICATION_OPTIONS, BYMAX_NOTIFICATION_OTP_STORAGE, BYMAX_NOTIFICATION_PUSH_PROVIDER, BYMAX_NOTIFICATION_SMS_PROVIDER, BYMAX_NOTIFICATION_TEMPLATE_RENDERER, BymaxNotificationModule, type BymaxNotificationModuleAsyncOptions, type BymaxNotificationModuleOptions, type BymaxNotificationModuleOptionsFactory, CANONICAL_EMAIL_TEMPLATES, type CanonicalEmailTemplate, type CanonicalNotificationPurpose, type ConsumeAttemptResult, DEFAULT_TTLS, DefaultTemplateRenderer, type DefaultTemplateRendererOptions, type DispatchInput, type DispatchResult, type EmailAttachment, type EmailChannelOptions, type EmailDispatchPayload, type EmailSendInput, type EmailSendOptions, type EmailSendResult, type EmailSendTemplateInput, EmailService, type GlobalOptions, type IEmailProvider, type IEmailTemplateRenderer, type INotificationLogRepository, type IOtpStorage, type IPushProvider, type ISmsProvider, InMemoryOtpStorage, type InMemoryStorageSize, type MissingVariableMode, NOTIFICATION_ERROR_CODES, NOTIFICATION_ERROR_DEFINITIONS, NOTIFICATION_PURPOSES, NoOpEmailProvider, NoOpNotificationLogRepository, NotificationAuditInterceptor, type NotificationChannel, type NotificationErrorCode, type NotificationErrorDefinition, type NotificationErrorKey, type NotificationErrorResponse, NotificationException, type NotificationExceptionOptions, type NotificationLogEntry, type NotificationLogVerb, type NotificationRequest, NotificationService, type OtpChannelOptions, type OtpConsumeInput, type OtpDispatchPayload, type OtpEntry, type OtpGenerateInput, type OtpGenerateResult, type OtpPurpose, type OtpPurposeConfig, OtpService, type OtpStatusInput, type OtpStatusResult, type OtpVerifyInput, type OtpVerifyResult, type PushChannelOptions, type PushSendOptions, type PushSendResult, type RedisLike, RedisOtpStorage, type RedisOtpStorageOptions, type RenderedEmail, ResendEmailProvider, type ResendEmailProviderOptions, type ResolvedAuditOptions, type ResolvedEmailOptions, type ResolvedGlobalOptions, type ResolvedNotificationOptions, type ResolvedOtpOptions, type SmsChannelOptions, type SmsSendOptions, type SmsSendResult, type SmtpCredentials, SmtpEmailProvider, type SmtpEmailProviderOptions, type SmtpTlsOptions, type TemplateDefinition, cooldownExpiresAt, formatCooldown, generateOtpCode, hashTenantRecipient, safeCompare, toRetryAfterHeader };
2708
+ export { BYMAX_NOTIFICATION_EMAIL_PROVIDER, BYMAX_NOTIFICATION_LOG_REPOSITORY, BYMAX_NOTIFICATION_OPTIONS, BYMAX_NOTIFICATION_OTP_STORAGE, BYMAX_NOTIFICATION_PUSH_PROVIDER, BYMAX_NOTIFICATION_SMS_PROVIDER, BYMAX_NOTIFICATION_TEMPLATE_RENDERER, BymaxNotificationModule, CANONICAL_EMAIL_TEMPLATES, DEFAULT_TTLS, DefaultTemplateRenderer, EmailService, InMemoryOtpStorage, NOTIFICATION_ERROR_CODES, NOTIFICATION_ERROR_DEFINITIONS, NOTIFICATION_PURPOSES, NoOpEmailProvider, NoOpNotificationLogRepository, NotificationAuditInterceptor, NotificationException, NotificationService, OtpService, RedisOtpStorage, ResendEmailProvider, SmtpEmailProvider, cooldownExpiresAt, formatCooldown, generateOtpCode, hashTenantRecipient, safeCompare, toRetryAfterHeader };
2709
+ export type { AuditOptions, BymaxNotificationModuleAsyncOptions, BymaxNotificationModuleOptions, BymaxNotificationModuleOptionsFactory, CanonicalEmailTemplate, CanonicalNotificationPurpose, ConsumeAttemptResult, DefaultTemplateRendererOptions, DispatchInput, DispatchResult, EmailAttachment, EmailChannelOptions, EmailDispatchPayload, EmailSendInput, EmailSendOptions, EmailSendResult, EmailSendTemplateInput, GlobalOptions, IEmailProvider, IEmailTemplateRenderer, INotificationLogRepository, IOtpStorage, IPushProvider, ISmsProvider, InMemoryStorageSize, MissingVariableMode, NotificationChannel, NotificationErrorCode, NotificationErrorDefinition, NotificationErrorKey, NotificationErrorResponse, NotificationExceptionOptions, NotificationLogEntry, NotificationLogVerb, NotificationRequest, OtpChannelOptions, OtpConsumeInput, OtpDispatchPayload, OtpEntry, OtpGenerateInput, OtpGenerateResult, OtpPurpose, OtpPurposeConfig, OtpStatusInput, OtpStatusResult, OtpVerifyInput, OtpVerifyResult, PushChannelOptions, PushSendOptions, PushSendResult, RedisLike, RedisOtpStorageOptions, RenderedEmail, ResendEmailProviderOptions, ResolvedAuditOptions, ResolvedEmailOptions, ResolvedGlobalOptions, ResolvedNotificationOptions, ResolvedOtpOptions, SmsChannelOptions, SmsSendOptions, SmsSendResult, SmtpCredentials, SmtpEmailProviderOptions, SmtpTlsOptions, TemplateDefinition };
@@ -1196,6 +1196,23 @@ function formatCooldown(remainingSeconds) {
1196
1196
  }
1197
1197
  return parts.join(" ");
1198
1198
  }
1199
+
1200
+ // src/server/utils/tenant-scope.ts
1201
+ function refuse(owner, label, reason) {
1202
+ return new NotificationException(
1203
+ "INVALID_SCOPE_IDENTIFIER",
1204
+ { boundary: owner, parameter: label, reason },
1205
+ { message: `[${owner}] ${label} ${reason}` }
1206
+ );
1207
+ }
1208
+ function assertIdentifies(owner, label, value) {
1209
+ if (typeof value !== "string") {
1210
+ throw refuse(owner, label, `expected a string, received ${typeof value}`);
1211
+ }
1212
+ if (value.trim() === "") {
1213
+ throw refuse(owner, label, "empty or whitespace-only");
1214
+ }
1215
+ }
1199
1216
  function safeCompare(expected, actual) {
1200
1217
  const expectedBytes = Buffer.from(expected, "utf8");
1201
1218
  const actualBytes = Buffer.from(actual, "utf8");
@@ -1241,6 +1258,7 @@ var OtpService = class {
1241
1258
  */
1242
1259
  async generate(input) {
1243
1260
  const otp = this.requireOtpOptions();
1261
+ this.assertScope(input);
1244
1262
  const cfg = otp.resolveForPurpose(input.purpose);
1245
1263
  await this.acquireCooldownOrThrow(input, cfg.resendCooldownSeconds);
1246
1264
  const code = generateOtpCode(cfg.length, cfg.codeType);
@@ -1258,6 +1276,7 @@ var OtpService = class {
1258
1276
  */
1259
1277
  async verify(input) {
1260
1278
  const otp = this.requireOtpOptions();
1279
+ this.assertScope(input);
1261
1280
  const result = await this.storage.consumeAttempt(input.tenantId, input.recipient, input.purpose);
1262
1281
  if (result.status === "not_found") {
1263
1282
  await this.audit(this.otpAuditEntry("failed", input, { reason: "not_found" }));
@@ -1289,6 +1308,7 @@ var OtpService = class {
1289
1308
  */
1290
1309
  async consume(input) {
1291
1310
  this.requireOtpOptions();
1311
+ this.assertScope(input);
1292
1312
  await this.storage.delete(input.tenantId, input.recipient, input.purpose);
1293
1313
  await this.storage.clearCooldown(input.tenantId, input.recipient, input.purpose);
1294
1314
  }
@@ -1308,6 +1328,7 @@ var OtpService = class {
1308
1328
  * @returns Existence, expiry, attempt counters, validation flag, and cooldown.
1309
1329
  */
1310
1330
  async getStatus(input) {
1331
+ this.assertScope(input);
1311
1332
  const [entry, cooldownSeconds] = await Promise.all([
1312
1333
  this.storage.get(input.tenantId, input.recipient, input.purpose),
1313
1334
  this.storage.getCooldown(input.tenantId, input.recipient, input.purpose)
@@ -1429,6 +1450,19 @@ var OtpService = class {
1429
1450
  }
1430
1451
  await this.audit(this.otpAuditEntry("verified", input, void 0));
1431
1452
  }
1453
+ /**
1454
+ * Refuses a tenant id or recipient that identifies nobody, before any storage call.
1455
+ *
1456
+ * The reference storage already refuses these through `hashTenantRecipient`, but a
1457
+ * consumer-supplied {@link IOtpStorage} is not required to, and a blank scope would
1458
+ * then be shared by every caller that sent one.
1459
+ *
1460
+ * @throws NotificationException `INVALID_SCOPE_IDENTIFIER` when either is blank.
1461
+ */
1462
+ assertScope(ref) {
1463
+ assertIdentifies("OtpService", "tenantId", ref.tenantId);
1464
+ assertIdentifies("OtpService", "recipient", ref.recipient);
1465
+ }
1432
1466
  /** Returns the resolved OTP options or throws `OTP_STORAGE_NOT_CONFIGURED`. */
1433
1467
  requireOtpOptions() {
1434
1468
  if (!this.options.otp) {
@@ -1845,25 +1879,6 @@ function instantiate(valueOrClass) {
1845
1879
  }
1846
1880
  return new ctor();
1847
1881
  }
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
1882
  var INTERCEPTOR_NAME = "NotificationAuditInterceptor";
1868
1883
  var INTERCEPTOR_PROVIDER_NAME = "__interceptor__";
1869
1884
  function toErrorMessage(error) {
@@ -142,4 +142,5 @@ declare const DEFAULT_TTLS: {
142
142
  readonly OTP_GENERIC_SECONDS: 600;
143
143
  };
144
144
 
145
- export { DEFAULT_TTLS, NOTIFICATION_ERROR_CODES, type NotificationChannel, type NotificationErrorCode, type NotificationErrorResponse, type OtpPurpose };
145
+ export { DEFAULT_TTLS, NOTIFICATION_ERROR_CODES };
146
+ export type { NotificationChannel, NotificationErrorCode, NotificationErrorResponse, OtpPurpose };
@@ -142,4 +142,5 @@ declare const DEFAULT_TTLS: {
142
142
  readonly OTP_GENERIC_SECONDS: 600;
143
143
  };
144
144
 
145
- export { DEFAULT_TTLS, NOTIFICATION_ERROR_CODES, type NotificationChannel, type NotificationErrorCode, type NotificationErrorResponse, type OtpPurpose };
145
+ export { DEFAULT_TTLS, NOTIFICATION_ERROR_CODES };
146
+ export type { NotificationChannel, NotificationErrorCode, NotificationErrorResponse, OtpPurpose };
@@ -22,9 +22,12 @@ function makeScope() {
22
22
  purpose: `${KEY_PREFIX}_${run}_${PURPOSE_MAIN}`,
23
23
  otherPurpose: `${KEY_PREFIX}_${run}_${PURPOSE_OTHER}`,
24
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"]
25
+ // joining the raw values around `:` maps both onto one string, and so does one
26
+ // built around `::`, which the single-colon pair alone does not expose.
27
+ boundaryShifts: [
28
+ { left: [`${KEY_PREFIX}_${run}_x:y`, "z"], right: [`${KEY_PREFIX}_${run}_x`, "y:z"] },
29
+ { left: [`${KEY_PREFIX}_${run}_x::y`, "z"], right: [`${KEY_PREFIX}_${run}_x`, "y::z"] }
30
+ ]
28
31
  };
29
32
  }
30
33
  var DEFAULT_EXPIRY_WAIT_MS = 1500;
@@ -54,7 +57,7 @@ async function cleanUp(storage, scope) {
54
57
  await storage.delete(tenant, scope.absentRecipient, purpose);
55
58
  await storage.clearCooldown(tenant, scope.absentRecipient, purpose);
56
59
  }
57
- for (const [tenant, recipient] of [scope.shiftedLeft, scope.shiftedRight]) {
60
+ for (const [tenant, recipient] of scope.boundaryShifts.flatMap((s) => [s.left, s.right])) {
58
61
  await storage.delete(tenant, recipient, scope.purpose);
59
62
  await storage.clearCooldown(tenant, recipient, scope.purpose);
60
63
  }
@@ -382,14 +385,14 @@ function keyBoundaryCase({ scope, withStorage }) {
382
385
  return {
383
386
  name: "keeps the tenant and recipient boundary when composing a key",
384
387
  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
- );
388
+ for (const { left, right } of scope.boundaryShifts) {
389
+ await storage.set(left[0], left[1], scope.purpose, makeEntry(6e4));
390
+ const bled = await storage.get(right[0], right[1], scope.purpose);
391
+ check(
392
+ bled === null,
393
+ "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"
394
+ );
395
+ }
393
396
  })
394
397
  };
395
398
  }
@@ -397,23 +400,18 @@ function cooldownKeyBoundaryCase({ scope, withStorage }) {
397
400
  return {
398
401
  name: "keeps the tenant and recipient boundary when composing a cooldown key",
399
402
  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
- );
403
+ for (const { left, right } of scope.boundaryShifts) {
404
+ const held = await storage.tryAcquireCooldown(left[0], left[1], scope.purpose, 60);
405
+ check(
406
+ held,
407
+ "the first cooldown could not be acquired, so this case proves nothing about boundary encoding \u2014 a case that cannot fail is decoration"
408
+ );
409
+ const other = await storage.tryAcquireCooldown(right[0], right[1], scope.purpose, 60);
410
+ check(
411
+ other,
412
+ "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"
413
+ );
414
+ }
417
415
  })
418
416
  };
419
417
  }
@@ -171,4 +171,5 @@ interface OtpStorageContractOptions {
171
171
  */
172
172
  declare function otpStorageContract(factory: OtpStorageFactory, options?: OtpStorageContractOptions): OtpStorageContractCase[];
173
173
 
174
- export { type OtpStorageContractCase, type OtpStorageContractOptions, type OtpStorageFactory, otpStorageContract };
174
+ export { otpStorageContract };
175
+ export type { OtpStorageContractCase, OtpStorageContractOptions, OtpStorageFactory };
@@ -171,4 +171,5 @@ interface OtpStorageContractOptions {
171
171
  */
172
172
  declare function otpStorageContract(factory: OtpStorageFactory, options?: OtpStorageContractOptions): OtpStorageContractCase[];
173
173
 
174
- export { type OtpStorageContractCase, type OtpStorageContractOptions, type OtpStorageFactory, otpStorageContract };
174
+ export { otpStorageContract };
175
+ export type { OtpStorageContractCase, OtpStorageContractOptions, OtpStorageFactory };
@@ -20,9 +20,12 @@ function makeScope() {
20
20
  purpose: `${KEY_PREFIX}_${run}_${PURPOSE_MAIN}`,
21
21
  otherPurpose: `${KEY_PREFIX}_${run}_${PURPOSE_OTHER}`,
22
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"]
23
+ // joining the raw values around `:` maps both onto one string, and so does one
24
+ // built around `::`, which the single-colon pair alone does not expose.
25
+ boundaryShifts: [
26
+ { left: [`${KEY_PREFIX}_${run}_x:y`, "z"], right: [`${KEY_PREFIX}_${run}_x`, "y:z"] },
27
+ { left: [`${KEY_PREFIX}_${run}_x::y`, "z"], right: [`${KEY_PREFIX}_${run}_x`, "y::z"] }
28
+ ]
26
29
  };
27
30
  }
28
31
  var DEFAULT_EXPIRY_WAIT_MS = 1500;
@@ -52,7 +55,7 @@ async function cleanUp(storage, scope) {
52
55
  await storage.delete(tenant, scope.absentRecipient, purpose);
53
56
  await storage.clearCooldown(tenant, scope.absentRecipient, purpose);
54
57
  }
55
- for (const [tenant, recipient] of [scope.shiftedLeft, scope.shiftedRight]) {
58
+ for (const [tenant, recipient] of scope.boundaryShifts.flatMap((s) => [s.left, s.right])) {
56
59
  await storage.delete(tenant, recipient, scope.purpose);
57
60
  await storage.clearCooldown(tenant, recipient, scope.purpose);
58
61
  }
@@ -380,14 +383,14 @@ function keyBoundaryCase({ scope, withStorage }) {
380
383
  return {
381
384
  name: "keeps the tenant and recipient boundary when composing a key",
382
385
  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
- );
386
+ for (const { left, right } of scope.boundaryShifts) {
387
+ await storage.set(left[0], left[1], scope.purpose, makeEntry(6e4));
388
+ const bled = await storage.get(right[0], right[1], 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
+ }
391
394
  })
392
395
  };
393
396
  }
@@ -395,23 +398,18 @@ function cooldownKeyBoundaryCase({ scope, withStorage }) {
395
398
  return {
396
399
  name: "keeps the tenant and recipient boundary when composing a cooldown key",
397
400
  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
- );
401
+ for (const { left, right } of scope.boundaryShifts) {
402
+ const held = await storage.tryAcquireCooldown(left[0], left[1], 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(right[0], right[1], scope.purpose, 60);
408
+ check(
409
+ other,
410
+ "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"
411
+ );
412
+ }
415
413
  })
416
414
  };
417
415
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-notification",
3
- "version": "1.4.0",
3
+ "version": "1.4.1",
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",
@@ -117,11 +117,11 @@
117
117
  "@aws-sdk/client-ses": "^3.0.0",
118
118
  "@aws-sdk/client-sns": "^3.0.0",
119
119
  "mailgun.js": "^11.0.0 || ^12.0.0 || ^13.0.0",
120
- "nodemailer": "^9.0.1",
120
+ "nodemailer": "^10.1.4",
121
121
  "twilio": "^5.0.0 || ^6.0.0",
122
122
  "firebase-admin": "^13.0.0 || ^14.0.0",
123
123
  "@aws-sdk/client-dynamodb": "^3.0.0",
124
- "handlebars": "^4.7.9",
124
+ "handlebars": "^4.7.10",
125
125
  "@react-email/render": "^1.0.0 || ^2.0.0",
126
126
  "mjml": "^5.0.0",
127
127
  "class-validator": "^0.14.0 || ^0.15.0",
@@ -222,7 +222,7 @@
222
222
  "rxjs": "^7.8.0",
223
223
  "ts-jest": "^29.4.11",
224
224
  "ts-node": "^10.9.2",
225
- "tsup": "^8.5.1",
225
+ "tsup": "^9.0.0",
226
226
  "typescript": "^5.9.3"
227
227
  },
228
228
  "keywords": [