@bymax-one/nest-notification 1.4.1 → 1.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +171 -1
- package/README.md +168 -48
- package/dist/server/index.cjs +382 -56
- package/dist/server/index.d.cts +203 -6
- package/dist/server/index.d.ts +203 -6
- package/dist/server/index.mjs +383 -57
- package/dist/shared/index.cjs +1 -0
- package/dist/shared/index.d.cts +2 -1
- package/dist/shared/index.d.ts +2 -1
- package/dist/shared/index.mjs +1 -0
- package/dist/testing/index.cjs +207 -12
- package/dist/testing/index.d.cts +36 -7
- package/dist/testing/index.d.ts +36 -7
- package/dist/testing/index.mjs +207 -12
- package/package.json +4 -57
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,175 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [1.4.2] - 2026-10-31
|
|
11
|
+
|
|
12
|
+
### Security
|
|
13
|
+
|
|
14
|
+
- **Two spellings of one mailbox are one OTP state.** `OtpService` keyed its state on the recipient
|
|
15
|
+
byte for byte, so `Jane@Acme.com`, `jane@acme.com` and ` jane@acme.com` each had their own resend
|
|
16
|
+
cooldown and their own attempt counter: with `defaultMaxAttempts: 3`, five spellings accepted 15
|
|
17
|
+
wrong guesses and five codes could be minted back to back, and a user who typed another case than
|
|
18
|
+
the one the code was issued for was told it did not exist. The service now keys on the recipient
|
|
19
|
+
with surrounding whitespace trimmed and an email address (a value containing `@`) lower-cased, in
|
|
20
|
+
all five methods and in the audit entry. The message is still delivered to the address exactly as
|
|
21
|
+
supplied, because RFC 5321 §2.4 requires a sender to preserve the local-part's case; only the key
|
|
22
|
+
is folded. A recipient that is not an email is only trimmed.
|
|
23
|
+
- **`EmailService` refuses a tenant that identifies nobody.** `send` and `sendTemplate` accepted an
|
|
24
|
+
empty or whitespace-only `tenantId` and recorded any string in the audit entry verbatim. They now
|
|
25
|
+
refuse it with `notification.invalid_scope_identifier`, as `OtpService` already did.
|
|
26
|
+
- **A control character in a tenant is refused in both services, and in a recipient by `OtpService`.** A newline in an
|
|
27
|
+
identifier reaches the consumer's audit sink and log lines verbatim and forges a second record;
|
|
28
|
+
no legitimate identifier contains one. The refusal never echoes the value.
|
|
29
|
+
- **An OTP code can be stored as a keyed digest instead of in plaintext.** `OtpEntry.code` held the
|
|
30
|
+
code itself, so anyone able to read Redis saw every live code. The new optional
|
|
31
|
+
`otp.codeSecret` (a string of at least 32 UTF-8 bytes, validated at startup, kept with the
|
|
32
|
+
application and not in the store) makes `OtpService` store `hmac-sha256:v1:<hex>`, an HMAC-SHA-256
|
|
33
|
+
of the code, and compare a guess in constant time. It is defence in depth: NIST SP 800-63B-4
|
|
34
|
+
requires hashing for look-up secrets and a separately stored key for password verifiers, and
|
|
35
|
+
says nothing about an out-of-band code. A plain hash would not do, since a six-digit code is
|
|
36
|
+
recovered by trying a million values. Without the option nothing changes except one startup
|
|
37
|
+
warning that codes are stored in plaintext. The delivered email still carries the plaintext
|
|
38
|
+
code, the audit entry carries neither form, and the secret is not a property of the resolved
|
|
39
|
+
options.
|
|
40
|
+
- **Failed verifications now survive a re-issue.** NIST SP 800-63B-4 §3.1.3.2 says generating a new
|
|
41
|
+
authentication secret "SHALL NOT reset the failed authentication count", yet every new code got a
|
|
42
|
+
fresh `defaultMaxAttempts`: with 3 attempts, three wrong guesses, a re-issue after the cooldown
|
|
43
|
+
and three more were all accepted, so the limit only bounded guesses per cooldown. A
|
|
44
|
+
`(tenant, recipient, purpose)` now has a failure counter in the storage: every verification attempt against a
|
|
45
|
+
live code adds one and restarts its lifetime to the purpose's code lifetime, `verify()` counts each attempt before
|
|
46
|
+
comparing the code and refuses once the count passes the ceiling whichever code is live, and a successful verification or `consume()` clears it.
|
|
47
|
+
`RedisOtpStorage` keeps it under `{namespace}:otp_fail:{purpose}:{hash}` with one atomic script.
|
|
48
|
+
A custom `IOtpStorage` opts in with three optional methods, `getFailures`, `recordFailure` and
|
|
49
|
+
`clearFailures`; one without them behaves as before and the module logs one
|
|
50
|
+
`BYMAX_NOTIFICATION_OTP_FAILURES_NOT_CARRIED` warning at startup. The executable contract in
|
|
51
|
+
`./testing` checks the three methods when they are present and passes trivially when they are
|
|
52
|
+
absent.
|
|
53
|
+
- **New error code `notification.otp_manual_delivery_unavailable`** (400; 24 codes, up from 23).
|
|
54
|
+
`generate()` never returns the code, so a manual delivery reads it back from the store, and a
|
|
55
|
+
store that holds a digest has nothing to hand over. With `otp.codeSecret` set, a manual
|
|
56
|
+
delivery (`deliverVia: 'manual'`, or the default when no email channel is configured) is refused
|
|
57
|
+
before the cooldown is taken or anything is stored, instead of succeeding with a code nobody can
|
|
58
|
+
deliver.
|
|
59
|
+
|
|
60
|
+
### ⚠️ Apply before upgrading
|
|
61
|
+
|
|
62
|
+
- **`otp.codeSecret` is opt-in and loses no live code.** An entry stored in plaintext before the
|
|
63
|
+
secret was set still verifies until it expires. Changing the secret, removing it, or
|
|
64
|
+
downgrading below this version leaves the stored digests unverifiable (`invalid_code`): those
|
|
65
|
+
codes must be requested again. A custom `IOtpStorage` is unaffected, since `OtpEntry.code` is an
|
|
66
|
+
opaque string. Set the secret from a secret store, not from the place the Redis credentials come
|
|
67
|
+
from, or a reader of Redis gets both.
|
|
68
|
+
- **A recipient at the failure ceiling stays locked out until the counter lapses.** With a
|
|
69
|
+
storage that carries failures (the bundled ones), a recipient at the ceiling gets
|
|
70
|
+
`{ valid: false, reason: 'max_attempts' }` for any code, a freshly issued one included, until the
|
|
71
|
+
counter has not been touched for the purpose's code lifetime. Someone who sends wrong
|
|
72
|
+
guesses for another person's address can keep that address locked out; rate-limit the OTP
|
|
73
|
+
endpoints by IP in your controller, as the security checklist says.
|
|
74
|
+
- **If you implement `IOtpStorage` yourself,** add `getFailures`, `recordFailure` and `clearFailures`
|
|
75
|
+
and re-run the contract from `@bymax-one/nest-notification/testing`. Until you do, a re-issued
|
|
76
|
+
code gets a fresh attempt budget and the startup warning says so. Redis users: the new key
|
|
77
|
+
`{namespace}:otp_fail:*` is created on the first wrong guess; nothing is migrated.
|
|
78
|
+
- **One extra storage write in `verify()`.** The stored failure count is the only thing that
|
|
79
|
+
outlives a code, so `verify()` increments it before comparing the code, while a code is live (one atomic script on Redis)
|
|
80
|
+
and refuses once the number passes the ceiling; a code is issued with its own full attempt count and
|
|
81
|
+
the lockout ends exactly when the counter lapses. Storages without the failure methods skip the
|
|
82
|
+
write. A refused verification now reports `max_attempts` where it used to report `not_found` after
|
|
83
|
+
the code was spent.
|
|
84
|
+
- **`otp.codeSecret` and manual delivery do not combine.** Where a flow delivers the code itself
|
|
85
|
+
(`deliverVia: 'manual'`, or no email channel), leave the secret unset or move that flow to email
|
|
86
|
+
delivery; a development setup that reads the code from the store keeps `codeSecret` unset.
|
|
87
|
+
- **A module with the OTP channel and no `otp.codeSecret` logs one warning at startup** (from
|
|
88
|
+
`forRoot` and `forRootAsync`). Set the option, or filter the log line
|
|
89
|
+
`BYMAX_NOTIFICATION_PLAINTEXT_OTP_CODES` if plaintext storage is a decision you have made.
|
|
90
|
+
- **A live OTP issued to a recipient with uppercase letters or surrounding whitespace is re-keyed.**
|
|
91
|
+
The code was stored under the old key, so verifying it after the upgrade reports `not_found`
|
|
92
|
+
until the user asks for a new code. The window is the code's TTL (10 minutes by default).
|
|
93
|
+
- **`getEmail()`, `getOtp()` and `dispatch` refuse a configured-but-unusable channel with 501.** Code
|
|
94
|
+
that branched on `notification.email_provider_not_configured` (500) from a `dispatch` or from a
|
|
95
|
+
send made through `getEmail()` now sees `notification.channel_disabled` (501) there; a send made
|
|
96
|
+
on an injected `EmailService` still raises the former.
|
|
97
|
+
- **The fourteen unused optional peers are gone from `package.json`.** If a tool of yours reads this
|
|
98
|
+
package's peer list to decide what to install (a template, a bootstrap script), install the SDK
|
|
99
|
+
of the adapter you write yourself: `handlebars` for a Handlebars renderer, `@sendgrid/mail` for
|
|
100
|
+
a SendGrid provider, and so on. The package no longer lists them.
|
|
101
|
+
- **A caller that passed a blank `tenantId` to `EmailService` now gets a 400.** Pass the tenant the
|
|
102
|
+
email belongs to.
|
|
103
|
+
|
|
104
|
+
### Changed
|
|
105
|
+
|
|
106
|
+
- **`RedisLike` accepts an ioredis client as the documentation shows.** `set` was declared as a
|
|
107
|
+
variadic `(key, value, ...args)`, which no overload of ioredis 6's `set` satisfies, so
|
|
108
|
+
`new RedisOtpStorage({ redisClient: new Redis(url) })`, the production example in the README, did
|
|
109
|
+
not compile under `strict`. It now declares the two forms the storage calls: the cooldown lock
|
|
110
|
+
(`EX`, seconds, `NX`) and the in-place rewrite that keeps the expiry (`KEEPTTL`, `XX`). A client
|
|
111
|
+
or double you wrote with a variadic `set` still satisfies it. Nothing changes at runtime.
|
|
112
|
+
- **A channel that is configured but unusable is refused the way `getEnabledChannels()` omits it.**
|
|
113
|
+
When the email provider or the OTP storage reports `isConfigured() === false` (a Resend client
|
|
114
|
+
without its key, an SMTP relay without a host), `getEnabledChannels()` already left the channel
|
|
115
|
+
out, yet `getEmail()` and `getOtp()` still returned the service and the first send failed later.
|
|
116
|
+
They now throw `notification.channel_disabled` (501) with `details.reason`
|
|
117
|
+
(`provider_not_configured` or `storage_not_configured`), and a `dispatch` to that channel is
|
|
118
|
+
refused the same way. The module also logs one `BYMAX_NOTIFICATION_CHANNEL_NOT_USABLE` warning
|
|
119
|
+
per such channel at startup, from `forRoot` and `forRootAsync`. Failing the boot instead is not
|
|
120
|
+
done: an application that starts without its secrets (a preview, a CI job) keeps starting.
|
|
121
|
+
- **Fourteen optional peer dependencies the package never loads are removed.** `package.json`
|
|
122
|
+
declared `@sendgrid/mail`, `@aws-sdk/client-ses`, `@aws-sdk/client-sns`,
|
|
123
|
+
`@aws-sdk/client-dynamodb`, `mailgun.js`, `twilio`, `firebase-admin`, `handlebars`,
|
|
124
|
+
`@react-email/render`, `mjml`, `class-validator`, `class-transformer`, `express` and
|
|
125
|
+
`@types/express` as optional peers, but no source file imports any of them: they were the
|
|
126
|
+
libraries the documentation's adapter examples use. What remains is what the package loads:
|
|
127
|
+
`@nestjs/common`, `@nestjs/core`, `reflect-metadata` and `rxjs` (required), `ioredis`, `resend`,
|
|
128
|
+
`nodemailer` and `react` (optional). Removing an optional peer cannot break an installation; it
|
|
129
|
+
stops advertising a range for packages the library has no code for, and it stops a scan of your
|
|
130
|
+
dependency tree from attributing their advisories to this package. An adapter you write for one
|
|
131
|
+
of those providers keeps depending on its SDK in your application.
|
|
132
|
+
|
|
133
|
+
### Documentation
|
|
134
|
+
|
|
135
|
+
- **README: three statements corrected against the code.** The subpath diagram drew `react`
|
|
136
|
+
depending on `shared`; `react` imports only `react`, and `server` is the subpath that builds on
|
|
137
|
+
`shared`. The Architecture section said an unconfigured channel is a startup error; it is not —
|
|
138
|
+
`getEnabledChannels()` lists the wired channels, and `getEmail()` / `getOtp()` throw
|
|
139
|
+
`CHANNEL_DISABLED` for one that is not. The SMTP `requireTls` default now reads "`true` unless
|
|
140
|
+
implicit TLS or loopback", which is what the provider does on port 465.
|
|
141
|
+
- **README: the multi-tenant snippet imports what it calls.** The `tenantIdResolver` example called
|
|
142
|
+
`BymaxNotificationModule.forRoot` after importing only a type, so pasted as written it did not
|
|
143
|
+
compile.
|
|
144
|
+
- **README: every error code, who raises it, and which are reserved.** A table lists every code with
|
|
145
|
+
its HTTP status and the component that throws it. The codes the library never throws are marked
|
|
146
|
+
reserved: the four OTP verify outcomes (`verify()` returns the reason instead),
|
|
147
|
+
`email_invalid_recipient` (the recipient is not validated), and the SMS and push codes.
|
|
148
|
+
- **README: the options and members that were only in the technical specification.**
|
|
149
|
+
`consumeOnVerify`, `defaultFromName`, `defaultReplyTo` and `defaultTags` join the Configuration
|
|
150
|
+
table; the `DefaultTemplateRenderer` options, the `EmailService.send` and `OtpService.generate`
|
|
151
|
+
inputs, the `useOtpInput` and `useOtpCountdown` options, the injection tokens,
|
|
152
|
+
`InMemoryOtpStorage.size()` and the `otpStorageContract` usage example are documented.
|
|
153
|
+
|
|
154
|
+
### Tests
|
|
155
|
+
|
|
156
|
+
- **The README's option-default tables are held to the code.** Two specs parse the Configuration
|
|
157
|
+
table and the SMTP option table and assert every stated default, every "required" marker, the
|
|
158
|
+
OTP length range and the SMTP port, TLS and timeout rules against the resolved options and the
|
|
159
|
+
transport the provider builds, so a drifted cell fails the suite instead of reaching npm.
|
|
160
|
+
- **`check:published` compiles every README snippet against the built types.** It now runs the
|
|
161
|
+
TypeScript API, so a parse error in one snippet no longer hides the semantic errors in the
|
|
162
|
+
others; compiles snippets that do not import the package too; and types the names
|
|
163
|
+
the prose introduces in `scripts/readme-prelude.d.ts`, so a wrong method, option or destructured
|
|
164
|
+
field is an error instead of a call through `any`.
|
|
165
|
+
- **The error table and the renderer options are held to the code.** One spec compares the README
|
|
166
|
+
error table with the catalog and with the source: a code is reserved exactly when no file
|
|
167
|
+
constructs a `NotificationException` with it. Another builds a `DefaultTemplateRenderer` without
|
|
168
|
+
each option and checks the documented default.
|
|
169
|
+
- **`RedisOtpStorage` is exercised against a real Redis on every pull request.** A `Real Redis e2e`
|
|
170
|
+
job starts `redis:8-alpine` with testcontainers and runs the executable `otpStorageContract`,
|
|
171
|
+
200 concurrent `recordFailure` calls, the hashed `otp_fail` key with its lifetime, and the
|
|
172
|
+
`OtpService` flows (lockout across a re-issue, parallel guesses, a success clearing the counter).
|
|
173
|
+
The unit suite keeps its in-process double; `pnpm test:e2e:redis` runs the same suite locally with
|
|
174
|
+
Docker.
|
|
175
|
+
- **A test guess cannot equal a generated code.** Specs that guessed `000000` against a code the
|
|
176
|
+
service had just generated failed about once in a million runs; they now guess `ABCDEF`, which
|
|
177
|
+
no numeric code can equal.
|
|
178
|
+
|
|
10
179
|
## [1.4.1] - 2026-10-30
|
|
11
180
|
|
|
12
181
|
### Security
|
|
@@ -772,7 +941,8 @@ rejected at startup rather than failing on the first send.
|
|
|
772
941
|
|
|
773
942
|
[1.0.4]: https://github.com/bymaxone/nest-notification/compare/v1.0.3...v1.0.4
|
|
774
943
|
[1.0.3]: https://github.com/bymaxone/nest-notification/compare/v1.0.2...v1.0.3
|
|
775
|
-
[Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.4.
|
|
944
|
+
[Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.4.2...HEAD
|
|
945
|
+
[1.4.2]: https://github.com/bymaxone/nest-notification/compare/v1.4.1...v1.4.2
|
|
776
946
|
[1.4.1]: https://github.com/bymaxone/nest-notification/compare/v1.4.0...v1.4.1
|
|
777
947
|
[1.4.0]: https://github.com/bymaxone/nest-notification/compare/v1.3.1...v1.4.0
|
|
778
948
|
[1.3.1]: https://github.com/bymaxone/nest-notification/compare/v1.3.0...v1.3.1
|
package/README.md
CHANGED
|
@@ -79,7 +79,7 @@ pnpm add @bymax-one/nest-notification
|
|
|
79
79
|
### 🧩 Developer Experience
|
|
80
80
|
|
|
81
81
|
- ✅ **Subpaths** — server, zero-dependency shared types, React hooks, and a `testing` storage contract
|
|
82
|
-
- ✅ **Stable error catalog** —
|
|
82
|
+
- ✅ **Stable error catalog** — 24 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
|
|
|
@@ -97,12 +97,10 @@ One package, four entry points — import only what your app needs:
|
|
|
97
97
|
| **Testing** | `@bymax-one/nest-notification/testing` | Executable `IOtpStorage` contract for your own storage | None |
|
|
98
98
|
|
|
99
99
|
```
|
|
100
|
-
shared (zero deps)
|
|
101
|
-
↗ ↖
|
|
102
|
-
server react
|
|
100
|
+
shared (zero deps) ← server react
|
|
103
101
|
```
|
|
104
102
|
|
|
105
|
-
`shared`
|
|
103
|
+
`shared` has no dependencies, `server` builds on it and re-exports its error codes and TTLs, and `react` imports nothing but `react` — importing one never drags in another's peers. Every subpath ships ESM (`.mjs`), CJS (`.cjs`), and declarations for both formats (`.d.ts` + `.d.cts`).
|
|
106
104
|
|
|
107
105
|
---
|
|
108
106
|
|
|
@@ -321,15 +319,15 @@ BymaxNotificationModule.forRoot({
|
|
|
321
319
|
})
|
|
322
320
|
```
|
|
323
321
|
|
|
324
|
-
| Option | Default
|
|
325
|
-
| --------------------------------------------------------- |
|
|
326
|
-
| `host` | —
|
|
327
|
-
| `port` | `587`
|
|
328
|
-
| `secure` | `true` iff port 465
|
|
329
|
-
| `requireTls` | `true`
|
|
330
|
-
| `credentials` | — (open relay)
|
|
331
|
-
| `tls` | —
|
|
332
|
-
| `connectionTimeout` / `greetingTimeout` / `socketTimeout` | `10s` / `10s` / `20s`
|
|
322
|
+
| Option | Default | Notes |
|
|
323
|
+
| --------------------------------------------------------- | -------------------------------------- | ---------------------------------------------------------------------------- |
|
|
324
|
+
| `host` | — | Required. Without it `isConfigured()` is `false` and `send()` throws. |
|
|
325
|
+
| `port` | `587` | Submission port. |
|
|
326
|
+
| `secure` | `true` iff port 465 | Implicit TLS from the first byte. |
|
|
327
|
+
| `requireTls` | `true` unless implicit TLS or loopback | Makes the STARTTLS upgrade mandatory. See the TLS note below. |
|
|
328
|
+
| `credentials` | — (open relay) | `{ user, pass }`. Supplying it declares the deployment logs in. |
|
|
329
|
+
| `tls` | — | `rejectUnauthorized` / `servername` / `ca`, for a relay behind a private CA. |
|
|
330
|
+
| `connectionTimeout` / `greetingTimeout` / `socketTimeout` | `10s` / `10s` / `20s` | Bounded on purpose — Nodemailer's own defaults run into minutes. |
|
|
333
331
|
|
|
334
332
|
> [!IMPORTANT]
|
|
335
333
|
> `isConfigured()` answers on the real configuration, not on "a transport object exists". Omitting `credentials` marks the relay as open and is fine; supplying them half-loaded — an `SMTP_PASS` that never made it into the environment — reports **not configured** and fails the send closed, rather than silently attempting an anonymous delivery a permissive relay might accept.
|
|
@@ -504,25 +502,30 @@ if (error.code === NOTIFICATION_ERROR_CODES.OTP_MAX_ATTEMPTS_EXCEEDED) {
|
|
|
504
502
|
|
|
505
503
|
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:
|
|
506
504
|
|
|
507
|
-
| Section | Option | Default | Notes
|
|
508
|
-
| -------- | ----------------------- | ---------------- |
|
|
509
|
-
| `global` | `redisNamespace` | `'notification'` | Prefix for store keys.
|
|
510
|
-
| `global` | `defaultLocale` | `'en'` | Template locale fallback.
|
|
511
|
-
| `global` | `tenantIdResolver` | — | `(req) => tenantId`; the audit source of truth.
|
|
512
|
-
| `email` | `provider` | — (required) | Instance or class implementing `IEmailProvider`.
|
|
513
|
-
| `email` | `defaultFrom` | — (required) | Must look like an email address.
|
|
514
|
-
| `email` | `templateRenderer` | default renderer | Any `IEmailTemplateRenderer`.
|
|
515
|
-
| `email` | `maxAttachmentBytes` | `10485760` | 10 MiB attachment guard.
|
|
516
|
-
| `otp` | `storage` | — (required) | Instance or class implementing `IOtpStorage`.
|
|
517
|
-
| `otp` | `defaultLength` | `6` | 1–32.
|
|
518
|
-
| `otp` | `defaultCodeType` | `'numeric'` | `numeric` \| `alpha` \| `alphanumeric`.
|
|
519
|
-
| `otp` | `defaultTtlSeconds` | `600` | Code lifetime.
|
|
520
|
-
| `otp` | `defaultMaxAttempts` | `5` | Verify attempts before lock-out.
|
|
521
|
-
| `otp` | `
|
|
522
|
-
| `otp` | `
|
|
523
|
-
| `
|
|
524
|
-
| `
|
|
525
|
-
| `
|
|
505
|
+
| Section | Option | Default | Notes |
|
|
506
|
+
| -------- | ----------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------- |
|
|
507
|
+
| `global` | `redisNamespace` | `'notification'` | Prefix for store keys. |
|
|
508
|
+
| `global` | `defaultLocale` | `'en'` | Template locale fallback. |
|
|
509
|
+
| `global` | `tenantIdResolver` | — | `(req) => tenantId`; the audit source of truth. |
|
|
510
|
+
| `email` | `provider` | — (required) | Instance or class implementing `IEmailProvider`. |
|
|
511
|
+
| `email` | `defaultFrom` | — (required) | Must look like an email address. |
|
|
512
|
+
| `email` | `templateRenderer` | default renderer | Any `IEmailTemplateRenderer`. |
|
|
513
|
+
| `email` | `maxAttachmentBytes` | `10485760` | 10 MiB attachment guard. |
|
|
514
|
+
| `otp` | `storage` | — (required) | Instance or class implementing `IOtpStorage`. |
|
|
515
|
+
| `otp` | `defaultLength` | `6` | 1–32. |
|
|
516
|
+
| `otp` | `defaultCodeType` | `'numeric'` | `numeric` \| `alpha` \| `alphanumeric`. |
|
|
517
|
+
| `otp` | `defaultTtlSeconds` | `600` | Code lifetime. |
|
|
518
|
+
| `otp` | `defaultMaxAttempts` | `5` | Verify attempts before lock-out. |
|
|
519
|
+
| `otp` | `codeSecret` | — | Secret (>= 32 bytes) the stored code is keyed under. |
|
|
520
|
+
| `otp` | `consumeOnVerify` | `false` | `true` deletes the code when `verify()` succeeds; otherwise the entry is marked validated until `consume()` or its TTL. |
|
|
521
|
+
| `email` | `defaultFromName` | — | Display name sent with `defaultFrom`. |
|
|
522
|
+
| `email` | `defaultReplyTo` | — | `Reply-To` applied when a send does not set one. |
|
|
523
|
+
| `email` | `defaultTags` | `[]` | Tags merged into every send, before the send's own tags. |
|
|
524
|
+
| `otp` | `resendCooldownSeconds` | `60` | Anti-resend window (atomic `SET NX EX`). |
|
|
525
|
+
| `otp` | `perPurpose` | `{}` | Per-purpose overrides of the above. |
|
|
526
|
+
| `audit` | `repository` | — (required) | Any `INotificationLogRepository`. |
|
|
527
|
+
| `audit` | `swallowErrors` | `true` | Keep audit failures out of the delivery path. |
|
|
528
|
+
| `audit` | `maskRecipient` | identity | Minimize recipient PII before persisting. |
|
|
526
529
|
|
|
527
530
|
---
|
|
528
531
|
|
|
@@ -532,6 +535,13 @@ Email rendering goes through `IEmailTemplateRenderer`. The bundled `DefaultTempl
|
|
|
532
535
|
|
|
533
536
|
Register named templates per `name::locale`; the renderer falls back to the `en` locale when a locale-specific template is missing.
|
|
534
537
|
|
|
538
|
+
| Renderer option | Default | Notes |
|
|
539
|
+
| ------------------- | --------- | ----------------------------------------------------------------------------------------------------- |
|
|
540
|
+
| `templates` | `{}` | `{ 'name::locale': { subject, html, text? } }`. Every template needs a string `subject` and `html`. |
|
|
541
|
+
| `fallbackLocales` | `['en']` | Locales tried, in order, after the requested one. |
|
|
542
|
+
| `onMissingVar` | `'empty'` | `'empty'` renders a missing variable as an empty string; `'throw'` raises instead. |
|
|
543
|
+
| `enableNestedPaths` | `false` | `true` resolves `{{user.name}}` through nested objects; `false` looks up the literal key `user.name`. |
|
|
544
|
+
|
|
535
545
|
`CANONICAL_EMAIL_TEMPLATES` exports stable names for common transactional emails (`otp_code`, `otp_password_reset`, `otp_resent`, `welcome`, `password_reset_success`, `trial_expiring`, …) so providers and templates agree on the wire. For richer output, plug in Handlebars, MJML, or React Email — examples under [`docs/templates/`](./docs/templates/).
|
|
536
546
|
|
|
537
547
|
---
|
|
@@ -561,7 +571,7 @@ The package runs **inside** your NestJS application as a dynamic module — not
|
|
|
561
571
|
└──────────────────────────────────────────────────┘
|
|
562
572
|
```
|
|
563
573
|
|
|
564
|
-
`NotificationService` is the façade: it dispatches to the channel services and exposes `getEnabledChannels()`, `getEmail()`, and `getOtp()` for direct access. Only the channels present in your configuration are
|
|
574
|
+
`NotificationService` is the façade: it dispatches to the channel services and exposes `getEnabledChannels()`, `getEmail()`, and `getOtp()` for direct access. Only the channels present in your configuration are wired: `getEnabledChannels()` lists them, and `getEmail()` / `getOtp()` throw `CHANNEL_DISABLED` for a channel that is not.
|
|
565
575
|
|
|
566
576
|
### Design Principles
|
|
567
577
|
|
|
@@ -598,7 +608,7 @@ The trade-off — opaque keys you cannot read back to a recipient — is intenti
|
|
|
598
608
|
When you expose notification endpoints over HTTP, a caller could forge another tenant's id in the request body — `POST { "tenantId": "tenant_a", … }` sent from `tenant_b` to verify someone else's OTP. Configure a `tenantIdResolver` that reads the tenant from a **trusted** source: a verified JWT claim, a subdomain, or a gateway-checked header.
|
|
599
609
|
|
|
600
610
|
```typescript
|
|
601
|
-
import type
|
|
611
|
+
import { BymaxNotificationModule, type NotificationRequest } from '@bymax-one/nest-notification'
|
|
602
612
|
|
|
603
613
|
BymaxNotificationModule.forRoot({
|
|
604
614
|
global: {
|
|
@@ -633,12 +643,34 @@ The library **never** writes a code to a sink that can be read back:
|
|
|
633
643
|
- Not inside an `errorMessage`, which carries the message only — never a stack trace.
|
|
634
644
|
- 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.
|
|
635
645
|
|
|
636
|
-
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`.
|
|
646
|
+
Within this library, codes exist only inside the OTP store, under a TTL (as a keyed digest when `otp.codeSecret` is set, see below), 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`.
|
|
647
|
+
|
|
648
|
+
### Stored codes are keyed digests when you set `otp.codeSecret`
|
|
649
|
+
|
|
650
|
+
A code is short: a six-digit code has a million values, so a plain hash of it is recovered by trying all of them, in a fraction of a second, by anyone who can read the store. With `otp.codeSecret` set (a string of at least 32 bytes, kept with the application and never in Redis), the store holds `hmac-sha256:v1:<hex>`, an HMAC-SHA-256 of the code under that secret, and `verify()` recomputes it and compares in constant time. A reader of the store alone then holds nothing to test a guess against. The delivered email still carries the plaintext code, and the audit entry never carries either form.
|
|
651
|
+
|
|
652
|
+
This is defence in depth, not a standards requirement: NIST SP 800-63B-4 requires hashed storage for look-up secrets (§3.1.2.2) and a keyed hash with the key "stored separately" for password verifiers (§3.1.1.2), and says nothing about hashing an out-of-band code (§3.1.3.2). The OWASP Password Storage Cheat Sheet describes the same shape for a low-entropy secret: an HMAC whose key is kept separately from the data.
|
|
653
|
+
|
|
654
|
+
- **Unset** (the default): codes are stored in plaintext, and a warning is logged once at startup.
|
|
655
|
+
- **Manual delivery is refused while it is set.** `generate()` never returns the code, so a manual delivery reads it back from the store, and a store that holds a digest has nothing to hand over. `generate({ deliverVia: 'manual' })`, or the default delivery when no email channel is configured, fails with `notification.otp_manual_delivery_unavailable` (400) before the cooldown is taken or anything is stored. Deliver by email, or leave `codeSecret` unset where you read the code from the store (a local development flow, for instance).
|
|
656
|
+
- **Turning it on loses no live code.** An entry written in plaintext before the secret was set still verifies until it expires.
|
|
657
|
+
- **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.
|
|
658
|
+
- A custom `IOtpStorage` is unaffected: `OtpEntry.code` is an opaque string to it.
|
|
637
659
|
|
|
638
660
|
### Attempt ceilings and cooldowns are atomic
|
|
639
661
|
|
|
640
662
|
`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.
|
|
641
663
|
|
|
664
|
+
### Failed attempts survive a re-issue
|
|
665
|
+
|
|
666
|
+
NIST SP 800-63B-4 §3.1.3.2: "Generating a new authentication secret SHALL NOT reset the failed authentication count." A per-code counter alone breaks that rule: three wrong guesses, a re-issue after the resend cooldown, and three more were accepted, so the attempt limit was only a rate limit of `defaultMaxAttempts` guesses per cooldown. The failed verifications of a `(tenant, recipient, purpose)` are now counted in the storage, and `verify()` refuses once that count passes the purpose's attempt ceiling, whichever code is live.
|
|
667
|
+
|
|
668
|
+
- 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.
|
|
669
|
+
- A successful verification and `consume()` clear it (the attempt that succeeded included), so the next flow starts with a full budget.
|
|
670
|
+
- 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.
|
|
671
|
+
- `RedisOtpStorage` keeps the counter under `{namespace}:otp_fail:{purpose}:{hash}`, incremented by one script; `InMemoryOtpStorage` does the same in memory.
|
|
672
|
+
- A custom `IOtpStorage` opts in by implementing three **optional** methods, `getFailures`, `recordFailure` and `clearFailures`; the executable contract in `./testing` checks them when they are present. The three work together: a storage with only some of them is treated as having none. Without them each code keeps a fresh budget, and one warning, `BYMAX_NOTIFICATION_OTP_FAILURES_NOT_CARRIED`, is logged at startup naming the deviation.
|
|
673
|
+
|
|
642
674
|
### Security Checklist
|
|
643
675
|
|
|
644
676
|
When integrating `@bymax-one/nest-notification` in production, verify each of the following:
|
|
@@ -646,9 +678,10 @@ When integrating `@bymax-one/nest-notification` in production, verify each of th
|
|
|
646
678
|
- `tenantIdResolver` reads from a **verified** source (JWT claim, subdomain, gateway-signed header) — never the request body
|
|
647
679
|
- `audit.maskRecipient` is configured if audit rows are retained beyond the operational minimum
|
|
648
680
|
- A custom `IOtpStorage` implements `consumeAttempt` and `tryAcquireCooldown` atomically
|
|
649
|
-
-
|
|
681
|
+
- `OtpService` keys its state on the recipient with surrounding whitespace trimmed and an email address lower-cased, so `Jane@Acme.com`, `jane@acme.com` and ` jane@acme.com` share one cooldown and one attempt counter; the message is still delivered to the address exactly as you pass it (RFC 5321 §2.4). A recipient that is not an email is only trimmed. Store and compare the same canonical form on your side
|
|
682
|
+
- `otp.codeSecret` is set, from a secret store and not from the same place as the Redis credentials, so a reader of the store cannot test a guess against a stored code
|
|
650
683
|
- `resendCooldownSeconds` and `defaultMaxAttempts` are tuned per purpose, not left at the defaults for high-value flows
|
|
651
|
-
- Your own controller rate-limits the OTP endpoints — the library bounds attempts per
|
|
684
|
+
- Your own controller rate-limits the OTP endpoints — the library bounds failed attempts per recipient and purpose, not requests per IP
|
|
652
685
|
|
|
653
686
|
---
|
|
654
687
|
|
|
@@ -747,6 +780,33 @@ pnpm mutation # Stryker mutation testing
|
|
|
747
780
|
| `NotificationService` | `getEnabledChannels()` | `NotificationChannel[]` | Which channels this instance actually registered |
|
|
748
781
|
| `NotificationService` | `getEmail()` / `getOtp()` | the channel service | Direct access when you already know the channel |
|
|
749
782
|
|
|
783
|
+
### Send and issue options
|
|
784
|
+
|
|
785
|
+
`EmailService.send()` takes these fields. `sendTemplate()` takes `tenantId`, `to`, `from`, `fromName`, `replyTo`, `tags`, `userId`, `auditRedactValues` and `publishProviderText` as below, plus `template`, `data` and an optional `locale` in place of `subject`, `html` and `text`; it has no `cc`, `bcc` or `attachments`.
|
|
786
|
+
|
|
787
|
+
| Field | Notes |
|
|
788
|
+
| ----------------------------- | -------------------------------------------------------------------------------------------------- |
|
|
789
|
+
| `tenantId` | Required. Refused when blank or when it contains a control character. |
|
|
790
|
+
| `to`, `cc`, `bcc` | A string or an array. `to` is not validated by the library. |
|
|
791
|
+
| `subject`, `html`, `text` | The message. `text` is optional. |
|
|
792
|
+
| `from`, `fromName`, `replyTo` | Override the `defaultFrom`, `defaultFromName` and `defaultReplyTo` of the channel. |
|
|
793
|
+
| `tags` | Merged after `defaultTags`. |
|
|
794
|
+
| `attachments` | `{ filename, content, contentType? }[]`; their total size is checked against `maxAttachmentBytes`. |
|
|
795
|
+
| `userId` | Recorded in the audit entry. |
|
|
796
|
+
| `auditRedactValues` | Values scrubbed from the failure's `cause` and `errorMessage`. See [Errors](#errors). |
|
|
797
|
+
| `publishProviderText` | `false` withholds everything the provider wrote. Default `true`. |
|
|
798
|
+
|
|
799
|
+
`OtpService.generate()` and `resend()` take:
|
|
800
|
+
|
|
801
|
+
| Field | Notes |
|
|
802
|
+
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
803
|
+
| `tenantId`, `recipient`, `purpose` | Required; the OTP state is keyed on all three. |
|
|
804
|
+
| `deliverVia` | `'email'` hands the code to the email channel; `'manual'` leaves delivery to you. Default `'email'` when an email channel exists, otherwise `'manual'`. |
|
|
805
|
+
| `emailTemplate` | Template rendered for email delivery. Default `'otp_code'`. |
|
|
806
|
+
| `emailData` | Variables for the template. `code`, `expiresInMinutes` and `purpose` are added to them. |
|
|
807
|
+
| `locale` | Locale for the template. Default `global.defaultLocale`. |
|
|
808
|
+
| `userId` | Recorded in the audit entry. |
|
|
809
|
+
|
|
750
810
|
### Interceptor
|
|
751
811
|
|
|
752
812
|
| Member | Purpose |
|
|
@@ -759,11 +819,40 @@ pnpm mutation # Stryker mutation testing
|
|
|
759
819
|
| -------------------------------- | -------------------------------------------------------------------------- |
|
|
760
820
|
| `NotificationException` | `HttpException` carrying a stable `code`, a status, and optional `details` |
|
|
761
821
|
| `NotificationExceptionOptions` | Constructor options bag: `{ status?, message?, cause? }` |
|
|
762
|
-
| `NOTIFICATION_ERROR_CODES` | The
|
|
822
|
+
| `NOTIFICATION_ERROR_CODES` | The 24 stable `notification.*` codes — branch on these, not on messages |
|
|
763
823
|
| `NOTIFICATION_ERROR_DEFINITIONS` | Server-side code → HTTP status + default English message |
|
|
764
824
|
|
|
765
825
|
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
826
|
|
|
827
|
+
A code marked **reserved** is part of the catalog but is never thrown by the library, so a consumer can map it without the library ever raising it behind their back. The four OTP verify outcomes are the notable ones: `verify()` returns its failure as a result (`{ valid: false, reason }`) and never throws it, so your controller maps `reason` to the code it wants to answer with. The SMS and push codes stay reserved until those channels exist.
|
|
828
|
+
|
|
829
|
+
| Code | Status | Raised by |
|
|
830
|
+
| ------------------------------------------------ | ------ | ------------------------------------------------------------------------------------------------------------------ |
|
|
831
|
+
| `notification.email_provider_not_configured` | 500 | `EmailService` — the provider reports `isConfigured() === false` |
|
|
832
|
+
| `notification.email_send_failed` | 502 | `EmailService` — the provider rejected the send |
|
|
833
|
+
| `notification.email_attachments_too_large` | 413 | `EmailService` — the attachments exceed `maxAttachmentBytes` |
|
|
834
|
+
| `notification.email_invalid_recipient` | 400 | reserved — `to` is not validated; a bad address surfaces as `email_send_failed` |
|
|
835
|
+
| `notification.email_missing_body` | 400 | `NotificationService.dispatch` — neither a template nor a subject and body |
|
|
836
|
+
| `notification.template_not_found` | 500 | `EmailService.sendTemplate` — no template for the locale or the fallback |
|
|
837
|
+
| `notification.template_render_failed` | 500 | `EmailService.sendTemplate` — the renderer threw |
|
|
838
|
+
| `notification.otp_storage_not_configured` | 500 | `OtpService` — the OTP channel is absent |
|
|
839
|
+
| `notification.otp_email_delivery_not_configured` | 500 | `OtpService.generate` — email delivery without an email channel |
|
|
840
|
+
| `notification.otp_manual_delivery_unavailable` | 400 | `OtpService.generate` — manual delivery while `otp.codeSecret` is set |
|
|
841
|
+
| `notification.otp_cooldown_active` | 429 | `OtpService.generate` and `resend` — inside the resend cooldown |
|
|
842
|
+
| `notification.otp_not_found` | 404 | reserved — `verify()` returns `{ valid: false, reason: 'not_found' }` |
|
|
843
|
+
| `notification.otp_expired` | 410 | reserved — an expired code is reported as `not_found` |
|
|
844
|
+
| `notification.otp_max_attempts_exceeded` | 429 | reserved — `verify()` returns `{ valid: false, reason: 'max_attempts' }` |
|
|
845
|
+
| `notification.otp_invalid_code` | 401 | reserved — `verify()` returns `{ valid: false, reason: 'invalid_code' }` |
|
|
846
|
+
| `notification.otp_invalid_length` | 400 | module options validation and the code generator |
|
|
847
|
+
| `notification.sms_provider_not_configured` | 500 | reserved — the SMS channel is not implemented |
|
|
848
|
+
| `notification.sms_send_failed` | 502 | reserved — the SMS channel is not implemented |
|
|
849
|
+
| `notification.sms_invalid_recipient` | 400 | reserved — the SMS channel is not implemented |
|
|
850
|
+
| `notification.push_provider_not_configured` | 500 | reserved — the push channel is not implemented |
|
|
851
|
+
| `notification.push_send_failed` | 502 | reserved — the push channel is not implemented |
|
|
852
|
+
| `notification.audit_log_failed` | 500 | `EmailService`, `OtpService` and `NotificationAuditInterceptor` — only with `audit.swallowErrors: false` |
|
|
853
|
+
| `notification.channel_disabled` | 501 | `NotificationService` — the channel is absent, or its provider or storage is not usable |
|
|
854
|
+
| `notification.invalid_scope_identifier` | 400 | `OtpService`, `EmailService` and `NotificationAuditInterceptor` — a blank or control-character tenant or recipient |
|
|
855
|
+
|
|
767
856
|
Failures raised by the library carry the underlying error as the native `Error.cause` — a provider's `connect ECONNREFUSED` sits on `exception.cause`, where cause-walking log serializers (e.g. pino's `err`) print it alongside the stable code. The cause is stored as a **log-safe copy**: `name`, `message`, `stack`, and the nested `cause` chain survive (depth-bounded); every other property is dropped, because SDK errors routinely retain the request payload (an axios-style `config.data`) and for an OTP email that payload contains the code. The cause never enters the HTTP response body either: `details` stays reserved for the structured, client-safe context shown above. To attach a cause in your own code, pass the options bag as the third constructor argument — `new NotificationException('EMAIL_SEND_FAILED', { providerName }, { cause: error })`; the positional `(key, details, status, message)` form keeps working.
|
|
768
857
|
|
|
769
858
|
**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.
|
|
@@ -795,15 +884,15 @@ The default is `true`, and deliberately so: for a receipt or a marketing send th
|
|
|
795
884
|
|
|
796
885
|
### Reference adapters
|
|
797
886
|
|
|
798
|
-
| Export | Implements | Use for
|
|
799
|
-
| ------------------------------- | ---------------------------- |
|
|
800
|
-
| `ResendEmailProvider` | `IEmailProvider` | Production email via Resend
|
|
801
|
-
| `SmtpEmailProvider` | `IEmailProvider` | Any SMTP relay, and Mailpit/MailHog in tests
|
|
802
|
-
| `NoOpEmailProvider` | `IEmailProvider` | Dev/test — logs a masked recipient only
|
|
803
|
-
| `RedisOtpStorage` | `IOtpStorage` | Production OTP state (atomic via Lua)
|
|
804
|
-
| `InMemoryOtpStorage` | `IOtpStorage` | Dev/test — single-process only
|
|
805
|
-
| `DefaultTemplateRenderer` | `IEmailTemplateRenderer` | `{{var}}` interpolation with HTML escaping
|
|
806
|
-
| `NoOpNotificationLogRepository` | `INotificationLogRepository` | Audit configured but intentionally discarded
|
|
887
|
+
| Export | Implements | Use for |
|
|
888
|
+
| ------------------------------- | ---------------------------- | ----------------------------------------------------------------------- |
|
|
889
|
+
| `ResendEmailProvider` | `IEmailProvider` | Production email via Resend |
|
|
890
|
+
| `SmtpEmailProvider` | `IEmailProvider` | Any SMTP relay, and Mailpit/MailHog in tests |
|
|
891
|
+
| `NoOpEmailProvider` | `IEmailProvider` | Dev/test — logs a masked recipient only |
|
|
892
|
+
| `RedisOtpStorage` | `IOtpStorage` | Production OTP state (atomic via Lua) |
|
|
893
|
+
| `InMemoryOtpStorage` | `IOtpStorage` | Dev/test — single-process only; `.size()` returns `{ otps, cooldowns }` |
|
|
894
|
+
| `DefaultTemplateRenderer` | `IEmailTemplateRenderer` | `{{var}}` interpolation with HTML escaping |
|
|
895
|
+
| `NoOpNotificationLogRepository` | `INotificationLogRepository` | Audit configured but intentionally discarded |
|
|
807
896
|
|
|
808
897
|
### Utilities
|
|
809
898
|
|
|
@@ -823,6 +912,37 @@ The default is `true`, and deliberately so: for a receipt or a marketing send th
|
|
|
823
912
|
| `useOtpInput()` | `{ values, setValue, onChange, onKeyDown, onPaste, refs, code, isComplete, reset }` | Multi-slot OTP input with paste and arrow navigation |
|
|
824
913
|
| `useOtpCountdown()` | `{ remainingSeconds, formatted, expired }` | Expiry countdown for the resend button |
|
|
825
914
|
|
|
915
|
+
| Hook option | Default | Notes |
|
|
916
|
+
| ------------------------------------- | ------------ | ----------------------------------------------------------------------------------------------------- |
|
|
917
|
+
| `useOtpInput({ length })` | `6` | Number of slots. |
|
|
918
|
+
| `useOtpInput({ type })` | `'numeric'` | `'numeric'`, `'alpha'` or `'alphanumeric'`; other characters are dropped and letters are upper-cased. |
|
|
919
|
+
| `useOtpInput({ onComplete })` | — | Called with the full code once every slot is filled. |
|
|
920
|
+
| `useOtpInput({ autoSubmit })` | `true` | `false` stops `onComplete` from firing on its own. |
|
|
921
|
+
| `useOtpInput({ sanitizeOnPaste })` | `true` | Strips whitespace and hyphens from pasted text before distributing it. |
|
|
922
|
+
| `useOtpCountdown({ expiresAt })` | — (required) | Epoch milliseconds, or `null` for no countdown. |
|
|
923
|
+
| `useOtpCountdown({ tickIntervalMs })` | `1000` | How often `remainingSeconds` is recomputed. |
|
|
924
|
+
| `useOtpCountdown({ onExpired })` | — | Called once when the countdown reaches zero. |
|
|
925
|
+
|
|
926
|
+
### Injection tokens
|
|
927
|
+
|
|
928
|
+
Every token is a `Symbol()`, exported for an advanced override or a test that replaces one part of the module: `BYMAX_NOTIFICATION_OPTIONS` (the resolved, frozen options), `BYMAX_NOTIFICATION_EMAIL_PROVIDER`, `BYMAX_NOTIFICATION_OTP_STORAGE`, `BYMAX_NOTIFICATION_TEMPLATE_RENDERER` and `BYMAX_NOTIFICATION_LOG_REPOSITORY`. `BYMAX_NOTIFICATION_SMS_PROVIDER` and `BYMAX_NOTIFICATION_PUSH_PROVIDER` exist for the reserved channels and carry nothing today.
|
|
929
|
+
|
|
930
|
+
### Testing your own storage (`./testing`)
|
|
931
|
+
|
|
932
|
+
`otpStorageContract(factory, options?)` returns the executable cases your own `IOtpStorage` has to pass: atomic attempt counting, atomic cooldown, TTL that survives an update, and keys scoped by tenant, recipient and purpose. Each case is `{ name, run }`, so it runs in any test runner; `expiryWaitMs` raises the wait of the TTL cases for a backend with coarse expiry.
|
|
933
|
+
|
|
934
|
+
```ts
|
|
935
|
+
import { InMemoryOtpStorage } from '@bymax-one/nest-notification'
|
|
936
|
+
import { otpStorageContract } from '@bymax-one/nest-notification/testing'
|
|
937
|
+
|
|
938
|
+
// Run it once per storage you ship; Jest, Vitest and node:test all accept this loop.
|
|
939
|
+
for (const contractCase of otpStorageContract(() => new InMemoryOtpStorage())) {
|
|
940
|
+
it(contractCase.name, contractCase.run)
|
|
941
|
+
}
|
|
942
|
+
```
|
|
943
|
+
|
|
944
|
+
Passing the contract does not prove a key encoding safe against every delimiter: it exercises the `:` and `::` joins, and the storage still has to encode the tenant and recipient boundary itself.
|
|
945
|
+
|
|
826
946
|
### Constants
|
|
827
947
|
|
|
828
948
|
| Export | Subpath | Purpose |
|