@bymax-one/nest-notification 1.4.9 → 1.4.11

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
@@ -11,6 +11,137 @@ the entries that carry one, is the compatibility contract — read it, not the n
11
11
 
12
12
  ## [Unreleased]
13
13
 
14
+ ## [1.4.11] - 2026-11-17
15
+
16
+ ### Added
17
+
18
+ - **`SmtpEmailProvider` can pool its connections, and closes with the application.** The new
19
+ option `pool` (`maxConnections` and `maxMessages`, each optional) turns Nodemailer's pooled mode
20
+ on, a limit left out keeping Nodemailer's default; without it the transport is configured as
21
+ before. The provider gains `close()`, which closes the transport it built (a send in flight on a
22
+ pooled transport finishes, one waiting for a connection fails, and a later `send()` builds a new
23
+ transport), and implements `onModuleDestroy`, so Nest closes it when the application closes. A
24
+ close that throws is logged as `[SMTP_CLOSE_FAILED]` with no text from the relay and is not
25
+ rethrown.
26
+
27
+ - **`otp.strictPurposes` refuses a purpose that nobody registered.** The limits of a recipient are
28
+ kept per `(tenant, recipient, purpose)` and a purpose with no `perPurpose` entry uses the
29
+ defaults, so a host that lets a caller choose the purpose lets the caller ask for a fresh
30
+ cooldown and attempt counter each time. With `strictPurposes: true`, `OtpService` refuses at every
31
+ operation, before any storage call, a purpose that is neither in
32
+ `NOTIFICATION_PURPOSES` nor a key of `perPurpose`, with `notification.invalid_scope_identifier`
33
+ (400) and the reason `not a registered purpose`, never the value. The option is a boolean
34
+ checked when the module starts and is off by default.
35
+
36
+ ### Documentation
37
+
38
+ - The README states how deep the audit metadata is kept, and a spec holds the number to the code.
39
+ - The README has a Production section: a bounded `ioredis` client and who closes it, the send
40
+ timeouts, the shutdown, and storing codes as digests.
41
+
42
+ #### Apply to a derived backend
43
+
44
+ `OtpChannelOptions` gains the optional `strictPurposes`, off by default, so a backend that does
45
+ not set it needs no change; one that sets it registers each purpose it uses that is not one of
46
+ the canonical purposes as a key of `perPurpose` (an empty object keeps the defaults).
47
+
48
+ `SmtpEmailProviderOptions` gains the optional `pool`, the exported `SmtpPoolOptions` type is new,
49
+ and `SmtpEmailProvider` gains `close()` and `onModuleDestroy()`. A backend that builds the
50
+ provider without `pool` needs no change; one that sets it should let Nest close the application,
51
+ or call `close()` itself.
52
+
53
+ ## [1.4.10] - 2026-11-16
54
+
55
+ ### Fixed
56
+
57
+ - **A control character in a value no longer starts a second audit record.** An audit entry carries
58
+ values a caller chose: a recipient, a user id, an error text, an email template name. The
59
+ interceptor, `OtpService` and `EmailService` wrote them as they came, so a line feed in one of
60
+ them started a record nobody wrote in any log or store that writes lines, and a bidirectional
61
+ control could make a line read as another. The entry is now escaped once, where every writer's
62
+ entry passes: every string of it, and every key and string value of its `metadata`, reaches
63
+ `INotificationLogRepository.create` with the C0 and C1 controls, the Unicode line and paragraph
64
+ separators and the bidirectional controls written as visible sequences (`\n`, `\r`, `\t`,
65
+ `\uXXXX`); a key that escapes to the text of an earlier key takes a `#2`, `#3` suffix. Metadata that is nested too deep, a cycle and a value that is not a plain
66
+ object, an array or a primitive arrive as a fixed marker. The `BYMAX_NOTIFICATION_LOG_REPOSITORY`
67
+ token still resolves to the host's own repository.
68
+
69
+ - **A purpose is a short name, and anything else is refused.** `purpose` is part of every storage
70
+ key, of the audit entry and of the template data, and nothing checked it: it could be empty,
71
+ carry a newline that forges a log record, carry glob characters that make a key pattern
72
+ unreliable, or be as long as the caller liked. A purpose is now 1 to 64 characters from
73
+ `A-Z a-z 0-9 : _ -`, checked by every OTP operation and by both reference storages before a key
74
+ is built. The refusal is `notification.invalid_scope_identifier` (400), names the boundary and
75
+ the parameter and never the value. A `perPurpose` key outside that set stops the module at
76
+ startup. The audit interceptor, which sees the payload before the service refuses it, leaves a
77
+ purpose that is not a plain name out of the entry it writes. The README now says what the limits
78
+ are scoped on and that purposes are the host's own.
79
+
80
+ - **One recipient, one key, whatever the spelling of its domain.** Two spellings of one mailbox's
81
+ domain reached two keys, so each had its own resend cooldown and attempt counter. The domain of an
82
+ email is now given the spelling a resolver gives it (UTS #46 mapping, non-transitional): fullwidth
83
+ and ligature forms and the punycode form of an internationalized domain are one key, and a domain
84
+ the mapping would change in any other way (an address literal, a host read as an address, text
85
+ with URL syntax in it) keeps its own spelling, lower-cased. The local part
86
+ gets no Unicode normalization, because two local parts that differ in a compatibility character are
87
+ two mailboxes and one key for both would let a code mailed to one verify for the other; plus tags
88
+ stay separate keys, which the README now says, with the advice to limit per user id. A recipient
89
+ whose domain is not plain ASCII gets a different key, so a code issued before the upgrade is not
90
+ found after it.
91
+
92
+ - **A control character in a relay's reply no longer starts a second log line.** The warning an
93
+ SMTP or Resend send failure logs carries the reason the relay or the API gave, after the
94
+ credentials and declared secrets are removed from it; the startup warning for a template
95
+ renderer that throws carries the error's text. A line feed in that text started a record nobody
96
+ wrote, and a bidirectional control could make a line read as another. These lines now write the
97
+ same controls the audit entry does as visible sequences, after the removal, so a declared value
98
+ that holds a line feed is still matched as written.
99
+
100
+ - **`InMemoryOtpStorage.size()` counts the failure counters.** The helper reported the entries and
101
+ the cooldowns and not the failure counters, so a test asserting that nothing is left behind could
102
+ not see a counter that leaked; it now returns `failures` as well.
103
+
104
+ - **Resolving a template placeholder no longer reads the whole data object.** `DefaultTemplateRenderer`
105
+ copied every own enumerable property of the data into a new map to find one value, and a nested path
106
+ did it for each segment. The work grew with the size of the object,
107
+ and a getter on a property the template never names ran, so one that threw broke a render that did
108
+ not ask for it. The renderer now reads only the property that is named, and only when it is an own
109
+ enumerable one: the same keys resolve as before, and inherited and prototype keys stay out of reach.
110
+ A getter on a named key now runs each time the placeholder is read, not once per render for a flat
111
+ placeholder, so a getter whose value changes between reads can differ between occurrences.
112
+
113
+ #### Apply to a derived backend
114
+
115
+ A purpose is now 1 to 64 characters from `A-Z a-z 0-9 : _ -`. `OtpService.generate`, `resend`,
116
+ `verify`, `consume` and `getStatus`, and the keys of `RedisOtpStorage` and `InMemoryOtpStorage`,
117
+ refuse any other with `notification.invalid_scope_identifier` (HTTP 400), where a purpose with a
118
+ space, a dot, a slash, a non-ASCII character, an empty string or more than 64 characters used to
119
+ work. A host that used such a purpose renames it; a code issued under one before the upgrade
120
+ cannot be verified after it, which only matters for the minutes of its lifetime. The
121
+ `NOTIFICATION_PURPOSES` and any snake_case name are unaffected. A `perPurpose` key outside the
122
+ set now fails when the module starts. A custom `IOtpStorage` needs no change: the service checks
123
+ before it calls the store, and the purposes `./testing` generates for its cases now fit the
124
+ rule. The default message of `INVALID_SCOPE_IDENTIFIER` in
125
+ `NOTIFICATION_ERROR_DEFINITIONS` is a literal type in the declarations and now reads "A tenant,
126
+ recipient or purpose identifier is not valid" where it said "Tenant or recipient identifier does
127
+ not identify anybody", so a host that matched on the old text updates; matching on the `code`
128
+ is unaffected.
129
+
130
+ A custom `INotificationLogRepository` now receives entries in which a control character in any
131
+ string, or in a key or string value of `metadata`, arrives as a visible escape sequence, and a
132
+ subtree of `metadata` that is too deep, circular or not a plain value arrives as a marker; a host
133
+ whose values never contain one sees no difference. The module wraps the repository for the
134
+ interceptor, `OtpService` and `EmailService`; a host that builds one of them by hand with `new`
135
+ passes its own repository straight through and escapes in its `create`. No declaration changes.
136
+
137
+ `InMemoryOtpStorage.size()` returns a `failures` field, and the exported
138
+ `InMemoryStorageSize` type gains it as a required property: code that reads the result is
139
+ unaffected, code that builds a value of that type adds the field.
140
+
141
+ The log lines of the SMTP and Resend providers and of the template startup check now hold a
142
+ reason with control characters written as visible sequences; the error those providers throw
143
+ keeps its text as it came, so a host that logs it writes its own line and escapes it there.
144
+
14
145
  ## [1.4.9] - 2026-11-14
15
146
 
16
147
  ### Fixed
@@ -1176,7 +1307,9 @@ rejected at startup rather than failing on the first send.
1176
1307
 
1177
1308
  [1.0.4]: https://github.com/bymaxone/nest-notification/compare/v1.0.3...v1.0.4
1178
1309
  [1.0.3]: https://github.com/bymaxone/nest-notification/compare/v1.0.2...v1.0.3
1179
- [Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.4.9...HEAD
1310
+ [Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.4.11...HEAD
1311
+ [1.4.11]: https://github.com/bymaxone/nest-notification/compare/v1.4.10...v1.4.11
1312
+ [1.4.10]: https://github.com/bymaxone/nest-notification/compare/v1.4.9...v1.4.10
1180
1313
  [1.4.9]: https://github.com/bymaxone/nest-notification/compare/v1.4.8...v1.4.9
1181
1314
  [1.4.8]: https://github.com/bymaxone/nest-notification/compare/v1.4.7...v1.4.8
1182
1315
  [1.4.7]: https://github.com/bymaxone/nest-notification/compare/v1.4.6...v1.4.7
package/README.md CHANGED
@@ -382,6 +382,8 @@ BymaxNotificationModule.forRoot({
382
382
 
383
383
  To capture HTTP-level `sent` / `failed` entries automatically, apply `NotificationAuditInterceptor` with `@UseInterceptors(...)` on a controller or handler, or wire it globally.
384
384
 
385
+ **Control characters are escaped before your repository sees an entry.** An entry carries values a caller chose (a recipient, a user id, an error text, a template name), and a line feed in one of them starts a second record in a log or a store that writes lines. Every string of an entry, and every key and string value of its `metadata`, reaches `create` with the C0 and C1 controls, the Unicode line and paragraph separators and the bidirectional controls written as visible sequences (`\n`, `\r`, `\t`, `\uXXXX`); a backslash is left as it is, so a key that escapes to the text of an earlier key takes a `#2`, `#3` suffix instead of replacing it. Metadata is kept down to 3 levels of nesting below the `metadata` object; a subtree deeper than that arrives as `[depth limit]`, a cycle as `[circular]`, and a value that is not a plain object, an array or a primitive as `[non-plain value]`. The module does this for every writer it wires, and the `BYMAX_NOTIFICATION_LOG_REPOSITORY` token still resolves to your own repository. A host that builds `OtpService`, `EmailService` or `NotificationAuditInterceptor` itself, with `new`, bypasses the wiring and has its own repository's `create` escape the strings of the entry the same way. The length of a value is not bounded here. The failure lines the library logs from text it did not write (the reason an SMTP relay or the Resend API gives, and the error a template renderer throws at startup) carry it with the same escape; the error those providers throw keeps the text as it came, and is yours to escape if you log it.
386
+
385
387
  ### 7. Frontend Integration (React)
386
388
 
387
389
  The `./react` subpath is browser-only state and UX — it drives the OTP-input box and a countdown. **Verifying the code is your app's job**: the hooks carry no HTTP client and no Node builtins, so nothing about your API shape is assumed.
@@ -433,6 +435,42 @@ if (error.code === NOTIFICATION_ERROR_CODES.OTP_MAX_ATTEMPTS_EXCEEDED) {
433
435
 
434
436
  ---
435
437
 
438
+ ## 🏭 Production
439
+
440
+ What the library leaves to you, and what to set before real traffic. The option tables are in the Configuration section and in [`docs/smtp-provider.md`](./docs/smtp-provider.md); nothing here restates a default.
441
+
442
+ ### The Redis client is yours: bound it, and close it
443
+
444
+ `RedisOtpStorage` uses the client you give it. It never connects it, configures it or quits it. A client with no bounds turns a Redis outage into requests that hang. With a connect timeout, a command timeout and a bounded retry policy, the same outage reaches the caller as the library's `503`: a command that fails because the server cannot be reached is answered as unavailable.
445
+
446
+ ```typescript
447
+ import Redis from 'ioredis'
448
+ import { RedisOtpStorage } from '@bymax-one/nest-notification'
449
+
450
+ const client = new Redis(process.env.REDIS_URL!, {
451
+ connectTimeout: 5_000,
452
+ commandTimeout: 2_000,
453
+ maxRetriesPerRequest: 1,
454
+ retryStrategy: (attempt) => Math.min(attempt * 200, 2_000)
455
+ })
456
+
457
+ const storage = new RedisOtpStorage({ redisClient: client })
458
+ ```
459
+
460
+ Close the client in your own shutdown hook, after Nest has closed the application, so no OTP operation is still running when its connection goes.
461
+
462
+ ### Bound every send
463
+
464
+ `ResendEmailProvider` takes `timeoutMs` and `SmtpEmailProvider` takes `sendTimeoutMs`, plus the phase timeouts, each with its default in the option tables. A send that times out fails with `EMAIL_SEND_FAILED`, and **may still have been delivered**: make the job that retries it idempotent, as the Apply note of 1.4.9 says.
465
+
466
+ ### Shut down cleanly
467
+
468
+ Call `app.enableShutdownHooks()`, or close the application yourself, and Nest calls `onModuleDestroy` on the providers. `SmtpEmailProvider` closes its transport there. That matters once you set `pool`: a pool keeps sockets to the relay open, and without a close they keep the process alive. `close()` is also public and idempotent. A send already in flight on a pooled transport finishes; one still waiting for a connection fails with `Connection pool was closed`. A `send()` after `close()` builds a new transport, which you have to close again if you keep the provider alive. A failing close is logged as `[SMTP_CLOSE_FAILED]` with no text from the relay and does not stop the other hooks.
469
+
470
+ ### Store codes as digests
471
+
472
+ Without `otp.codeSecret`, codes are stored in plaintext and the startup warning `BYMAX_NOTIFICATION_PLAINTEXT_OTP_CODES` says so. In production set it to a secret of at least 32 bytes; see [Stored codes are keyed digests](#stored-codes-are-keyed-digests-when-you-set-otpcodesecret).
473
+
436
474
  ## ⚙️ Configuration
437
475
 
438
476
  Configure via `forRoot(options)` or `forRootAsync({ useFactory })`. **At least one channel must be configured**, and configuring a channel the library does not implement throws at startup rather than failing on the first send. The full reference is in [`docs/technical_specification.md` §4](./docs/technical_specification.md); the most-used options:
@@ -459,6 +497,7 @@ Configure via `forRoot(options)` or `forRootAsync({ useFactory })`. **At least o
459
497
  | `otp` | `consumeOnVerify` | `false` | `true` deletes the code when `verify()` succeeds, once however many verifications run together (needs `IOtpStorage.deleteIfCode`); otherwise the entry is marked validated until `consume()` or its TTL. |
460
498
  | `otp` | `resendCooldownSeconds` | `60` | Anti-resend window (atomic `SET NX EX`). |
461
499
  | `otp` | `perPurpose` | `{}` | Per-purpose overrides of the above. |
500
+ | `otp` | `strictPurposes` | `false` | `true` refuses a purpose that is neither in `NOTIFICATION_PURPOSES` nor a key of `perPurpose`, before any storage call. |
462
501
  | `audit` | `repository` | — (required) | Any `INotificationLogRepository`. |
463
502
  | `audit` | `swallowErrors` | `true` | Keep audit failures out of the delivery path. A swallowed failure logs `BYMAX_NOTIFICATION_AUDIT_WRITE_FAILED`, at most once a minute per channel. |
464
503
  | `audit` | `maskRecipient` | identity | Minimize recipient PII before persisting. |
@@ -579,6 +618,14 @@ A code is short: a six-digit code has a million values, so a plain hash of it is
579
618
  - **Changing or removing the secret** makes the digests already stored unverifiable (`invalid_code`); those codes must be requested again. Downgrading the library below the version that introduced the option does the same.
580
619
  - A custom `IOtpStorage` is unaffected: `OtpEntry.code` is an opaque string to it.
581
620
 
621
+ ### Which spellings share a key
622
+
623
+ The recipient is normalized before it is hashed. Surrounding whitespace is trimmed, and an email (an identifier with an ASCII `@`) is lower-cased and its domain is given the spelling the resolver gives it, so `Jane@Acme.com`, `jane@acme.com` and `jane@acme.com` (fullwidth letters) are one recipient, and so are `jane@bücher.de` and `jane@xn--bcher-kva.de`. A domain the mapping would change in any other way keeps the spelling it was written in, lower-cased: an address literal, a host a URL parser reads as an address (`0x7f.1`), and a domain with anything in it that is not part of a name. The local part gets no Unicode normalization: two local parts that differ in a compatibility character (`file` and `file`) are two mailboxes at a provider that accepts them, and one key for both would let a code mailed to one verify for the other. A plus tag is kept for the same reason of not guessing a provider's rules: `jane+1@acme.com` and `jane@acme.com` are two recipients, each with its own cooldown and attempt counter, although many providers deliver both to one mailbox. A host that must limit per mailbox limits per user id, not per recipient.
624
+
625
+ ### Purposes are yours
626
+
627
+ A purpose names a flow (`email_verification`, `password_reset`): 1 to 64 characters from `A-Z a-z 0-9 : _ -`. Every OTP operation and both reference storages refuse anything else with `notification.invalid_scope_identifier` (HTTP 400), and a `perPurpose` key outside that set stops the module at startup. The refusal never carries the value. The limits of a recipient are kept per `(tenant, recipient, purpose)`, and a purpose with no `perPurpose` entry uses the defaults, so a caller who can choose the purpose can ask for a fresh cooldown and a fresh attempt counter each time. Purposes are yours: a literal from `NOTIFICATION_PURPOSES` or your own list, never taken from the request. If a purpose can still reach the service from outside, set `otp.strictPurposes: true`: a purpose that is neither in `NOTIFICATION_PURPOSES` nor a key of `perPurpose` is then refused the same way (`reason: 'not a registered purpose'`), so your own flows are registered with `perPurpose: { my_flow: {} }`.
628
+
582
629
  ### Attempt ceilings and cooldowns are atomic
583
630
 
584
631
  `consumeAttempt` is the only writer of the attempt counter, and `tryAcquireCooldown` (`SET NX EX`) is the only acquirer of the resend window — both inside the storage, in one indivisible step. A service-side `get` followed by an `update` looks equivalent and passes every sequential test, but two concurrent verifies read the same count and each writes back the same increment: five attempts become unbounded. The same shape lets two concurrent resends both pass the cooldown check.
@@ -593,7 +640,7 @@ With the default, `consumeOnVerify: false`, the entry is marked validated and st
593
640
 
594
641
  A per-code counter alone lets a re-issue reset the failure count: guess wrongly up to the limit, wait out the resend cooldown, and guess again. So the failed verifications of a `(tenant, recipient, purpose)` are counted in the storage, and `verify()` refuses once that count passes the purpose's attempt ceiling, whichever code is live.
595
642
 
596
- - Every verification attempt against a live code adds one to the count, before its code is compared, and restarts the counter's lifetime to the purpose's code lifetime (`ttlSeconds`); a counter that is not touched for that long lapses, which starts the count again from zero.
643
+ - Every verification attempt against a live code adds one to the count, before its code is compared, and restarts the counter's lifetime to the purpose's code lifetime (`ttlSeconds`); a counter that is not touched for that long lapses, which starts the count again from zero. Because every attempt restarts the lifetime, attempts spaced closer apart than `ttlSeconds` never let the counter lapse; only a success, `consume()` or `ttlSeconds` of silence resets it, which is the stricter behaviour against a slow attack.
597
644
  - A successful verification and `consume()` clear it (the attempt that succeeded included), so the next flow starts with a full budget.
598
645
  - Once the count passes the ceiling, `verify()` returns `{ valid: false, reason: 'max_attempts' }` for any code, a freshly issued one included, until the counter lapses. The stored count alone decides, so the lockout ends exactly when the counter lapses. Because the increment is atomic and happens first, guesses that arrive together each get their own number and only those within the ceiling are compared. `remainingAttempts` reports the nearer of the code's own budget and the count's. This also means that someone who keeps sending wrong guesses for a recipient keeps that recipient locked out, so rate-limit the OTP endpoints by IP in your controller.
599
646
  - `RedisOtpStorage` keeps the counter under `{namespace}:otp_fail:{purpose}:{hash}`, incremented by one script; `InMemoryOtpStorage` does the same in memory.
@@ -657,7 +704,7 @@ A one-time password is a credential, so every behavior is pinned so that a regre
657
704
  | Coverage | **100%** line/branch/function/statement per file (`pnpm test:cov:all`) |
658
705
  | Mutation | Stryker score **100%** (`break: 100`), no survivors |
659
706
  | Lint | ESLint flat config + `eslint-plugin-security`, zero warnings |
660
- | Bundle budgets | server < 33.21 KB · shared < 4 KB · react < 8 KB · testing < 4.5 KB brotli (`pnpm size`) |
707
+ | Bundle budgets | server < 35.34 KB · shared < 4 KB · react < 8 KB · testing < 4.5 KB brotli (`pnpm size`) |
661
708
  | Prisma-free | `pnpm check:no-prisma` — the library never imports `@prisma/client` |
662
709
  | Export map | `pnpm check:exports` — `attw` against the packed tarball, ESM and CJS |
663
710
  | Supply chain | published with npm provenance (OIDC), CodeQL + OpenSSF Scorecard |
@@ -732,15 +779,15 @@ pnpm mutation # Stryker mutation testing
732
779
 
733
780
  ### Reference adapters
734
781
 
735
- | Export | Implements | Use for |
736
- | ------------------------------- | ---------------------------- | ----------------------------------------------------------------------- |
737
- | `ResendEmailProvider` | `IEmailProvider` | Production email via Resend |
738
- | `SmtpEmailProvider` | `IEmailProvider` | Any SMTP relay, and Mailpit/MailHog in tests |
739
- | `NoOpEmailProvider` | `IEmailProvider` | Dev/test — logs a masked recipient only |
740
- | `RedisOtpStorage` | `IOtpStorage` | Production OTP state (atomic via Lua) |
741
- | `InMemoryOtpStorage` | `IOtpStorage` | Dev/test — single-process only; `.size()` returns `{ otps, cooldowns }` |
742
- | `DefaultTemplateRenderer` | `IEmailTemplateRenderer` | `{{var}}` interpolation with HTML escaping |
743
- | `NoOpNotificationLogRepository` | `INotificationLogRepository` | Audit configured but intentionally discarded |
782
+ | Export | Implements | Use for |
783
+ | ------------------------------- | ---------------------------- | --------------------------------------------------------------- |
784
+ | `ResendEmailProvider` | `IEmailProvider` | Production email via Resend |
785
+ | `SmtpEmailProvider` | `IEmailProvider` | Any SMTP relay, and Mailpit/MailHog in tests |
786
+ | `NoOpEmailProvider` | `IEmailProvider` | Dev/test — logs a masked recipient only |
787
+ | `RedisOtpStorage` | `IOtpStorage` | Production OTP state (atomic via Lua) |
788
+ | `InMemoryOtpStorage` | `IOtpStorage` | Dev/test — single-process only; `.size()` reports what it holds |
789
+ | `DefaultTemplateRenderer` | `IEmailTemplateRenderer` | `{{var}}` interpolation with HTML escaping |
790
+ | `NoOpNotificationLogRepository` | `INotificationLogRepository` | Audit configured but intentionally discarded |
744
791
 
745
792
  ### Utilities
746
793