@bymax-one/nest-notification 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +70 -0
- package/LICENSE +21 -0
- package/README.md +785 -0
- package/dist/react/index.cjs +225 -0
- package/dist/react/index.d.cts +105 -0
- package/dist/react/index.d.ts +105 -0
- package/dist/react/index.mjs +222 -0
- package/dist/server/index.cjs +2087 -0
- package/dist/server/index.d.cts +2155 -0
- package/dist/server/index.d.ts +2155 -0
- package/dist/server/index.mjs +2067 -0
- package/dist/shared/index.cjs +49 -0
- package/dist/shared/index.d.cts +138 -0
- package/dist/shared/index.d.ts +138 -0
- package/dist/shared/index.mjs +46 -0
- package/package.json +244 -0
|
@@ -0,0 +1,2155 @@
|
|
|
1
|
+
import { ModuleMetadata, FactoryProvider, DynamicModule, NestInterceptor, ExecutionContext, CallHandler, HttpStatus, HttpException } from '@nestjs/common';
|
|
2
|
+
import { Observable } from 'rxjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @fileoverview Email send provider contract (`IEmailProvider`) and its DTOs.
|
|
6
|
+
* @layer domain
|
|
7
|
+
*
|
|
8
|
+
* Defines *what* to send, never *how*. Reference adapters (Resend, SendGrid, SES)
|
|
9
|
+
* implement this; `EmailService` consumes it and maps thrown errors to
|
|
10
|
+
* `NotificationException`.
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* Email send provider.
|
|
14
|
+
*
|
|
15
|
+
* Implementations must:
|
|
16
|
+
* - never log the email body in plaintext (it may carry OTP codes / PII);
|
|
17
|
+
* - never leak credentials (API keys) in error messages;
|
|
18
|
+
* - throw an `Error` with a useful message on failure — `EmailService` catches it
|
|
19
|
+
* and converts it to a `NotificationException`.
|
|
20
|
+
*/
|
|
21
|
+
interface IEmailProvider {
|
|
22
|
+
/**
|
|
23
|
+
* Sends a transactional email.
|
|
24
|
+
*
|
|
25
|
+
* @param options - The message envelope and body.
|
|
26
|
+
* @returns The provider's send result (carries the `messageId`).
|
|
27
|
+
* @throws Error When the send fails; `EmailService` converts it to a `NotificationException`.
|
|
28
|
+
*/
|
|
29
|
+
send(options: EmailSendOptions): Promise<EmailSendResult>;
|
|
30
|
+
/**
|
|
31
|
+
* Whether the provider is configured and ready to send. Used by `EmailService`
|
|
32
|
+
* for startup validation (e.g. warn when credentials are missing).
|
|
33
|
+
*/
|
|
34
|
+
isConfigured(): boolean;
|
|
35
|
+
/** Provider name (e.g. `'resend'`, `'sendgrid'`, `'ses'`) — used in logs and audit. */
|
|
36
|
+
readonly name: string;
|
|
37
|
+
}
|
|
38
|
+
/** A single email attachment. `content` is a `Buffer` or a base64 string. */
|
|
39
|
+
interface EmailAttachment {
|
|
40
|
+
filename: string;
|
|
41
|
+
content: Buffer | string;
|
|
42
|
+
contentType?: string;
|
|
43
|
+
}
|
|
44
|
+
/** Options describing one transactional email to send. */
|
|
45
|
+
interface EmailSendOptions {
|
|
46
|
+
/** Recipient email address(es). */
|
|
47
|
+
to: string | string[];
|
|
48
|
+
/** Sender email (overrides the channel's `defaultFrom`). */
|
|
49
|
+
from?: string;
|
|
50
|
+
/** Sender display name. */
|
|
51
|
+
fromName?: string;
|
|
52
|
+
/** Subject line. */
|
|
53
|
+
subject: string;
|
|
54
|
+
/** HTML body. */
|
|
55
|
+
html: string;
|
|
56
|
+
/** Plain-text body (recommended for deliverability). */
|
|
57
|
+
text?: string;
|
|
58
|
+
/** Reply-to address. */
|
|
59
|
+
replyTo?: string;
|
|
60
|
+
/** Carbon-copy recipient(s). */
|
|
61
|
+
cc?: string | string[];
|
|
62
|
+
/** Blind carbon-copy recipient(s). */
|
|
63
|
+
bcc?: string | string[];
|
|
64
|
+
/** Provider-side tracking tags (Resend tags, SES tags, …). */
|
|
65
|
+
tags?: ReadonlyArray<{
|
|
66
|
+
name: string;
|
|
67
|
+
value: string;
|
|
68
|
+
}>;
|
|
69
|
+
/** Custom headers. */
|
|
70
|
+
headers?: Record<string, string>;
|
|
71
|
+
/** Attachments. */
|
|
72
|
+
attachments?: ReadonlyArray<EmailAttachment>;
|
|
73
|
+
}
|
|
74
|
+
/** Result of a successful send. `messageId` is provider-specific; useful for audit correlation. */
|
|
75
|
+
interface EmailSendResult {
|
|
76
|
+
messageId: string;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* @fileoverview Email template renderer contract (`IEmailTemplateRenderer`).
|
|
81
|
+
* @layer domain
|
|
82
|
+
*
|
|
83
|
+
* Pluggable templating: the default is `{{var}}` interpolation with HTML escape;
|
|
84
|
+
* consumers may plug in Handlebars / MJML / React Email by implementing this.
|
|
85
|
+
*/
|
|
86
|
+
/** A rendered email — subject + bodies ready to hand to an `IEmailProvider`. */
|
|
87
|
+
interface RenderedEmail {
|
|
88
|
+
subject: string;
|
|
89
|
+
html: string;
|
|
90
|
+
text?: string;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Email template renderer.
|
|
94
|
+
*
|
|
95
|
+
* Lets the email channel swap engines (simple interpolation, Handlebars, MJML,
|
|
96
|
+
* React Email, …) behind one contract.
|
|
97
|
+
*/
|
|
98
|
+
interface IEmailTemplateRenderer {
|
|
99
|
+
/**
|
|
100
|
+
* Renders a template to a subject + HTML (and optionally text) body.
|
|
101
|
+
*
|
|
102
|
+
* @param templateName - Template key (e.g. `'otp_code'`, `'welcome'`).
|
|
103
|
+
* @param data - Variables to interpolate.
|
|
104
|
+
* @param locale - Locale (e.g. `'en'`, `'pt-BR'`).
|
|
105
|
+
* @returns The rendered email.
|
|
106
|
+
* @throws Error When the template is not found.
|
|
107
|
+
*/
|
|
108
|
+
render(templateName: string, data: Record<string, unknown>, locale: string): Promise<RenderedEmail>;
|
|
109
|
+
/**
|
|
110
|
+
* Whether the renderer has the template registered for the locale — lets
|
|
111
|
+
* `EmailService` fail early when a template is missing.
|
|
112
|
+
*/
|
|
113
|
+
hasTemplate(templateName: string, locale: string): Promise<boolean>;
|
|
114
|
+
/** Renderer name (e.g. `'default-interpolation'`, `'handlebars'`). */
|
|
115
|
+
readonly name: string;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* @fileoverview Public `NotificationChannel` union for the shared subpath.
|
|
120
|
+
* @layer shared
|
|
121
|
+
*
|
|
122
|
+
* Zero-dependency type. `'sms'` and `'push'` are part of the union so consumers can
|
|
123
|
+
* plan dispatch code paths against a stable shape, even though no service serves them.
|
|
124
|
+
*/
|
|
125
|
+
/**
|
|
126
|
+
* A delivery/identity channel a notification can flow through.
|
|
127
|
+
*
|
|
128
|
+
* - `email` — transactional email.
|
|
129
|
+
* - `otp` — one-time-passcode lifecycle (generate / verify / consume).
|
|
130
|
+
* - `sms` — text message (declared; no service behind it).
|
|
131
|
+
* - `push` — device push notification (declared; no service behind it).
|
|
132
|
+
*/
|
|
133
|
+
type NotificationChannel = 'email' | 'otp' | 'sms' | 'push';
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* @fileoverview Audit-log repository contract (`INotificationLogRepository`).
|
|
137
|
+
* @layer domain
|
|
138
|
+
*
|
|
139
|
+
* Optional compliance/audit sink. The consumer owns persistence (Postgres, Mongo,
|
|
140
|
+
* ClickHouse, BigQuery, …); the library only describes the entry shape.
|
|
141
|
+
*/
|
|
142
|
+
|
|
143
|
+
/** Event verb recorded on a {@link NotificationLogEntry}. */
|
|
144
|
+
type NotificationLogVerb = 'sent' | 'generated' | 'verified' | 'failed' | 'cooldown_blocked' | 'max_attempts_exceeded';
|
|
145
|
+
/** A single audit-log entry. */
|
|
146
|
+
interface NotificationLogEntry {
|
|
147
|
+
/** Event time as a Unix timestamp in milliseconds. */
|
|
148
|
+
timestamp: number;
|
|
149
|
+
/** Tenant the event belongs to. */
|
|
150
|
+
tenantId: string;
|
|
151
|
+
/** Channel the event occurred on. */
|
|
152
|
+
channel: NotificationChannel;
|
|
153
|
+
/** What happened. */
|
|
154
|
+
verb: NotificationLogVerb;
|
|
155
|
+
/** Recipient identifier (email/phone/userId) — masked when the consumer configures a masker. */
|
|
156
|
+
recipient: string;
|
|
157
|
+
/** OTP purpose, or the email template name. */
|
|
158
|
+
purpose?: string;
|
|
159
|
+
/** Provider name used (`resend`, `twilio`, `fcm`, …). */
|
|
160
|
+
providerName: string;
|
|
161
|
+
/** Provider-returned message id, for correlation. */
|
|
162
|
+
messageId?: string;
|
|
163
|
+
/** Failure message only — NEVER a stack trace (avoids PII / vulnerability leakage). */
|
|
164
|
+
errorMessage?: string;
|
|
165
|
+
/** Associated user id, when known. */
|
|
166
|
+
userId?: string;
|
|
167
|
+
/** Arbitrary caller metadata. */
|
|
168
|
+
metadata?: Record<string, unknown>;
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Notification audit-log repository.
|
|
172
|
+
*
|
|
173
|
+
* Records successful send/generate/verify calls and failures. Writes are
|
|
174
|
+
* fire-and-forget — gated by the channel's `audit.swallowErrors` setting.
|
|
175
|
+
*/
|
|
176
|
+
interface INotificationLogRepository {
|
|
177
|
+
/**
|
|
178
|
+
* Persists one audit entry.
|
|
179
|
+
*
|
|
180
|
+
* @param entry - The entry to record.
|
|
181
|
+
*/
|
|
182
|
+
create(entry: NotificationLogEntry): Promise<void>;
|
|
183
|
+
/** Repository name (e.g. `'prisma'`, `'noop'`). */
|
|
184
|
+
readonly name: string;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* @fileoverview OTP storage contract (`IOtpStorage`) — the core security surface.
|
|
189
|
+
* @layer domain
|
|
190
|
+
*
|
|
191
|
+
* Single persistence interface for all OTP state. This interface DISSOLVES the
|
|
192
|
+
* Prisma coupling that a typical consumer's hand-rolled OTP store would otherwise
|
|
193
|
+
* impose: the library never imports the Prisma client (nor any ORM) — every
|
|
194
|
+
* consumer plugs in their own storage (Redis, in-memory, …).
|
|
195
|
+
*/
|
|
196
|
+
/** A stored OTP entry. */
|
|
197
|
+
interface OtpEntry {
|
|
198
|
+
/** Plaintext OTP code. Never logged. */
|
|
199
|
+
code: string;
|
|
200
|
+
/** Expiration as a Unix timestamp in milliseconds. */
|
|
201
|
+
expiresAt: number;
|
|
202
|
+
/** Number of verification attempts made so far. */
|
|
203
|
+
attempts: number;
|
|
204
|
+
/** Maximum attempts before the entry is invalidated. */
|
|
205
|
+
maxAttempts: number;
|
|
206
|
+
/** Whether the OTP has already been successfully verified (not yet deleted). */
|
|
207
|
+
validated?: boolean;
|
|
208
|
+
/** Optional caller metadata — ignored by the library. */
|
|
209
|
+
metadata?: Record<string, unknown>;
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Result of the atomic {@link IOtpStorage.consumeAttempt} primitive.
|
|
213
|
+
*
|
|
214
|
+
* - `not_found` — no entry, or it expired (the two are indistinguishable once the TTL lapses).
|
|
215
|
+
* - `max_attempts` — the attempt ceiling was already reached; the entry is deleted.
|
|
216
|
+
* - `ok` — an attempt was consumed; `entry` carries the updated entry (incl. the stored `code`).
|
|
217
|
+
*/
|
|
218
|
+
type ConsumeAttemptResult = {
|
|
219
|
+
status: 'not_found';
|
|
220
|
+
} | {
|
|
221
|
+
status: 'max_attempts';
|
|
222
|
+
} | {
|
|
223
|
+
status: 'ok';
|
|
224
|
+
entry: OtpEntry;
|
|
225
|
+
};
|
|
226
|
+
/**
|
|
227
|
+
* Outcome of a verification, as returned by `OtpService.verify()`.
|
|
228
|
+
*
|
|
229
|
+
* Note: an expired entry is reported as `not_found` — once a code's TTL lapses the
|
|
230
|
+
* entry is gone, so "missing" and "expired" are indistinguishable at the storage
|
|
231
|
+
* layer, and the catalog recommends not leaking the difference to the client.
|
|
232
|
+
*/
|
|
233
|
+
type OtpVerifyResult = {
|
|
234
|
+
valid: true;
|
|
235
|
+
} | {
|
|
236
|
+
valid: false;
|
|
237
|
+
reason: 'not_found';
|
|
238
|
+
} | {
|
|
239
|
+
valid: false;
|
|
240
|
+
reason: 'max_attempts';
|
|
241
|
+
} | {
|
|
242
|
+
valid: false;
|
|
243
|
+
reason: 'invalid_code';
|
|
244
|
+
remainingAttempts: number;
|
|
245
|
+
};
|
|
246
|
+
/**
|
|
247
|
+
* OTP storage.
|
|
248
|
+
*
|
|
249
|
+
* Implementations MUST:
|
|
250
|
+
* - make `consumeAttempt` **atomic** — the lookup + attempt increment is a single
|
|
251
|
+
* indivisible operation (Redis: a Lua script; in-memory: one synchronous
|
|
252
|
+
* read-modify-write). A plain `get`+`update` races and lets the `maxAttempts`
|
|
253
|
+
* brute-force limit be bypassed under concurrency;
|
|
254
|
+
* - make `tryAcquireCooldown` **atomic** — a check-and-set in one step (Redis:
|
|
255
|
+
* `SET NX EX`), so two concurrent generate/resend calls cannot both pass;
|
|
256
|
+
* - apply TTL — expired entries must not be returned by `get` / `consumeAttempt`;
|
|
257
|
+
* - scope keys by `(tenantId, recipient, purpose)` without cross-tenant collision;
|
|
258
|
+
* - never expose OTP codes in plaintext logs.
|
|
259
|
+
*
|
|
260
|
+
* The library does NOT normalize `recipient`: callers must pass a canonical value
|
|
261
|
+
* (e.g. `email.trim().toLowerCase()`); `'A@x.com'` and `'a@x.com'` map to distinct keys.
|
|
262
|
+
*/
|
|
263
|
+
interface IOtpStorage {
|
|
264
|
+
/**
|
|
265
|
+
* Creates or replaces an OTP entry (with its own TTL).
|
|
266
|
+
*
|
|
267
|
+
* @param tenantId - Tenant isolation scope.
|
|
268
|
+
* @param recipient - Pre-normalized recipient identifier (email, phone, userId — caller decides).
|
|
269
|
+
* @param purpose - OTP purpose (e.g. `'email_verification'`).
|
|
270
|
+
* @param entry - The entry to persist.
|
|
271
|
+
*/
|
|
272
|
+
set(tenantId: string, recipient: string, purpose: string, entry: OtpEntry): Promise<void>;
|
|
273
|
+
/**
|
|
274
|
+
* Reads an OTP entry. Returns `null` if it does not exist or has expired.
|
|
275
|
+
* Read-only — used by `getStatus()`. Verification MUST go through `consumeAttempt`.
|
|
276
|
+
*/
|
|
277
|
+
get(tenantId: string, recipient: string, purpose: string): Promise<OtpEntry | null>;
|
|
278
|
+
/**
|
|
279
|
+
* Atomic verification primitive — in one indivisible step: returns `not_found`
|
|
280
|
+
* when absent/expired; deletes the entry and returns `max_attempts` when the
|
|
281
|
+
* ceiling is reached; otherwise increments `attempts` (preserving TTL) and
|
|
282
|
+
* returns `ok` with the updated entry. The caller then constant-time-compares
|
|
283
|
+
* the guessed code against `entry.code`.
|
|
284
|
+
*
|
|
285
|
+
* MUST be atomic.
|
|
286
|
+
*/
|
|
287
|
+
consumeAttempt(tenantId: string, recipient: string, purpose: string): Promise<ConsumeAttemptResult>;
|
|
288
|
+
/**
|
|
289
|
+
* Updates an existing entry, preserving its remaining TTL. A no-op if the entry
|
|
290
|
+
* is gone (TTL expired). Used to mark `validated` / write `metadata` after a
|
|
291
|
+
* successful verify — never for the attempt counter (that is `consumeAttempt`).
|
|
292
|
+
*/
|
|
293
|
+
update(tenantId: string, recipient: string, purpose: string, entry: OtpEntry): Promise<void>;
|
|
294
|
+
/** Removes the OTP entry. Idempotent. */
|
|
295
|
+
delete(tenantId: string, recipient: string, purpose: string): Promise<void>;
|
|
296
|
+
/**
|
|
297
|
+
* Atomic cooldown acquire for `(tenant, recipient, purpose)`. Sets the cooldown
|
|
298
|
+
* key only if it does not already exist (Redis: `SET NX EX`). Returns `true`
|
|
299
|
+
* when acquired, `false` when a cooldown is already active. Acts as a
|
|
300
|
+
* short-lived lock around generate/resend.
|
|
301
|
+
*
|
|
302
|
+
* MUST be atomic.
|
|
303
|
+
*
|
|
304
|
+
* @param ttlSeconds - Cooldown duration in seconds.
|
|
305
|
+
*/
|
|
306
|
+
tryAcquireCooldown(tenantId: string, recipient: string, purpose: string, ttlSeconds: number): Promise<boolean>;
|
|
307
|
+
/** Remaining cooldown in seconds, or `0` when there is no active cooldown. */
|
|
308
|
+
getCooldown(tenantId: string, recipient: string, purpose: string): Promise<number>;
|
|
309
|
+
/**
|
|
310
|
+
* Clears the cooldown for `(tenant, recipient, purpose)`. Idempotent. Called when
|
|
311
|
+
* a delivery fails (so the user is not locked out) and on `consume()` (so a
|
|
312
|
+
* cancelled flow can restart immediately).
|
|
313
|
+
*/
|
|
314
|
+
clearCooldown(tenantId: string, recipient: string, purpose: string): Promise<void>;
|
|
315
|
+
/** Whether the storage is configured and ready. Used during module initialization. */
|
|
316
|
+
isConfigured(): boolean;
|
|
317
|
+
/** Storage name (e.g. `'redis'`, `'memory'`, `'dynamodb'`). */
|
|
318
|
+
readonly name: string;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* @fileoverview Push provider contract (`IPushProvider`) — declared, not yet served.
|
|
323
|
+
* @layer domain
|
|
324
|
+
*
|
|
325
|
+
* The contract is exported so consumers can plan their dispatch code paths against a
|
|
326
|
+
* stable shape. No `PushService` implements it, and `validateOptions` rejects a `push`
|
|
327
|
+
* channel at startup rather than letting it fail on the first send.
|
|
328
|
+
*/
|
|
329
|
+
/** Options for one push notification to send. */
|
|
330
|
+
interface PushSendOptions {
|
|
331
|
+
/** Device token(s). */
|
|
332
|
+
tokens: string | string[];
|
|
333
|
+
/** Notification title. */
|
|
334
|
+
title: string;
|
|
335
|
+
/** Notification body. */
|
|
336
|
+
body: string;
|
|
337
|
+
/** Arbitrary data payload read by the mobile client. */
|
|
338
|
+
data?: Record<string, string>;
|
|
339
|
+
/** Image URL. */
|
|
340
|
+
imageUrl?: string;
|
|
341
|
+
/** Sound (e.g. `'default'`, `'custom.caf'`). */
|
|
342
|
+
sound?: string;
|
|
343
|
+
/** Badge count (iOS). */
|
|
344
|
+
badge?: number;
|
|
345
|
+
/** Time-to-live in seconds. */
|
|
346
|
+
ttlSeconds?: number;
|
|
347
|
+
/** Delivery priority. */
|
|
348
|
+
priority?: 'high' | 'normal';
|
|
349
|
+
}
|
|
350
|
+
/** Per-token result of a push send. */
|
|
351
|
+
interface PushSendResult {
|
|
352
|
+
results: Array<{
|
|
353
|
+
token: string;
|
|
354
|
+
messageId?: string;
|
|
355
|
+
error?: string;
|
|
356
|
+
}>;
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Push notification provider.
|
|
360
|
+
*
|
|
361
|
+
* Intended implementations: FCM (Firebase), APN (Apple), Web Push (VAPID).
|
|
362
|
+
*/
|
|
363
|
+
interface IPushProvider {
|
|
364
|
+
/** Provider name (e.g. `'fcm'`). */
|
|
365
|
+
readonly name: string;
|
|
366
|
+
/** Whether the provider is configured and ready to send. */
|
|
367
|
+
isConfigured(): boolean;
|
|
368
|
+
/**
|
|
369
|
+
* Sends a push notification to one or more device tokens.
|
|
370
|
+
*
|
|
371
|
+
* @param options - The notification payload and target tokens.
|
|
372
|
+
* @returns Per-token send results.
|
|
373
|
+
* @throws Error When the send fails wholesale.
|
|
374
|
+
*/
|
|
375
|
+
send(options: PushSendOptions): Promise<PushSendResult>;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* @fileoverview SMS provider contract (`ISmsProvider`) — declared, not yet served.
|
|
380
|
+
* @layer domain
|
|
381
|
+
*
|
|
382
|
+
* The contract is exported so consumers can plan their dispatch code paths against a
|
|
383
|
+
* stable shape. No `SmsService` implements it, and `validateOptions` rejects an `sms`
|
|
384
|
+
* channel at startup rather than letting it fail on the first send.
|
|
385
|
+
*/
|
|
386
|
+
/** Options for one SMS to send. */
|
|
387
|
+
interface SmsSendOptions {
|
|
388
|
+
/** Recipient in E.164 format (e.g. `'+5511999998888'`). */
|
|
389
|
+
to: string;
|
|
390
|
+
/** Sender (E.164 or an alphanumeric sender id). */
|
|
391
|
+
from?: string;
|
|
392
|
+
/** Message body. */
|
|
393
|
+
body: string;
|
|
394
|
+
/** Provider-side tracking tags (not supported by every provider). */
|
|
395
|
+
tags?: ReadonlyArray<{
|
|
396
|
+
name: string;
|
|
397
|
+
value: string;
|
|
398
|
+
}>;
|
|
399
|
+
}
|
|
400
|
+
/** Result of a successful SMS send. */
|
|
401
|
+
interface SmsSendResult {
|
|
402
|
+
messageId: string;
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* SMS provider.
|
|
406
|
+
*
|
|
407
|
+
* Intended implementations: Twilio, AWS SNS, MessageBird, Vonage.
|
|
408
|
+
*/
|
|
409
|
+
interface ISmsProvider {
|
|
410
|
+
/** Provider name (e.g. `'twilio'`, `'sns'`). */
|
|
411
|
+
readonly name: string;
|
|
412
|
+
/** Whether the provider is configured and ready to send. */
|
|
413
|
+
isConfigured(): boolean;
|
|
414
|
+
/**
|
|
415
|
+
* Sends an SMS.
|
|
416
|
+
*
|
|
417
|
+
* @param options - The message envelope and body.
|
|
418
|
+
* @returns The provider's send result.
|
|
419
|
+
* @throws Error When the send fails.
|
|
420
|
+
*/
|
|
421
|
+
send(options: SmsSendOptions): Promise<SmsSendResult>;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* @fileoverview Public configuration surface for `BymaxNotificationModule`.
|
|
426
|
+
* @layer domain
|
|
427
|
+
*
|
|
428
|
+
* Declares the synchronous + async module options and every channel sub-interface.
|
|
429
|
+
* Each `provider`/`storage`/`renderer`/`repository` field accepts either a ready
|
|
430
|
+
* instance OR a class constructor — the module resolves the form at registration
|
|
431
|
+
* time (`useValue` vs `useClass`).
|
|
432
|
+
*/
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* A class constructor that yields `T`. The `never[]` parameter list makes any
|
|
436
|
+
* constructor assignable (parameters are contravariant), so the module can accept
|
|
437
|
+
* a bare class reference for adapters whose dependencies NestJS can resolve.
|
|
438
|
+
*/
|
|
439
|
+
type Newable<T> = new (...args: never[]) => T;
|
|
440
|
+
/**
|
|
441
|
+
* Minimal, framework-agnostic request shape used by `global.tenantIdResolver`.
|
|
442
|
+
* Compatible with both Express and Fastify request objects (both expose
|
|
443
|
+
* `headers`; `hostname` is present on Express and Fastify >= 4). Cast to your
|
|
444
|
+
* framework's request type inside the resolver.
|
|
445
|
+
*/
|
|
446
|
+
interface NotificationRequest {
|
|
447
|
+
headers: Record<string, string | string[] | undefined>;
|
|
448
|
+
hostname?: string;
|
|
449
|
+
}
|
|
450
|
+
/** Library-wide settings applied across channels unless overridden. */
|
|
451
|
+
interface GlobalOptions {
|
|
452
|
+
/** Namespace prefixed to every storage key. Default: `'notification'`. */
|
|
453
|
+
redisNamespace?: string;
|
|
454
|
+
/** Default template locale when the caller does not specify. Default: `'en'`. */
|
|
455
|
+
defaultLocale?: string;
|
|
456
|
+
/**
|
|
457
|
+
* Resolves the tenant id from the request. When provided, the module prefers
|
|
458
|
+
* this source over a tenant id passed in the body/argument — preventing tenant
|
|
459
|
+
* spoofing.
|
|
460
|
+
*/
|
|
461
|
+
tenantIdResolver?: (req: NotificationRequest) => string | Promise<string>;
|
|
462
|
+
}
|
|
463
|
+
/** Per-purpose OTP overrides (every field required when overriding). */
|
|
464
|
+
interface OtpPurposeConfig {
|
|
465
|
+
length: number;
|
|
466
|
+
codeType: 'numeric' | 'alpha' | 'alphanumeric';
|
|
467
|
+
ttlSeconds: number;
|
|
468
|
+
maxAttempts: number;
|
|
469
|
+
resendCooldownSeconds: number;
|
|
470
|
+
}
|
|
471
|
+
/** Email channel configuration. Omitted when the email channel is not used. */
|
|
472
|
+
interface EmailChannelOptions {
|
|
473
|
+
/** Send adapter (required). */
|
|
474
|
+
provider: IEmailProvider | Newable<IEmailProvider>;
|
|
475
|
+
/** Default `from` address (required, e.g. `'noreply@example.com'`). */
|
|
476
|
+
defaultFrom: string;
|
|
477
|
+
/** Default sender display name. */
|
|
478
|
+
defaultFromName?: string;
|
|
479
|
+
/** Template renderer. Default: `DefaultTemplateRenderer` (`{{var}}` interpolation). */
|
|
480
|
+
templateRenderer?: IEmailTemplateRenderer | Newable<IEmailTemplateRenderer>;
|
|
481
|
+
/** Default reply-to address. */
|
|
482
|
+
defaultReplyTo?: string;
|
|
483
|
+
/** Default tags attached to every email. */
|
|
484
|
+
defaultTags?: ReadonlyArray<{
|
|
485
|
+
name: string;
|
|
486
|
+
value: string;
|
|
487
|
+
}>;
|
|
488
|
+
/**
|
|
489
|
+
* Maximum total attachment size in bytes. `EmailService` sums attachment byte
|
|
490
|
+
* lengths and throws `EMAIL_ATTACHMENTS_TOO_LARGE` when exceeded.
|
|
491
|
+
* Default: `10_485_760` (10 MiB).
|
|
492
|
+
*/
|
|
493
|
+
maxAttachmentBytes?: number;
|
|
494
|
+
}
|
|
495
|
+
/** OTP channel configuration. Omitted when the OTP channel is not used. */
|
|
496
|
+
interface OtpChannelOptions {
|
|
497
|
+
/** Storage backend (required). Recommended default: `RedisOtpStorage`. */
|
|
498
|
+
storage: IOtpStorage | Newable<IOtpStorage>;
|
|
499
|
+
/** Default code length. Default: `6`. */
|
|
500
|
+
defaultLength?: number;
|
|
501
|
+
/** Default code charset. Default: `'numeric'`. */
|
|
502
|
+
defaultCodeType?: 'numeric' | 'alpha' | 'alphanumeric';
|
|
503
|
+
/** Default TTL in seconds. Default: `600`. */
|
|
504
|
+
defaultTtlSeconds?: number;
|
|
505
|
+
/** Default maximum verification attempts. Default: `5`. */
|
|
506
|
+
defaultMaxAttempts?: number;
|
|
507
|
+
/** Cooldown between resends of the same OTP. Default: `60`. */
|
|
508
|
+
resendCooldownSeconds?: number;
|
|
509
|
+
/** When `true`, `verify()` consumes (deletes) the OTP on success. Default: `false`. */
|
|
510
|
+
consumeOnVerify?: boolean;
|
|
511
|
+
/** Per-purpose overrides of the defaults above. */
|
|
512
|
+
perPurpose?: Record<string, Partial<OtpPurposeConfig>>;
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* SMS channel configuration.
|
|
516
|
+
*
|
|
517
|
+
* Declared so consumers can plan code paths against a stable shape; no service
|
|
518
|
+
* implements the channel and `validateOptions` rejects it at startup.
|
|
519
|
+
*/
|
|
520
|
+
interface SmsChannelOptions {
|
|
521
|
+
provider: ISmsProvider | Newable<ISmsProvider>;
|
|
522
|
+
defaultFrom?: string;
|
|
523
|
+
resendCooldownSeconds?: number;
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* Push channel configuration.
|
|
527
|
+
*
|
|
528
|
+
* Declared so consumers can plan code paths against a stable shape; no service
|
|
529
|
+
* implements the channel and `validateOptions` rejects it at startup.
|
|
530
|
+
*/
|
|
531
|
+
interface PushChannelOptions {
|
|
532
|
+
provider: IPushProvider | Newable<IPushProvider>;
|
|
533
|
+
defaultTtlSeconds?: number;
|
|
534
|
+
}
|
|
535
|
+
/** Audit-log configuration. Omitted when no audit sink is wired. */
|
|
536
|
+
interface AuditOptions {
|
|
537
|
+
/** Log repository (required). */
|
|
538
|
+
repository: INotificationLogRepository | Newable<INotificationLogRepository>;
|
|
539
|
+
/** When `true`, audit failures do not propagate to the caller. Default: `true`. */
|
|
540
|
+
swallowErrors?: boolean;
|
|
541
|
+
/**
|
|
542
|
+
* Transforms the recipient before it is written to the audit entry — for PII
|
|
543
|
+
* minimization (e.g. `'jane@acme.com'` -> `'j***@acme.com'`). When `to` is an
|
|
544
|
+
* array, the mask is applied to each element and joined with `', '`.
|
|
545
|
+
* Default: identity (recipient stored verbatim).
|
|
546
|
+
*/
|
|
547
|
+
maskRecipient?: (recipient: string) => string;
|
|
548
|
+
}
|
|
549
|
+
/** Top-level synchronous module options passed to `BymaxNotificationModule.forRoot`. */
|
|
550
|
+
interface BymaxNotificationModuleOptions {
|
|
551
|
+
/** Library-wide settings. */
|
|
552
|
+
global?: GlobalOptions;
|
|
553
|
+
/** Email channel — registered only when present. */
|
|
554
|
+
email?: EmailChannelOptions;
|
|
555
|
+
/** OTP channel — registered only when present. */
|
|
556
|
+
otp?: OtpChannelOptions;
|
|
557
|
+
/** SMS channel — declared; rejected at startup. */
|
|
558
|
+
sms?: SmsChannelOptions;
|
|
559
|
+
/** Push channel — declared; rejected at startup. */
|
|
560
|
+
push?: PushChannelOptions;
|
|
561
|
+
/** Audit log — defaults to a no-op sink when absent. */
|
|
562
|
+
audit?: AuditOptions;
|
|
563
|
+
}
|
|
564
|
+
/**
|
|
565
|
+
* Factory interface for the `useClass` / `useExisting` async pattern.
|
|
566
|
+
*
|
|
567
|
+
* Reserved — only `useFactory` is wired today.
|
|
568
|
+
*/
|
|
569
|
+
interface BymaxNotificationModuleOptionsFactory {
|
|
570
|
+
createNotificationOptions(): BymaxNotificationModuleOptions | Promise<BymaxNotificationModuleOptions>;
|
|
571
|
+
}
|
|
572
|
+
/**
|
|
573
|
+
* Asynchronous module options passed to `BymaxNotificationModule.forRootAsync`.
|
|
574
|
+
*
|
|
575
|
+
* Only the `useFactory` + `inject` form is supported; `useClass`/`useExisting` are
|
|
576
|
+
* reserved and rejected at registration.
|
|
577
|
+
*/
|
|
578
|
+
interface BymaxNotificationModuleAsyncOptions {
|
|
579
|
+
/** Modules to import so the factory's injected dependencies are available. */
|
|
580
|
+
imports?: ModuleMetadata['imports'];
|
|
581
|
+
/** Providers injected into `useFactory`, in order. */
|
|
582
|
+
inject?: FactoryProvider['inject'];
|
|
583
|
+
/**
|
|
584
|
+
* Builds the module options at runtime. Injected dependencies (per `inject`)
|
|
585
|
+
* arrive as positional arguments.
|
|
586
|
+
*/
|
|
587
|
+
useFactory: (...args: never[]) => BymaxNotificationModuleOptions | Promise<BymaxNotificationModuleOptions>;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
/**
|
|
591
|
+
* @fileoverview The `BymaxNotificationModule` dynamic module.
|
|
592
|
+
* @layer infrastructure
|
|
593
|
+
*
|
|
594
|
+
* Registers only the channels the consumer configures (opt-in), wiring each
|
|
595
|
+
* provider/storage/renderer/repository under a `Symbol` DI token. `forRoot` is
|
|
596
|
+
* fully synchronous and registers a channel's token only when that channel is
|
|
597
|
+
* present. `forRootAsync` resolves the consumer options through DI: because the
|
|
598
|
+
* configured channels are unknown until the factory runs, it registers every
|
|
599
|
+
* channel token (an absent channel resolves to `null`) and registers the channel
|
|
600
|
+
* services as factories that resolve to `undefined` when their channel is absent —
|
|
601
|
+
* mirroring the sync rule, so `NotificationService` reports the channel disabled.
|
|
602
|
+
*/
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* Multi-channel notification module.
|
|
606
|
+
*
|
|
607
|
+
* @example
|
|
608
|
+
* ```ts
|
|
609
|
+
* BymaxNotificationModule.forRoot({
|
|
610
|
+
* email: { provider: new ResendEmailProvider({ apiKey }), defaultFrom: 'noreply@acme.com' }
|
|
611
|
+
* })
|
|
612
|
+
* ```
|
|
613
|
+
*/
|
|
614
|
+
declare class BymaxNotificationModule {
|
|
615
|
+
private static readonly logger;
|
|
616
|
+
/**
|
|
617
|
+
* Registers the module synchronously from static options.
|
|
618
|
+
*
|
|
619
|
+
* @param options - The channel configuration; at least one channel is required.
|
|
620
|
+
* @returns A global `DynamicModule` exposing only the configured channels' tokens.
|
|
621
|
+
* @throws Error When validation fails (no channel, malformed channel, or an unsupported channel).
|
|
622
|
+
*/
|
|
623
|
+
static forRoot(options: BymaxNotificationModuleOptions): DynamicModule;
|
|
624
|
+
/**
|
|
625
|
+
* Registers the module with options resolved at runtime through DI.
|
|
626
|
+
*
|
|
627
|
+
* Only the `useFactory` + `inject` form is supported — `useClass`/`useExisting`
|
|
628
|
+
* are rejected with an explicit error. The factory runs once (under an internal
|
|
629
|
+
* token); every channel token and all three services derive from its result, so
|
|
630
|
+
* a `ConfigService`-driven async bootstrap wires the same graph as `forRoot`.
|
|
631
|
+
*
|
|
632
|
+
* @param asyncOptions - The async options factory and its dependencies.
|
|
633
|
+
* @returns A global `DynamicModule` exposing the resolved options token, every
|
|
634
|
+
* channel token, and the three services.
|
|
635
|
+
* @throws Error When `useClass`/`useExisting` is supplied, or `useFactory` is missing.
|
|
636
|
+
*/
|
|
637
|
+
static forRootAsync(asyncOptions: BymaxNotificationModuleAsyncOptions): DynamicModule;
|
|
638
|
+
/**
|
|
639
|
+
* Builds the async channel-service providers, mirroring the conditional wiring of
|
|
640
|
+
* the sync path. `EmailService`/`OtpService` are factory providers that resolve to
|
|
641
|
+
* `undefined` when their required channel dependency (the email provider / OTP
|
|
642
|
+
* storage token) is absent, so the `@Optional()`-injected `NotificationService`
|
|
643
|
+
* keeps throwing `CHANNEL_DISABLED` for that channel and `getEnabledChannels()`
|
|
644
|
+
* omits it. `NotificationService` is always registered.
|
|
645
|
+
*/
|
|
646
|
+
private static buildAsyncServiceProviders;
|
|
647
|
+
/**
|
|
648
|
+
* Builds the async channel-token factories. Each derives from the validated raw
|
|
649
|
+
* options under {@link RAW_NOTIFICATION_OPTIONS}: an unconfigured email/OTP token
|
|
650
|
+
* resolves to `null` (the owning service guards against it), the audit token
|
|
651
|
+
* defaults to {@link NoOpNotificationLogRepository}, and the renderer defaults to
|
|
652
|
+
* {@link DefaultTemplateRenderer}.
|
|
653
|
+
*/
|
|
654
|
+
private static buildAsyncTokenProviders;
|
|
655
|
+
/** Assembles the provider list for the configured channels. */
|
|
656
|
+
private static buildProviders;
|
|
657
|
+
/**
|
|
658
|
+
* Builds the channel service providers. `EmailService`/`OtpService` are
|
|
659
|
+
* registered only when their channel is configured; `NotificationService` is
|
|
660
|
+
* always registered (it injects the channel services with `@Optional()`).
|
|
661
|
+
*/
|
|
662
|
+
private static buildServiceProviders;
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/**
|
|
666
|
+
* @fileoverview Resolution of module options into the frozen runtime shape.
|
|
667
|
+
* @layer application
|
|
668
|
+
*
|
|
669
|
+
* `resolveOptions` merges consumer options with the channel defaults and publishes
|
|
670
|
+
* `ResolvedNotificationOptions` under `BYMAX_NOTIFICATION_OPTIONS` — the value every
|
|
671
|
+
* service injects. Channel sections are omitted when the consumer did not configure
|
|
672
|
+
* them, enabling `if (resolved.email)` narrowing; the result is deep-frozen so a
|
|
673
|
+
* service cannot mutate shared config at runtime.
|
|
674
|
+
*
|
|
675
|
+
* Provider/storage/renderer/repository instances are NOT nested here — they are
|
|
676
|
+
* registered under their own DI tokens, keeping this object pure scalar config.
|
|
677
|
+
*/
|
|
678
|
+
|
|
679
|
+
/** Resolved global section — always present. */
|
|
680
|
+
interface ResolvedGlobalOptions {
|
|
681
|
+
redisNamespace: string;
|
|
682
|
+
defaultLocale: string;
|
|
683
|
+
tenantIdResolver?: (req: NotificationRequest) => string | Promise<string>;
|
|
684
|
+
}
|
|
685
|
+
/** Resolved email section — present only when the email channel is configured. */
|
|
686
|
+
interface ResolvedEmailOptions {
|
|
687
|
+
defaultFrom: string;
|
|
688
|
+
defaultFromName?: string;
|
|
689
|
+
defaultReplyTo?: string;
|
|
690
|
+
defaultTags: ReadonlyArray<{
|
|
691
|
+
name: string;
|
|
692
|
+
value: string;
|
|
693
|
+
}>;
|
|
694
|
+
maxAttachmentBytes: number;
|
|
695
|
+
}
|
|
696
|
+
/** Resolved OTP section — present only when the OTP channel is configured. */
|
|
697
|
+
interface ResolvedOtpOptions {
|
|
698
|
+
defaultLength: number;
|
|
699
|
+
defaultCodeType: 'numeric' | 'alpha' | 'alphanumeric';
|
|
700
|
+
defaultTtlSeconds: number;
|
|
701
|
+
defaultMaxAttempts: number;
|
|
702
|
+
resendCooldownSeconds: number;
|
|
703
|
+
consumeOnVerify: boolean;
|
|
704
|
+
/** Per-purpose overrides, each fully resolved against the OTP defaults. */
|
|
705
|
+
perPurpose: Record<string, OtpPurposeConfig>;
|
|
706
|
+
/** Effective config for a purpose: the resolved `perPurpose[purpose]`, or the OTP defaults. */
|
|
707
|
+
resolveForPurpose(purpose: string): OtpPurposeConfig;
|
|
708
|
+
}
|
|
709
|
+
/** Resolved audit section — always present; the no-op sink obeys these settings too. */
|
|
710
|
+
interface ResolvedAuditOptions {
|
|
711
|
+
swallowErrors: boolean;
|
|
712
|
+
maskRecipient: (recipient: string) => string;
|
|
713
|
+
}
|
|
714
|
+
/** The fully resolved, frozen module options injected under `BYMAX_NOTIFICATION_OPTIONS`. */
|
|
715
|
+
interface ResolvedNotificationOptions {
|
|
716
|
+
global: ResolvedGlobalOptions;
|
|
717
|
+
email?: ResolvedEmailOptions;
|
|
718
|
+
otp?: ResolvedOtpOptions;
|
|
719
|
+
audit: ResolvedAuditOptions;
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/**
|
|
723
|
+
* @fileoverview Public transactional email service.
|
|
724
|
+
* @layer application
|
|
725
|
+
*
|
|
726
|
+
* Wraps the configured `IEmailProvider`, adding: default header application
|
|
727
|
+
* (`from` / `fromName` / `replyTo` / `tags`), an attachment-size guard, optional
|
|
728
|
+
* template rendering via `IEmailTemplateRenderer` (the renderer owns HTML escaping
|
|
729
|
+
* during `sendTemplate`), and fire-and-forget audit logging with recipient masking.
|
|
730
|
+
*
|
|
731
|
+
* Security: the email body is never logged or audited; on a provider failure the
|
|
732
|
+
* underlying error reaches the audit log only — the caller receives the generic
|
|
733
|
+
* `EMAIL_SEND_FAILED`. OTP codes ride inside the body, never in audit metadata.
|
|
734
|
+
*/
|
|
735
|
+
|
|
736
|
+
/** An email tag pair. */
|
|
737
|
+
type EmailTag$1 = {
|
|
738
|
+
name: string;
|
|
739
|
+
value: string;
|
|
740
|
+
};
|
|
741
|
+
/** Input for {@link EmailService.send} — the caller supplies the rendered body. */
|
|
742
|
+
interface EmailSendInput {
|
|
743
|
+
tenantId: string;
|
|
744
|
+
to: string | string[];
|
|
745
|
+
subject: string;
|
|
746
|
+
html: string;
|
|
747
|
+
text?: string;
|
|
748
|
+
from?: string;
|
|
749
|
+
fromName?: string;
|
|
750
|
+
replyTo?: string;
|
|
751
|
+
cc?: string | string[];
|
|
752
|
+
bcc?: string | string[];
|
|
753
|
+
tags?: ReadonlyArray<EmailTag$1>;
|
|
754
|
+
attachments?: EmailSendOptions['attachments'];
|
|
755
|
+
/** Associated user id, recorded in the audit entry. */
|
|
756
|
+
userId?: string;
|
|
757
|
+
}
|
|
758
|
+
/** Input for {@link EmailService.sendTemplate} — the renderer produces the body. */
|
|
759
|
+
interface EmailSendTemplateInput {
|
|
760
|
+
tenantId: string;
|
|
761
|
+
to: string | string[];
|
|
762
|
+
template: string;
|
|
763
|
+
data: Record<string, unknown>;
|
|
764
|
+
locale?: string;
|
|
765
|
+
from?: string;
|
|
766
|
+
fromName?: string;
|
|
767
|
+
replyTo?: string;
|
|
768
|
+
tags?: ReadonlyArray<EmailTag$1>;
|
|
769
|
+
userId?: string;
|
|
770
|
+
}
|
|
771
|
+
/** Transactional email service. */
|
|
772
|
+
declare class EmailService {
|
|
773
|
+
private readonly options;
|
|
774
|
+
private readonly provider;
|
|
775
|
+
private readonly renderer;
|
|
776
|
+
private readonly auditLog;
|
|
777
|
+
/**
|
|
778
|
+
* @param options - The resolved, frozen module options.
|
|
779
|
+
* @param provider - The configured email send provider.
|
|
780
|
+
* @param renderer - The configured template renderer.
|
|
781
|
+
* @param auditLog - The audit-log repository (no-op when none configured).
|
|
782
|
+
*/
|
|
783
|
+
constructor(options: ResolvedNotificationOptions, provider: IEmailProvider, renderer: IEmailTemplateRenderer, auditLog: INotificationLogRepository);
|
|
784
|
+
/**
|
|
785
|
+
* Whether the email channel is configured and its provider is ready.
|
|
786
|
+
*
|
|
787
|
+
* @returns `true` when both hold.
|
|
788
|
+
*/
|
|
789
|
+
isConfigured(): boolean;
|
|
790
|
+
/**
|
|
791
|
+
* Sends an email whose subject/html/text the caller already produced.
|
|
792
|
+
*
|
|
793
|
+
* @param input - The message envelope and rendered body.
|
|
794
|
+
* @returns The provider's message id.
|
|
795
|
+
* @throws NotificationException `EMAIL_PROVIDER_NOT_CONFIGURED`, `EMAIL_ATTACHMENTS_TOO_LARGE`,
|
|
796
|
+
* `EMAIL_SEND_FAILED`, or `AUDIT_LOG_FAILED` (only when `audit.swallowErrors` is `false`).
|
|
797
|
+
*/
|
|
798
|
+
send(input: EmailSendInput): Promise<{
|
|
799
|
+
messageId: string;
|
|
800
|
+
}>;
|
|
801
|
+
/**
|
|
802
|
+
* Renders a template (with an `en` fallback) and sends the result.
|
|
803
|
+
*
|
|
804
|
+
* @param input - The template name, data, and envelope.
|
|
805
|
+
* @returns The provider's message id.
|
|
806
|
+
* @throws NotificationException `TEMPLATE_NOT_FOUND` (no template for the locale nor `en`),
|
|
807
|
+
* `TEMPLATE_RENDER_FAILED` (the renderer threw), plus anything {@link EmailService.send} throws.
|
|
808
|
+
*/
|
|
809
|
+
sendTemplate(input: EmailSendTemplateInput): Promise<{
|
|
810
|
+
messageId: string;
|
|
811
|
+
}>;
|
|
812
|
+
/** Returns the resolved email options or throws when the channel is not configured. */
|
|
813
|
+
private requireEmailOptions;
|
|
814
|
+
/** Throws `EMAIL_ATTACHMENTS_TOO_LARGE` when the attachments exceed the byte budget. */
|
|
815
|
+
private guardAttachmentSize;
|
|
816
|
+
/** Applies channel defaults and concatenates default + caller tags. */
|
|
817
|
+
private buildSendOptions;
|
|
818
|
+
/** Picks the locale that has a template, falling back to `en`, else throws `TEMPLATE_NOT_FOUND`. */
|
|
819
|
+
private resolveTemplateLocale;
|
|
820
|
+
/** Renders the template, mapping a renderer failure to `TEMPLATE_RENDER_FAILED`. */
|
|
821
|
+
private renderTemplate;
|
|
822
|
+
/** Builds an audit entry with the recipient already masked. */
|
|
823
|
+
private auditEntry;
|
|
824
|
+
/** Writes an audit entry, swallowing failures unless `audit.swallowErrors` is `false`. */
|
|
825
|
+
private audit;
|
|
826
|
+
/** Masks the recipient(s) per `audit.maskRecipient`, joining an array with `', '`. */
|
|
827
|
+
private maskRecipients;
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/**
|
|
831
|
+
* @fileoverview Public OTP lifecycle service — the library's security core.
|
|
832
|
+
* @layer application
|
|
833
|
+
*
|
|
834
|
+
* Two atomic guarantees are enforced here and never weakened:
|
|
835
|
+
*
|
|
836
|
+
* 1. **Atomic attempt counting** — the per-OTP attempt counter is mutated ONLY by
|
|
837
|
+
* `storage.consumeAttempt` (a Redis Lua script / a single synchronous Map op).
|
|
838
|
+
* The service never does its own `get`+`update` to increment.
|
|
839
|
+
* 2. **Atomic cooldown with release-on-failure** — `generate` claims the resend
|
|
840
|
+
* cooldown with `storage.tryAcquireCooldown` (`SET NX EX`) BEFORE issuing a code,
|
|
841
|
+
* and releases it (plus deletes the orphan OTP) if persistence OR delivery fails,
|
|
842
|
+
* so a storage outage or a bounced email never locks the user out and concurrent
|
|
843
|
+
* resends cannot both reset the counter.
|
|
844
|
+
*
|
|
845
|
+
* The plaintext code never leaves storage: it is never logged, never placed in an
|
|
846
|
+
* audit entry, and `getStatus` never returns it. Verification compares in constant
|
|
847
|
+
* time via `safeCompare`.
|
|
848
|
+
*/
|
|
849
|
+
|
|
850
|
+
/** Common `(tenant, recipient, purpose)` reference shared by every OTP operation. */
|
|
851
|
+
interface OtpRecipientRef {
|
|
852
|
+
tenantId: string;
|
|
853
|
+
recipient: string;
|
|
854
|
+
purpose: string;
|
|
855
|
+
/** Associated user id, recorded in the audit entry. */
|
|
856
|
+
userId?: string;
|
|
857
|
+
}
|
|
858
|
+
/** Input for {@link OtpService.generate} / {@link OtpService.resend}. */
|
|
859
|
+
interface OtpGenerateInput extends OtpRecipientRef {
|
|
860
|
+
/** `'email'` delivers via {@link EmailService}; `'manual'` lets the caller deliver. */
|
|
861
|
+
deliverVia?: 'email' | 'manual';
|
|
862
|
+
/** Template to render for email delivery. Default: `'otp_code'`. */
|
|
863
|
+
emailTemplate?: string;
|
|
864
|
+
/** Extra template variables merged under the auto-injected `{ code, expiresInMinutes, purpose }`. */
|
|
865
|
+
emailData?: Record<string, unknown>;
|
|
866
|
+
/** Email locale. */
|
|
867
|
+
locale?: string;
|
|
868
|
+
}
|
|
869
|
+
/** Input for {@link OtpService.verify}. */
|
|
870
|
+
interface OtpVerifyInput extends OtpRecipientRef {
|
|
871
|
+
code: string;
|
|
872
|
+
}
|
|
873
|
+
/** Input for {@link OtpService.consume}. */
|
|
874
|
+
type OtpConsumeInput = OtpRecipientRef;
|
|
875
|
+
/** Input for {@link OtpService.getStatus}. */
|
|
876
|
+
interface OtpStatusInput {
|
|
877
|
+
tenantId: string;
|
|
878
|
+
recipient: string;
|
|
879
|
+
purpose: string;
|
|
880
|
+
}
|
|
881
|
+
/** Result of a successful {@link OtpService.generate}. */
|
|
882
|
+
interface OtpGenerateResult {
|
|
883
|
+
expiresAt: number;
|
|
884
|
+
cooldownSeconds: number;
|
|
885
|
+
}
|
|
886
|
+
/** Result of {@link OtpService.getStatus} — never carries the plaintext code. */
|
|
887
|
+
interface OtpStatusResult {
|
|
888
|
+
exists: boolean;
|
|
889
|
+
expiresAt?: number;
|
|
890
|
+
attempts?: number;
|
|
891
|
+
maxAttempts?: number;
|
|
892
|
+
cooldownSeconds: number;
|
|
893
|
+
validated?: boolean;
|
|
894
|
+
}
|
|
895
|
+
/** OTP generation, verification, consumption, and status. */
|
|
896
|
+
declare class OtpService {
|
|
897
|
+
private readonly options;
|
|
898
|
+
private readonly storage;
|
|
899
|
+
private readonly auditLog;
|
|
900
|
+
private readonly emailService?;
|
|
901
|
+
/**
|
|
902
|
+
* @param options - The resolved, frozen module options.
|
|
903
|
+
* @param storage - The configured OTP storage.
|
|
904
|
+
* @param auditLog - The audit-log repository (no-op when none configured).
|
|
905
|
+
* @param emailService - The email service; present only when the email channel is configured.
|
|
906
|
+
*/
|
|
907
|
+
constructor(options: ResolvedNotificationOptions, storage: IOtpStorage, auditLog: INotificationLogRepository, emailService?: EmailService | undefined);
|
|
908
|
+
/**
|
|
909
|
+
* Whether the OTP channel is configured and its storage is ready.
|
|
910
|
+
*
|
|
911
|
+
* @returns `true` when both hold.
|
|
912
|
+
*/
|
|
913
|
+
isConfigured(): boolean;
|
|
914
|
+
/**
|
|
915
|
+
* Generates, persists, and (optionally) delivers an OTP by email.
|
|
916
|
+
*
|
|
917
|
+
* @param input - The recipient, purpose, and delivery options.
|
|
918
|
+
* @returns The expiry timestamp and the resend cooldown length.
|
|
919
|
+
* @throws NotificationException `OTP_STORAGE_NOT_CONFIGURED`, `OTP_COOLDOWN_ACTIVE`,
|
|
920
|
+
* `OTP_EMAIL_DELIVERY_NOT_CONFIGURED`, or rethrows a persistence/delivery error after
|
|
921
|
+
* releasing the cooldown lock.
|
|
922
|
+
*/
|
|
923
|
+
generate(input: OtpGenerateInput): Promise<OtpGenerateResult>;
|
|
924
|
+
/**
|
|
925
|
+
* Verifies a guessed code against the stored OTP (constant-time).
|
|
926
|
+
*
|
|
927
|
+
* @param input - The recipient, purpose, and guessed code.
|
|
928
|
+
* @returns The discriminated verification result.
|
|
929
|
+
* @throws NotificationException `OTP_STORAGE_NOT_CONFIGURED` when the channel is absent.
|
|
930
|
+
*/
|
|
931
|
+
verify(input: OtpVerifyInput): Promise<OtpVerifyResult>;
|
|
932
|
+
/**
|
|
933
|
+
* Deletes an OTP and clears its resend cooldown. Idempotent.
|
|
934
|
+
*
|
|
935
|
+
* @param input - The recipient and purpose.
|
|
936
|
+
* @throws NotificationException `OTP_STORAGE_NOT_CONFIGURED` when the channel is absent.
|
|
937
|
+
*/
|
|
938
|
+
consume(input: OtpConsumeInput): Promise<void>;
|
|
939
|
+
/**
|
|
940
|
+
* Explicit resend — a functional alias of {@link OtpService.generate}.
|
|
941
|
+
*
|
|
942
|
+
* @param input - The recipient, purpose, and delivery options.
|
|
943
|
+
* @returns The expiry timestamp and the resend cooldown length.
|
|
944
|
+
*/
|
|
945
|
+
resend(input: OtpGenerateInput): Promise<OtpGenerateResult>;
|
|
946
|
+
/**
|
|
947
|
+
* Returns the current OTP status without ever exposing the plaintext code.
|
|
948
|
+
*
|
|
949
|
+
* @param input - The recipient and purpose.
|
|
950
|
+
* @returns Existence, expiry, attempt counters, validation flag, and cooldown.
|
|
951
|
+
*/
|
|
952
|
+
getStatus(input: OtpStatusInput): Promise<OtpStatusResult>;
|
|
953
|
+
/** Acquires the cooldown lock or throws `OTP_COOLDOWN_ACTIVE` with retry hints. */
|
|
954
|
+
private acquireCooldownOrThrow;
|
|
955
|
+
/**
|
|
956
|
+
* Persists the OTP then delivers it, releasing the cooldown lock (and deleting the
|
|
957
|
+
* orphan entry) if EITHER step fails — so a storage outage or a bounced email can
|
|
958
|
+
* never leave the recipient locked out behind a cooldown with no live code. The
|
|
959
|
+
* plaintext code is never placed in the failure audit entry. The original typed
|
|
960
|
+
* error is re-thrown after the lock is released.
|
|
961
|
+
*/
|
|
962
|
+
private persistAndDeliver;
|
|
963
|
+
/** Delivers the code by email when requested; throws on failure (release is handled by the caller). */
|
|
964
|
+
private deliverOtp;
|
|
965
|
+
/** Clears the cooldown and deletes the OTP — used to undo a failed delivery. */
|
|
966
|
+
private releaseOtp;
|
|
967
|
+
/** Builds the OTP email payload with the auto-injected `{ code, expiresInMinutes, purpose }`. */
|
|
968
|
+
private buildOtpEmail;
|
|
969
|
+
/** Finalizes a correct verification: consume-and-clear, or mark `validated`. */
|
|
970
|
+
private finalizeVerifySuccess;
|
|
971
|
+
/** Returns the resolved OTP options or throws `OTP_STORAGE_NOT_CONFIGURED`. */
|
|
972
|
+
private requireOtpOptions;
|
|
973
|
+
/** Builds an OTP audit entry with the recipient masked and never the code. */
|
|
974
|
+
private otpAuditEntry;
|
|
975
|
+
/** Writes an audit entry, swallowing failures unless `audit.swallowErrors` is `false`. */
|
|
976
|
+
private audit;
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
/**
|
|
980
|
+
* @fileoverview Channel-agnostic notification façade.
|
|
981
|
+
* @layer application
|
|
982
|
+
*
|
|
983
|
+
* A uniform `dispatch({ channel, tenantId, payload })` API over the per-channel
|
|
984
|
+
* services, plus throwing accessors (`getEmail` / `getOtp`) and channel discovery
|
|
985
|
+
* (`getEnabledChannels`). Channel services are `@Optional()`: a channel that was
|
|
986
|
+
* not configured is simply absent, and dispatching to it throws `CHANNEL_DISABLED`.
|
|
987
|
+
*/
|
|
988
|
+
|
|
989
|
+
/** An email tag pair. */
|
|
990
|
+
type EmailTag = {
|
|
991
|
+
name: string;
|
|
992
|
+
value: string;
|
|
993
|
+
};
|
|
994
|
+
/** Email dispatch payload — either a `template` (+ `data`) or a raw `subject` + `html`. */
|
|
995
|
+
interface EmailDispatchPayload {
|
|
996
|
+
to: string | string[];
|
|
997
|
+
template?: string;
|
|
998
|
+
data?: Record<string, unknown>;
|
|
999
|
+
locale?: string;
|
|
1000
|
+
subject?: string;
|
|
1001
|
+
html?: string;
|
|
1002
|
+
text?: string;
|
|
1003
|
+
from?: string;
|
|
1004
|
+
fromName?: string;
|
|
1005
|
+
replyTo?: string;
|
|
1006
|
+
tags?: ReadonlyArray<EmailTag>;
|
|
1007
|
+
userId?: string;
|
|
1008
|
+
}
|
|
1009
|
+
/** OTP dispatch payload — `action` selects generate (default) / verify / consume. */
|
|
1010
|
+
interface OtpDispatchPayload {
|
|
1011
|
+
recipient: string;
|
|
1012
|
+
purpose: string;
|
|
1013
|
+
action?: 'generate' | 'verify' | 'consume';
|
|
1014
|
+
/** Required when `action === 'verify'`. */
|
|
1015
|
+
code?: string;
|
|
1016
|
+
deliverVia?: 'email' | 'manual';
|
|
1017
|
+
emailTemplate?: string;
|
|
1018
|
+
emailData?: Record<string, unknown>;
|
|
1019
|
+
locale?: string;
|
|
1020
|
+
userId?: string;
|
|
1021
|
+
}
|
|
1022
|
+
/** Discriminated dispatch input, one variant per channel. */
|
|
1023
|
+
type DispatchInput = {
|
|
1024
|
+
channel: 'email';
|
|
1025
|
+
tenantId: string;
|
|
1026
|
+
payload: EmailDispatchPayload;
|
|
1027
|
+
} | {
|
|
1028
|
+
channel: 'otp';
|
|
1029
|
+
tenantId: string;
|
|
1030
|
+
payload: OtpDispatchPayload;
|
|
1031
|
+
};
|
|
1032
|
+
/** Discriminated dispatch result, one variant per channel. */
|
|
1033
|
+
type DispatchResult = {
|
|
1034
|
+
channel: 'email';
|
|
1035
|
+
messageId: string;
|
|
1036
|
+
} | {
|
|
1037
|
+
channel: 'otp';
|
|
1038
|
+
result: OtpGenerateResult | OtpVerifyResult | void;
|
|
1039
|
+
};
|
|
1040
|
+
/** Uniform façade over the configured channel services. */
|
|
1041
|
+
declare class NotificationService {
|
|
1042
|
+
private readonly emailService?;
|
|
1043
|
+
private readonly otpService?;
|
|
1044
|
+
/**
|
|
1045
|
+
* @param emailService - The email service, present only when the email channel is configured.
|
|
1046
|
+
* @param otpService - The OTP service, present only when the OTP channel is configured.
|
|
1047
|
+
*/
|
|
1048
|
+
constructor(emailService?: EmailService | undefined, otpService?: OtpService | undefined);
|
|
1049
|
+
/**
|
|
1050
|
+
* Dispatches a notification to the channel named in `input`.
|
|
1051
|
+
*
|
|
1052
|
+
* @param input - The channel-discriminated dispatch request.
|
|
1053
|
+
* @returns The channel-discriminated result.
|
|
1054
|
+
* @throws NotificationException `CHANNEL_DISABLED` (channel not configured) or
|
|
1055
|
+
* `EMAIL_MISSING_BODY` (email payload has neither a template nor subject+html).
|
|
1056
|
+
*/
|
|
1057
|
+
dispatch(input: DispatchInput): Promise<DispatchResult>;
|
|
1058
|
+
/**
|
|
1059
|
+
* Lists the channels whose service is present and reports itself configured.
|
|
1060
|
+
*
|
|
1061
|
+
* @returns The enabled channels.
|
|
1062
|
+
*/
|
|
1063
|
+
getEnabledChannels(): NotificationChannel[];
|
|
1064
|
+
/**
|
|
1065
|
+
* Returns the email service or throws when the email channel is not enabled.
|
|
1066
|
+
*
|
|
1067
|
+
* @returns The email service.
|
|
1068
|
+
* @throws NotificationException `CHANNEL_DISABLED` when email is not configured.
|
|
1069
|
+
*/
|
|
1070
|
+
getEmail(): EmailService;
|
|
1071
|
+
/**
|
|
1072
|
+
* Returns the OTP service or throws when the OTP channel is not enabled.
|
|
1073
|
+
*
|
|
1074
|
+
* @returns The OTP service.
|
|
1075
|
+
* @throws NotificationException `CHANNEL_DISABLED` when OTP is not configured.
|
|
1076
|
+
*/
|
|
1077
|
+
getOtp(): OtpService;
|
|
1078
|
+
/** Routes an email dispatch to `sendTemplate` (template) or `send` (raw body). */
|
|
1079
|
+
private dispatchEmail;
|
|
1080
|
+
/** Routes an OTP dispatch by `action`, defaulting to `generate`. */
|
|
1081
|
+
private dispatchOtp;
|
|
1082
|
+
/** Builds the `sendTemplate` input from a resolved template name and payload. */
|
|
1083
|
+
private toTemplateInput;
|
|
1084
|
+
/** Builds the raw `send` input from a resolved subject/html and payload. */
|
|
1085
|
+
private toSendInput;
|
|
1086
|
+
/** The optional envelope fields shared by both email paths. */
|
|
1087
|
+
private commonEmailFields;
|
|
1088
|
+
/** Builds the `generate` input from a reference and an OTP dispatch payload. */
|
|
1089
|
+
private toGenerateInput;
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
/**
|
|
1093
|
+
* @fileoverview Opt-in audit interceptor for `NotificationService.dispatch` calls.
|
|
1094
|
+
* @layer infrastructure
|
|
1095
|
+
*
|
|
1096
|
+
* Records one audit entry per intercepted dispatch — `verb: 'sent'` on success,
|
|
1097
|
+
* `verb: 'failed'` (with the error message) on rejection, then re-throws. The
|
|
1098
|
+
* tenant id is taken from `global.tenantIdResolver(request)` when configured,
|
|
1099
|
+
* which OVERRIDES any `tenantId` carried in the dispatch payload — closing the
|
|
1100
|
+
* tenant-spoofing vector where a caller forges another tenant's id in the body.
|
|
1101
|
+
*
|
|
1102
|
+
* The entry NEVER carries the dispatched payload (an OTP `verify` payload holds a
|
|
1103
|
+
* guessed code) — only the channel, the masked recipient, the purpose/template,
|
|
1104
|
+
* and a fixed `providerName: '__interceptor__'` marker. Audit failures are
|
|
1105
|
+
* swallowed by default (`audit.swallowErrors`) so auditing can never crash the
|
|
1106
|
+
* request flow; a consumer that sets `swallowErrors: false` opts into propagation.
|
|
1107
|
+
*
|
|
1108
|
+
* NOT auto-registered — a consumer opts in explicitly, e.g.
|
|
1109
|
+
* `{ provide: APP_INTERCEPTOR, useClass: NotificationAuditInterceptor }`.
|
|
1110
|
+
*/
|
|
1111
|
+
|
|
1112
|
+
/**
|
|
1113
|
+
* Records an audit entry around each `NotificationService.dispatch` call.
|
|
1114
|
+
*
|
|
1115
|
+
* @example
|
|
1116
|
+
* ```ts
|
|
1117
|
+
* // app.module.ts
|
|
1118
|
+
* providers: [{ provide: APP_INTERCEPTOR, useClass: NotificationAuditInterceptor }]
|
|
1119
|
+
* ```
|
|
1120
|
+
*/
|
|
1121
|
+
declare class NotificationAuditInterceptor implements NestInterceptor {
|
|
1122
|
+
private readonly options;
|
|
1123
|
+
private readonly auditLog;
|
|
1124
|
+
/**
|
|
1125
|
+
* @param options - The resolved, frozen module options (carries the tenant resolver + mask).
|
|
1126
|
+
* @param auditLog - The audit-log repository (no-op when none configured).
|
|
1127
|
+
*/
|
|
1128
|
+
constructor(options: ResolvedNotificationOptions, auditLog: INotificationLogRepository);
|
|
1129
|
+
/**
|
|
1130
|
+
* Taps the handler stream: records `'sent'` after a successful dispatch and
|
|
1131
|
+
* `'failed'` before re-throwing a rejected one. The success recording runs
|
|
1132
|
+
* downstream of the error handler so a failure is audited exactly once.
|
|
1133
|
+
*
|
|
1134
|
+
* @param context - The execution context exposing the handler arguments + request.
|
|
1135
|
+
* @param next - The downstream call handler.
|
|
1136
|
+
* @returns The original stream, unchanged except for the audit side effect.
|
|
1137
|
+
*/
|
|
1138
|
+
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown>;
|
|
1139
|
+
/**
|
|
1140
|
+
* Builds and writes the audit entry for one intercepted dispatch. Does nothing
|
|
1141
|
+
* when no argument matches the dispatch shape. Swallows write failures unless
|
|
1142
|
+
* `audit.swallowErrors` is `false`.
|
|
1143
|
+
*/
|
|
1144
|
+
private recordMeta;
|
|
1145
|
+
/** Returns the first handler argument shaped like a {@link DispatchInput}, else `null`. */
|
|
1146
|
+
private extractDispatchInput;
|
|
1147
|
+
/** Narrows an unknown argument to a {@link DispatchInput} by structural shape. */
|
|
1148
|
+
private isDispatchInput;
|
|
1149
|
+
/**
|
|
1150
|
+
* Resolves the trusted tenant id: `tenantIdResolver(request)` when configured and
|
|
1151
|
+
* a request is available, otherwise the payload-supplied `fallback`.
|
|
1152
|
+
*/
|
|
1153
|
+
private resolveTenantId;
|
|
1154
|
+
/** Reads the HTTP request from the context, returning `null` outside an HTTP context. */
|
|
1155
|
+
private extractRequest;
|
|
1156
|
+
/** Assembles the audit entry — masked recipient, never the dispatched payload. */
|
|
1157
|
+
private buildEntry;
|
|
1158
|
+
/** Extracts the (unmasked) recipient from the dispatch payload. */
|
|
1159
|
+
private extractRecipient;
|
|
1160
|
+
/** Extracts the audit `purpose`: the OTP purpose, or the email template name. */
|
|
1161
|
+
private extractPurpose;
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
/**
|
|
1165
|
+
* @fileoverview Dependency-injection tokens for the notification module.
|
|
1166
|
+
* @layer infrastructure
|
|
1167
|
+
*
|
|
1168
|
+
* Tokens are `Symbol`s, not strings, so they can never collide with another
|
|
1169
|
+
* library's provider tokens. They are exported publicly so a consumer can pull a
|
|
1170
|
+
* provider out of the container (e.g. `app.get(BYMAX_NOTIFICATION_EMAIL_PROVIDER)`)
|
|
1171
|
+
* to override or assert it in tests.
|
|
1172
|
+
*/
|
|
1173
|
+
/** Token for the resolved, frozen `ResolvedNotificationOptions`. */
|
|
1174
|
+
declare const BYMAX_NOTIFICATION_OPTIONS: unique symbol;
|
|
1175
|
+
/** Token for the registered `IEmailProvider`. */
|
|
1176
|
+
declare const BYMAX_NOTIFICATION_EMAIL_PROVIDER: unique symbol;
|
|
1177
|
+
/** Token for the registered `IOtpStorage`. */
|
|
1178
|
+
declare const BYMAX_NOTIFICATION_OTP_STORAGE: unique symbol;
|
|
1179
|
+
/** Token for the registered `ISmsProvider` — reserved; no SMS service is wired. */
|
|
1180
|
+
declare const BYMAX_NOTIFICATION_SMS_PROVIDER: unique symbol;
|
|
1181
|
+
/** Token for the registered `IPushProvider` — reserved; no push service is wired. */
|
|
1182
|
+
declare const BYMAX_NOTIFICATION_PUSH_PROVIDER: unique symbol;
|
|
1183
|
+
/** Token for the registered `IEmailTemplateRenderer`. */
|
|
1184
|
+
declare const BYMAX_NOTIFICATION_TEMPLATE_RENDERER: unique symbol;
|
|
1185
|
+
/** Token for the registered `INotificationLogRepository`. */
|
|
1186
|
+
declare const BYMAX_NOTIFICATION_LOG_REPOSITORY: unique symbol;
|
|
1187
|
+
|
|
1188
|
+
/**
|
|
1189
|
+
* @fileoverview Canonical OTP purpose constants.
|
|
1190
|
+
* @layer domain
|
|
1191
|
+
*
|
|
1192
|
+
* The five built-in purposes, exposed as constants so consumers get type-safe
|
|
1193
|
+
* references. Callers may still pass arbitrary purpose strings — these are the
|
|
1194
|
+
* well-known ones the library documents.
|
|
1195
|
+
*/
|
|
1196
|
+
/** The canonical OTP purposes the library ships with. */
|
|
1197
|
+
declare const NOTIFICATION_PURPOSES: {
|
|
1198
|
+
readonly EMAIL_VERIFICATION: "email_verification";
|
|
1199
|
+
readonly PASSWORD_RESET: "password_reset";
|
|
1200
|
+
readonly MFA_OOB: "mfa_oob";
|
|
1201
|
+
readonly PHONE_VERIFICATION: "phone_verification";
|
|
1202
|
+
readonly MAGIC_LINK: "magic_link";
|
|
1203
|
+
};
|
|
1204
|
+
/** Literal-union type of the canonical purpose values. */
|
|
1205
|
+
type CanonicalNotificationPurpose = (typeof NOTIFICATION_PURPOSES)[keyof typeof NOTIFICATION_PURPOSES];
|
|
1206
|
+
|
|
1207
|
+
/**
|
|
1208
|
+
* @fileoverview Canonical email-template name convention.
|
|
1209
|
+
* @layer domain
|
|
1210
|
+
*
|
|
1211
|
+
* The library ships NO HTML for these templates — the consumer registers each one
|
|
1212
|
+
* in their `IEmailTemplateRenderer`. This catalog documents the conventional names
|
|
1213
|
+
* plus the variables each template is expected to receive, so adopters share a
|
|
1214
|
+
* vocabulary and get type-safe autocompletion.
|
|
1215
|
+
*
|
|
1216
|
+
* Using these constants is OPTIONAL — `emailService.sendTemplate({ template })`
|
|
1217
|
+
* accepts any string; the benefit is IDE autocompletion and a single source of
|
|
1218
|
+
* truth for the canonical template names a typical consumer ships.
|
|
1219
|
+
*/
|
|
1220
|
+
/**
|
|
1221
|
+
* Canonical template names recognized by the library's conventions.
|
|
1222
|
+
*
|
|
1223
|
+
* Each entry's JSDoc lists the variables the template is expected to interpolate.
|
|
1224
|
+
*/
|
|
1225
|
+
declare const CANONICAL_EMAIL_TEMPLATES: {
|
|
1226
|
+
/** OTP for email verification — variables: `code`, `expiresInMinutes`, `purpose`, `name`, `appName`. */
|
|
1227
|
+
readonly OTP_CODE: "otp_code";
|
|
1228
|
+
/** OTP for password reset (distinct copy; may carry a deep link) — variables: `code`, `expiresInMinutes`, `name`, `appName`, `verificationLink`. */
|
|
1229
|
+
readonly OTP_PASSWORD_RESET: "otp_password_reset";
|
|
1230
|
+
/** OTP resend — same variables as the originating OTP template. */
|
|
1231
|
+
readonly OTP_RESENT: "otp_resent";
|
|
1232
|
+
/** Welcome after email verification — variables: `name`, `appName`, `appUrl`. */
|
|
1233
|
+
readonly WELCOME: "welcome";
|
|
1234
|
+
/** Password reset success — variables: `name`, `appName`, `supportEmail`. */
|
|
1235
|
+
readonly PASSWORD_RESET_SUCCESS: "password_reset_success";
|
|
1236
|
+
/** Trial ending soon — variables: `name`, `appName`, `trialPlanName`, `daysLeft`, `appUrl`. */
|
|
1237
|
+
readonly TRIAL_EXPIRING: "trial_expiring";
|
|
1238
|
+
/** Trial ended — variables: `name`, `appName`, `trialPlanName`, `durationDays`, `appUrl`. */
|
|
1239
|
+
readonly TRIAL_EXPIRED: "trial_expired";
|
|
1240
|
+
/** New device login — variables: `device`, `ip`, `timestamp`, `name`, `appName`. */
|
|
1241
|
+
readonly NEW_LOGIN_ALERT: "new_login_alert";
|
|
1242
|
+
/** MFA enabled — variables: `name`, `appName`. */
|
|
1243
|
+
readonly MFA_ENABLED: "mfa_enabled";
|
|
1244
|
+
/** MFA disabled — variables: `name`, `appName`. */
|
|
1245
|
+
readonly MFA_DISABLED: "mfa_disabled";
|
|
1246
|
+
};
|
|
1247
|
+
/** Union of the canonical template name string literals. */
|
|
1248
|
+
type CanonicalEmailTemplate = (typeof CANONICAL_EMAIL_TEMPLATES)[keyof typeof CANONICAL_EMAIL_TEMPLATES];
|
|
1249
|
+
|
|
1250
|
+
/**
|
|
1251
|
+
* @fileoverview Development email provider that logs instead of sending.
|
|
1252
|
+
* @layer infrastructure
|
|
1253
|
+
*
|
|
1254
|
+
* Useful for local development without SMTP credentials. It logs only the
|
|
1255
|
+
* recipient and subject — NEVER the body, which may carry OTP codes or PII.
|
|
1256
|
+
*
|
|
1257
|
+
* DO NOT USE IN PRODUCTION.
|
|
1258
|
+
*/
|
|
1259
|
+
|
|
1260
|
+
/** No-op `IEmailProvider` for development and tests. */
|
|
1261
|
+
declare class NoOpEmailProvider implements IEmailProvider {
|
|
1262
|
+
readonly name = "noop";
|
|
1263
|
+
private readonly logger;
|
|
1264
|
+
/** Always ready — the no-op provider has nothing to configure. */
|
|
1265
|
+
isConfigured(): boolean;
|
|
1266
|
+
/**
|
|
1267
|
+
* Pretends to send: logs the recipient and subject and returns a synthetic id.
|
|
1268
|
+
*
|
|
1269
|
+
* @param options - The message to "send". Only `to` and `subject` are logged.
|
|
1270
|
+
* @returns A synthetic `messageId` prefixed with `noop-`.
|
|
1271
|
+
*/
|
|
1272
|
+
send(options: EmailSendOptions): Promise<EmailSendResult>;
|
|
1273
|
+
}
|
|
1274
|
+
|
|
1275
|
+
/**
|
|
1276
|
+
* @fileoverview Audit repository that discards every entry.
|
|
1277
|
+
* @layer infrastructure
|
|
1278
|
+
*
|
|
1279
|
+
* The default `INotificationLogRepository` when the consumer does not configure
|
|
1280
|
+
* an audit sink. Keeps the audit code path uniform (always a repository present)
|
|
1281
|
+
* without persisting anything.
|
|
1282
|
+
*/
|
|
1283
|
+
|
|
1284
|
+
/** No-op audit repository: silently discards every entry. */
|
|
1285
|
+
declare class NoOpNotificationLogRepository implements INotificationLogRepository {
|
|
1286
|
+
readonly name = "noop";
|
|
1287
|
+
/**
|
|
1288
|
+
* Discards the entry.
|
|
1289
|
+
*
|
|
1290
|
+
* @param _entry - The audit entry; intentionally ignored.
|
|
1291
|
+
*/
|
|
1292
|
+
create(_entry: NotificationLogEntry): Promise<void>;
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
/**
|
|
1296
|
+
* @fileoverview Default `{{var}}`-interpolation email template renderer.
|
|
1297
|
+
* @layer infrastructure
|
|
1298
|
+
*
|
|
1299
|
+
* A minimal renderer: `{{var}}` substitution with automatic HTML escaping in the
|
|
1300
|
+
* html body only. It is deliberately not a full templating engine (no `{{#if}}`,
|
|
1301
|
+
* no `{{#each}}`, no partials) — consumers needing that plug in
|
|
1302
|
+
* Handlebars/MJML/React Email via `IEmailTemplateRenderer`.
|
|
1303
|
+
*
|
|
1304
|
+
* Security: variable values are HTML-escaped only in the html body, never in the
|
|
1305
|
+
* subject or text body (those are not HTML contexts, so escaping would surface
|
|
1306
|
+
* literal `&`/`<`). This closes a stored-XSS vector for interpolated names.
|
|
1307
|
+
*/
|
|
1308
|
+
|
|
1309
|
+
/** A raw template: subject + html (+ optional text) with `{{var}}` placeholders. */
|
|
1310
|
+
interface TemplateDefinition {
|
|
1311
|
+
subject: string;
|
|
1312
|
+
html: string;
|
|
1313
|
+
text?: string;
|
|
1314
|
+
}
|
|
1315
|
+
/** Behaviour when an interpolated variable is absent from the render data. */
|
|
1316
|
+
type MissingVariableMode = 'empty' | 'throw';
|
|
1317
|
+
/** Construction options for {@link DefaultTemplateRenderer}. */
|
|
1318
|
+
interface DefaultTemplateRendererOptions {
|
|
1319
|
+
/** Templates keyed by `${templateName}::${locale}`. */
|
|
1320
|
+
templates?: Record<string, TemplateDefinition>;
|
|
1321
|
+
/** Locale chain tried after the requested one. Defaults to `['en']`. */
|
|
1322
|
+
fallbackLocales?: readonly string[];
|
|
1323
|
+
/** Missing-variable behaviour: `'empty'` (default) renders `''`; `'throw'` errors. */
|
|
1324
|
+
onMissingVar?: MissingVariableMode;
|
|
1325
|
+
/** When `true`, `{{user.name}}` resolves nested data; otherwise it is a flat key. */
|
|
1326
|
+
enableNestedPaths?: boolean;
|
|
1327
|
+
}
|
|
1328
|
+
/**
|
|
1329
|
+
* Default renderer based on `{{var}}` interpolation with html-only escaping.
|
|
1330
|
+
*
|
|
1331
|
+
* Supports a configurable locale fallback chain, optional nested-path resolution,
|
|
1332
|
+
* a missing-variable policy, and fail-fast validation of registered templates at
|
|
1333
|
+
* construction. It does NOT support conditionals (`{{#if}}`), iteration
|
|
1334
|
+
* (`{{#each}}`), or partials — plug a richer engine for those.
|
|
1335
|
+
*
|
|
1336
|
+
* @example
|
|
1337
|
+
* ```ts
|
|
1338
|
+
* const renderer = new DefaultTemplateRenderer({
|
|
1339
|
+
* templates: { 'otp_code::en': { subject: 'Code', html: '<p>Hi {{user.name}}</p>' } },
|
|
1340
|
+
* fallbackLocales: ['en'],
|
|
1341
|
+
* enableNestedPaths: true
|
|
1342
|
+
* })
|
|
1343
|
+
* await renderer.render('otp_code', { user: { name: 'Jane' } }, 'pt-BR')
|
|
1344
|
+
* ```
|
|
1345
|
+
*/
|
|
1346
|
+
declare class DefaultTemplateRenderer implements IEmailTemplateRenderer {
|
|
1347
|
+
readonly name = "default-interpolation";
|
|
1348
|
+
private readonly templates;
|
|
1349
|
+
private readonly fallbackLocales;
|
|
1350
|
+
private readonly onMissingVar;
|
|
1351
|
+
private readonly enableNestedPaths;
|
|
1352
|
+
/**
|
|
1353
|
+
* @param options - Templates plus locale/missing-variable/nested-path policy.
|
|
1354
|
+
* @throws Error When a registered template lacks a string `subject`/`html`, or
|
|
1355
|
+
* carries a non-string `text`.
|
|
1356
|
+
*/
|
|
1357
|
+
constructor(options?: DefaultTemplateRendererOptions);
|
|
1358
|
+
/**
|
|
1359
|
+
* Whether a template is registered for the exact name + locale.
|
|
1360
|
+
*
|
|
1361
|
+
* @param templateName - Template name.
|
|
1362
|
+
* @param locale - Requested locale.
|
|
1363
|
+
* @returns `true` when the `${name}::${locale}` key exists.
|
|
1364
|
+
*/
|
|
1365
|
+
hasTemplate(templateName: string, locale: string): Promise<boolean>;
|
|
1366
|
+
/**
|
|
1367
|
+
* Renders a template, escaping interpolated values in the html body only.
|
|
1368
|
+
*
|
|
1369
|
+
* @param templateName - Template name.
|
|
1370
|
+
* @param data - Variables to interpolate.
|
|
1371
|
+
* @param locale - Requested locale; resolved via the fallback chain.
|
|
1372
|
+
* @returns The rendered subject + html (+ text when the template has one).
|
|
1373
|
+
* @throws Error When no template in the fallback chain matches, or a variable is
|
|
1374
|
+
* missing and `onMissingVar` is `'throw'`.
|
|
1375
|
+
*/
|
|
1376
|
+
render(templateName: string, data: Record<string, unknown>, locale: string): Promise<RenderedEmail>;
|
|
1377
|
+
/** Resolves the first registered template along `[locale, ...fallbackLocales]`. */
|
|
1378
|
+
private resolveTemplate;
|
|
1379
|
+
/** Replaces every `{{path}}` placeholder, escaping only when `escape` is `true`. */
|
|
1380
|
+
private interpolate;
|
|
1381
|
+
/**
|
|
1382
|
+
* Builds a variable resolver for one render call. Lookups go through a `Map`
|
|
1383
|
+
* built from own enumerable entries (never bracket indexing) so neither flat
|
|
1384
|
+
* nor nested resolution can reach inherited/prototype keys.
|
|
1385
|
+
*/
|
|
1386
|
+
private buildResolver;
|
|
1387
|
+
/** Walks a dotted path through own enumerable keys, stopping at any non-object. */
|
|
1388
|
+
private resolveNested;
|
|
1389
|
+
/**
|
|
1390
|
+
* Validates a registered template shape, throwing on the offending key. The
|
|
1391
|
+
* optional `text` body, when present, must be a string — a non-string `text`
|
|
1392
|
+
* would otherwise pass construction and crash at render time inside
|
|
1393
|
+
* `String.prototype.replace`.
|
|
1394
|
+
*/
|
|
1395
|
+
private assertValidTemplate;
|
|
1396
|
+
/** Builds the `${templateName}::${locale}` registry key. */
|
|
1397
|
+
private key;
|
|
1398
|
+
/** Escapes the five HTML-significant characters. */
|
|
1399
|
+
private escapeHtml;
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
/**
|
|
1403
|
+
* @fileoverview Reference `IEmailProvider` adapter backed by the Resend SDK.
|
|
1404
|
+
* @layer infrastructure
|
|
1405
|
+
*
|
|
1406
|
+
* `resend` is an OPTIONAL peer dependency: the SDK is loaded lazily via a dynamic
|
|
1407
|
+
* `import()` the first time `send()` runs, so a consumer who picks a different
|
|
1408
|
+
* provider never has to install it. The adapter forward-declares the slim
|
|
1409
|
+
* `ResendLike` shape it needs instead of importing `resend` at compile time,
|
|
1410
|
+
* keeping the library free of a hard dependency on the SDK's types.
|
|
1411
|
+
*
|
|
1412
|
+
* Security: the email body (`html` / `text`) may carry OTP codes or PII — it is
|
|
1413
|
+
* NEVER logged. Only the provider's own error message is surfaced (and re-thrown
|
|
1414
|
+
* as a plain `Error`, which `EmailService` maps to `EMAIL_SEND_FAILED`).
|
|
1415
|
+
*/
|
|
1416
|
+
|
|
1417
|
+
/** Construction options for {@link ResendEmailProvider}. */
|
|
1418
|
+
interface ResendEmailProviderOptions {
|
|
1419
|
+
/** Resend API key. When absent the provider is not configured and `send()` throws. */
|
|
1420
|
+
apiKey?: string;
|
|
1421
|
+
}
|
|
1422
|
+
/**
|
|
1423
|
+
* Reference {@link IEmailProvider} on top of Resend.
|
|
1424
|
+
*
|
|
1425
|
+
* @example
|
|
1426
|
+
* ```ts
|
|
1427
|
+
* BymaxNotificationModule.forRoot({
|
|
1428
|
+
* email: { provider: new ResendEmailProvider({ apiKey }), defaultFrom: 'noreply@acme.com' }
|
|
1429
|
+
* })
|
|
1430
|
+
* ```
|
|
1431
|
+
*/
|
|
1432
|
+
declare class ResendEmailProvider implements IEmailProvider {
|
|
1433
|
+
private readonly options;
|
|
1434
|
+
readonly name = "resend";
|
|
1435
|
+
private readonly logger;
|
|
1436
|
+
/**
|
|
1437
|
+
* Cached in-flight (or resolved) SDK client initialization. `null` until the first
|
|
1438
|
+
* `send()` and after a failed init. Caching the PROMISE (not just the client)
|
|
1439
|
+
* collapses concurrent first sends onto a single dynamic `import()` + instantiation;
|
|
1440
|
+
* a failed init resets this back to `null` so a transient error can be retried.
|
|
1441
|
+
*/
|
|
1442
|
+
private clientPromise;
|
|
1443
|
+
/**
|
|
1444
|
+
* @param options - Adapter options; `apiKey` is required to actually send.
|
|
1445
|
+
*/
|
|
1446
|
+
constructor(options?: ResendEmailProviderOptions);
|
|
1447
|
+
/**
|
|
1448
|
+
* Whether an API key was supplied. Does not load the SDK.
|
|
1449
|
+
*
|
|
1450
|
+
* @returns `true` when an `apiKey` is present.
|
|
1451
|
+
*/
|
|
1452
|
+
isConfigured(): boolean;
|
|
1453
|
+
/**
|
|
1454
|
+
* Sends one transactional email through Resend.
|
|
1455
|
+
*
|
|
1456
|
+
* @param options - The message envelope and body.
|
|
1457
|
+
* @returns The Resend message id.
|
|
1458
|
+
* @throws Error When the API key is missing, the `resend` package is not
|
|
1459
|
+
* installed, the SDK returns an error, or no message id comes back. `EmailService`
|
|
1460
|
+
* maps any thrown `Error` to `EMAIL_SEND_FAILED`.
|
|
1461
|
+
*/
|
|
1462
|
+
send(options: EmailSendOptions): Promise<EmailSendResult>;
|
|
1463
|
+
/**
|
|
1464
|
+
* Formats the RFC-5322 `from` header. The `Name <address>` display-name form is
|
|
1465
|
+
* only used when a non-empty address exists — otherwise it would emit the literal
|
|
1466
|
+
* `Name <undefined>` / `Name <>`. Falls back to the bare address (or `''`).
|
|
1467
|
+
*
|
|
1468
|
+
* @param from - The sender address, if any.
|
|
1469
|
+
* @param fromName - The sender display name, if any.
|
|
1470
|
+
* @returns `"Name <address>"`, the bare address, or `''`.
|
|
1471
|
+
*/
|
|
1472
|
+
private formatFrom;
|
|
1473
|
+
/**
|
|
1474
|
+
* Returns the cached SDK client, lazily importing `resend` on first use. Concurrent
|
|
1475
|
+
* first calls share one in-flight initialization promise so the dynamic import and
|
|
1476
|
+
* constructor run exactly once; a failed init is dropped from the cache so a later
|
|
1477
|
+
* call can retry instead of being permanently bricked.
|
|
1478
|
+
*
|
|
1479
|
+
* @returns The instantiated client.
|
|
1480
|
+
* @throws Error When `apiKey` is missing or the `resend` package is not installed.
|
|
1481
|
+
*/
|
|
1482
|
+
private getClient;
|
|
1483
|
+
/**
|
|
1484
|
+
* Builds a fresh SDK client, resetting the cached promise on any failure so the
|
|
1485
|
+
* provider is not permanently bricked by a transient init error.
|
|
1486
|
+
*
|
|
1487
|
+
* @returns The instantiated client.
|
|
1488
|
+
* @throws Error When `apiKey` is missing or the `resend` package is not installed.
|
|
1489
|
+
*/
|
|
1490
|
+
private createClient;
|
|
1491
|
+
/**
|
|
1492
|
+
* Dynamically imports the optional `resend` peer dependency.
|
|
1493
|
+
*
|
|
1494
|
+
* @returns The SDK's `Resend` constructor.
|
|
1495
|
+
* @throws Error When the package is not installed in the consumer app.
|
|
1496
|
+
*/
|
|
1497
|
+
private loadResendConstructor;
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
/**
|
|
1501
|
+
* @fileoverview In-memory `IOtpStorage` for development and unit tests.
|
|
1502
|
+
* @layer infrastructure
|
|
1503
|
+
*
|
|
1504
|
+
* Backed by two native `Map`s. It is atomic by construction: `consumeAttempt`
|
|
1505
|
+
* performs its read → checks → increment → write with NO `await` in between, so
|
|
1506
|
+
* Node's single-threaded event loop cannot interleave two calls and overshoot
|
|
1507
|
+
* `maxAttempts`.
|
|
1508
|
+
*
|
|
1509
|
+
* DO NOT USE IN MULTI-INSTANCE PRODUCTION — entries live in the process memory
|
|
1510
|
+
* and are not shared across instances; use `RedisOtpStorage` there.
|
|
1511
|
+
*/
|
|
1512
|
+
|
|
1513
|
+
/** Aggregate sizes of the two internal maps — exposed by the {@link InMemoryOtpStorage.size} helper. */
|
|
1514
|
+
interface InMemoryStorageSize {
|
|
1515
|
+
otps: number;
|
|
1516
|
+
cooldowns: number;
|
|
1517
|
+
}
|
|
1518
|
+
/** Process-local `IOtpStorage` for dev/test. */
|
|
1519
|
+
declare class InMemoryOtpStorage implements IOtpStorage {
|
|
1520
|
+
readonly name = "memory";
|
|
1521
|
+
/** OTP entries keyed by `${tenantId}::${recipient}::${purpose}`. */
|
|
1522
|
+
private readonly store;
|
|
1523
|
+
/** Cooldown expiries (epoch ms) keyed by the same composite key. */
|
|
1524
|
+
private readonly cooldowns;
|
|
1525
|
+
/** Always ready — there is nothing to configure.
|
|
1526
|
+
*
|
|
1527
|
+
* @returns `true`.
|
|
1528
|
+
*/
|
|
1529
|
+
isConfigured(): boolean;
|
|
1530
|
+
/**
|
|
1531
|
+
* Creates or replaces an OTP entry.
|
|
1532
|
+
*
|
|
1533
|
+
* @param tenantId - Tenant isolation scope.
|
|
1534
|
+
* @param recipient - Pre-normalized recipient identifier.
|
|
1535
|
+
* @param purpose - OTP purpose.
|
|
1536
|
+
* @param entry - The entry to persist.
|
|
1537
|
+
*/
|
|
1538
|
+
set(tenantId: string, recipient: string, purpose: string, entry: OtpEntry): Promise<void>;
|
|
1539
|
+
/**
|
|
1540
|
+
* Reads an entry, self-evicting it when its TTL has lapsed.
|
|
1541
|
+
*
|
|
1542
|
+
* @param tenantId - Tenant isolation scope.
|
|
1543
|
+
* @param recipient - Pre-normalized recipient identifier.
|
|
1544
|
+
* @param purpose - OTP purpose.
|
|
1545
|
+
* @returns The entry, or `null` when absent or expired.
|
|
1546
|
+
*/
|
|
1547
|
+
get(tenantId: string, recipient: string, purpose: string): Promise<OtpEntry | null>;
|
|
1548
|
+
/**
|
|
1549
|
+
* Atomic verification primitive — read → expiry/max checks → increment → write,
|
|
1550
|
+
* with no `await` between read and write.
|
|
1551
|
+
*
|
|
1552
|
+
* @param tenantId - Tenant isolation scope.
|
|
1553
|
+
* @param recipient - Pre-normalized recipient identifier.
|
|
1554
|
+
* @param purpose - OTP purpose.
|
|
1555
|
+
* @returns `not_found` (missing/expired), `max_attempts` (ceiling reached, entry
|
|
1556
|
+
* deleted), or `ok` with the entry whose `attempts` was incremented by one.
|
|
1557
|
+
*/
|
|
1558
|
+
consumeAttempt(tenantId: string, recipient: string, purpose: string): Promise<ConsumeAttemptResult>;
|
|
1559
|
+
/**
|
|
1560
|
+
* Updates an existing entry; a no-op when the key is absent (no resurrection).
|
|
1561
|
+
*
|
|
1562
|
+
* @param tenantId - Tenant isolation scope.
|
|
1563
|
+
* @param recipient - Pre-normalized recipient identifier.
|
|
1564
|
+
* @param purpose - OTP purpose.
|
|
1565
|
+
* @param entry - The replacement entry.
|
|
1566
|
+
*/
|
|
1567
|
+
update(tenantId: string, recipient: string, purpose: string, entry: OtpEntry): Promise<void>;
|
|
1568
|
+
/**
|
|
1569
|
+
* Removes the OTP entry. Idempotent.
|
|
1570
|
+
*
|
|
1571
|
+
* @param tenantId - Tenant isolation scope.
|
|
1572
|
+
* @param recipient - Pre-normalized recipient identifier.
|
|
1573
|
+
* @param purpose - OTP purpose.
|
|
1574
|
+
*/
|
|
1575
|
+
delete(tenantId: string, recipient: string, purpose: string): Promise<void>;
|
|
1576
|
+
/**
|
|
1577
|
+
* Acquires the cooldown lock only when one is not already active.
|
|
1578
|
+
*
|
|
1579
|
+
* @param tenantId - Tenant isolation scope.
|
|
1580
|
+
* @param recipient - Pre-normalized recipient identifier.
|
|
1581
|
+
* @param purpose - OTP purpose.
|
|
1582
|
+
* @param ttlSeconds - Cooldown duration in seconds.
|
|
1583
|
+
* @returns `true` when acquired, `false` when a cooldown is already active.
|
|
1584
|
+
*/
|
|
1585
|
+
tryAcquireCooldown(tenantId: string, recipient: string, purpose: string, ttlSeconds: number): Promise<boolean>;
|
|
1586
|
+
/**
|
|
1587
|
+
* Remaining cooldown in seconds, self-evicting a lapsed cooldown.
|
|
1588
|
+
*
|
|
1589
|
+
* @param tenantId - Tenant isolation scope.
|
|
1590
|
+
* @param recipient - Pre-normalized recipient identifier.
|
|
1591
|
+
* @param purpose - OTP purpose.
|
|
1592
|
+
* @returns Remaining seconds, or `0` when there is no active cooldown.
|
|
1593
|
+
*/
|
|
1594
|
+
getCooldown(tenantId: string, recipient: string, purpose: string): Promise<number>;
|
|
1595
|
+
/**
|
|
1596
|
+
* Clears the cooldown. Idempotent.
|
|
1597
|
+
*
|
|
1598
|
+
* @param tenantId - Tenant isolation scope.
|
|
1599
|
+
* @param recipient - Pre-normalized recipient identifier.
|
|
1600
|
+
* @param purpose - OTP purpose.
|
|
1601
|
+
*/
|
|
1602
|
+
clearCooldown(tenantId: string, recipient: string, purpose: string): Promise<void>;
|
|
1603
|
+
/**
|
|
1604
|
+
* Test helper — wipes all entries and cooldowns. Not part of `IOtpStorage`.
|
|
1605
|
+
*/
|
|
1606
|
+
clear(): void;
|
|
1607
|
+
/**
|
|
1608
|
+
* Test helper — current map sizes. Not part of `IOtpStorage`.
|
|
1609
|
+
*
|
|
1610
|
+
* @returns The number of stored OTP entries and active cooldowns.
|
|
1611
|
+
*/
|
|
1612
|
+
size(): InMemoryStorageSize;
|
|
1613
|
+
/** Collapses the `(tenantId, recipient, purpose)` tuple into one map key. */
|
|
1614
|
+
private key;
|
|
1615
|
+
}
|
|
1616
|
+
|
|
1617
|
+
/**
|
|
1618
|
+
* @fileoverview Production `IOtpStorage` backed by Redis.
|
|
1619
|
+
* @layer infrastructure
|
|
1620
|
+
*
|
|
1621
|
+
* The default OTP backend for multi-instance SaaS. Two security-critical
|
|
1622
|
+
* guarantees live here:
|
|
1623
|
+
*
|
|
1624
|
+
* 1. **Atomic attempt counting** — `consumeAttempt` runs its whole
|
|
1625
|
+
* read → expiry/max check → increment → write sequence inside ONE Lua script
|
|
1626
|
+
* (`EVAL`), so concurrent verifications cannot interleave and overshoot
|
|
1627
|
+
* `maxAttempts`.
|
|
1628
|
+
* 2. **PII-free keys** — every key carries `sha256(tenantId:recipient)`, never the
|
|
1629
|
+
* plaintext email/phone, so an operator with `KEYS` access cannot enumerate
|
|
1630
|
+
* recipients, and a cross-tenant key collision is computationally infeasible.
|
|
1631
|
+
*
|
|
1632
|
+
* `ioredis` is an OPTIONAL peer dependency: this class forward-declares the slim
|
|
1633
|
+
* {@link RedisLike} surface it needs (including `eval`/`pttl`) instead of importing
|
|
1634
|
+
* `ioredis` types, so a consumer on a different backend never pays for it.
|
|
1635
|
+
*/
|
|
1636
|
+
|
|
1637
|
+
/** The slim Redis surface {@link RedisOtpStorage} relies on (ioredis is structurally compatible). */
|
|
1638
|
+
interface RedisLike {
|
|
1639
|
+
get(key: string): Promise<string | null>;
|
|
1640
|
+
set(key: string, value: string, ...args: Array<string | number>): Promise<'OK' | null>;
|
|
1641
|
+
setex(key: string, ttlSeconds: number, value: string): Promise<'OK'>;
|
|
1642
|
+
del(...keys: string[]): Promise<number>;
|
|
1643
|
+
ttl(key: string): Promise<number>;
|
|
1644
|
+
/** Millisecond TTL — read inside the Lua script to preserve the original expiry on rewrite. */
|
|
1645
|
+
pttl(key: string): Promise<number>;
|
|
1646
|
+
/** Evaluates a Lua script atomically — used for the `consumeAttempt` primitive. */
|
|
1647
|
+
eval(script: string, numKeys: number, ...args: Array<string | number>): Promise<unknown>;
|
|
1648
|
+
}
|
|
1649
|
+
/** Construction options for {@link RedisOtpStorage}. */
|
|
1650
|
+
interface RedisOtpStorageOptions {
|
|
1651
|
+
/** ioredis (or structurally compatible) client supplied by the consumer. */
|
|
1652
|
+
redisClient: RedisLike;
|
|
1653
|
+
/** Key namespace prefix. Default: `'notification'`. */
|
|
1654
|
+
namespace?: string;
|
|
1655
|
+
}
|
|
1656
|
+
/** Redis-backed `IOtpStorage` with atomic Lua attempt counting and NX cooldown locking. */
|
|
1657
|
+
declare class RedisOtpStorage implements IOtpStorage {
|
|
1658
|
+
readonly name = "redis";
|
|
1659
|
+
private readonly redis;
|
|
1660
|
+
private readonly namespace;
|
|
1661
|
+
/**
|
|
1662
|
+
* @param options - The Redis client and optional namespace.
|
|
1663
|
+
*/
|
|
1664
|
+
constructor(options: RedisOtpStorageOptions);
|
|
1665
|
+
/**
|
|
1666
|
+
* Atomic verify primitive. The entire read → expiry/max check → increment → write
|
|
1667
|
+
* runs in this single script, so concurrent calls cannot overshoot `maxAttempts`.
|
|
1668
|
+
* `PTTL` is read inside the script to preserve the original expiry on rewrite.
|
|
1669
|
+
*/
|
|
1670
|
+
private static readonly CONSUME_ATTEMPT_LUA;
|
|
1671
|
+
/** Whether a Redis client was supplied.
|
|
1672
|
+
*
|
|
1673
|
+
* @returns `true` when a client is present.
|
|
1674
|
+
*/
|
|
1675
|
+
isConfigured(): boolean;
|
|
1676
|
+
/**
|
|
1677
|
+
* Creates or replaces an OTP entry with a TTL derived from `expiresAt`.
|
|
1678
|
+
*
|
|
1679
|
+
* @param tenantId - Tenant isolation scope.
|
|
1680
|
+
* @param recipient - Pre-normalized recipient identifier.
|
|
1681
|
+
* @param purpose - OTP purpose.
|
|
1682
|
+
* @param entry - The entry to persist.
|
|
1683
|
+
*/
|
|
1684
|
+
set(tenantId: string, recipient: string, purpose: string, entry: OtpEntry): Promise<void>;
|
|
1685
|
+
/**
|
|
1686
|
+
* Reads an entry, deleting and returning `null` for corrupted JSON.
|
|
1687
|
+
*
|
|
1688
|
+
* @param tenantId - Tenant isolation scope.
|
|
1689
|
+
* @param recipient - Pre-normalized recipient identifier.
|
|
1690
|
+
* @param purpose - OTP purpose.
|
|
1691
|
+
* @returns The parsed entry, or `null` when absent/corrupted.
|
|
1692
|
+
*/
|
|
1693
|
+
get(tenantId: string, recipient: string, purpose: string): Promise<OtpEntry | null>;
|
|
1694
|
+
/**
|
|
1695
|
+
* Atomic verification primitive (single `EVAL`).
|
|
1696
|
+
*
|
|
1697
|
+
* @param tenantId - Tenant isolation scope.
|
|
1698
|
+
* @param recipient - Pre-normalized recipient identifier.
|
|
1699
|
+
* @param purpose - OTP purpose.
|
|
1700
|
+
* @returns `not_found`, `max_attempts`, or `ok` with the incremented entry.
|
|
1701
|
+
*/
|
|
1702
|
+
consumeAttempt(tenantId: string, recipient: string, purpose: string): Promise<ConsumeAttemptResult>;
|
|
1703
|
+
/**
|
|
1704
|
+
* Updates an entry with `SET … KEEPTTL XX` — preserves the TTL and never
|
|
1705
|
+
* resurrects an already-expired key.
|
|
1706
|
+
*
|
|
1707
|
+
* @param tenantId - Tenant isolation scope.
|
|
1708
|
+
* @param recipient - Pre-normalized recipient identifier.
|
|
1709
|
+
* @param purpose - OTP purpose.
|
|
1710
|
+
* @param entry - The replacement entry.
|
|
1711
|
+
*/
|
|
1712
|
+
update(tenantId: string, recipient: string, purpose: string, entry: OtpEntry): Promise<void>;
|
|
1713
|
+
/**
|
|
1714
|
+
* Removes the OTP entry. Idempotent.
|
|
1715
|
+
*
|
|
1716
|
+
* @param tenantId - Tenant isolation scope.
|
|
1717
|
+
* @param recipient - Pre-normalized recipient identifier.
|
|
1718
|
+
* @param purpose - OTP purpose.
|
|
1719
|
+
*/
|
|
1720
|
+
delete(tenantId: string, recipient: string, purpose: string): Promise<void>;
|
|
1721
|
+
/**
|
|
1722
|
+
* Atomic cooldown acquire with `SET … NX EX` — only the first concurrent caller wins.
|
|
1723
|
+
*
|
|
1724
|
+
* A non-positive `ttlSeconds` means "no resend cooldown is configured". Redis rejects
|
|
1725
|
+
* `SET … EX 0` with `ERR invalid expire time`, so this short-circuits: it never issues
|
|
1726
|
+
* the `SET`, clears any stale cooldown key, and reports success (there is nothing to
|
|
1727
|
+
* lock, so the caller is always free to proceed).
|
|
1728
|
+
*
|
|
1729
|
+
* @param tenantId - Tenant isolation scope.
|
|
1730
|
+
* @param recipient - Pre-normalized recipient identifier.
|
|
1731
|
+
* @param purpose - OTP purpose.
|
|
1732
|
+
* @param ttlSeconds - Cooldown duration in seconds; `<= 0` means no cooldown.
|
|
1733
|
+
* @returns `true` when acquired (or when no cooldown applies), `false` when a cooldown is already active.
|
|
1734
|
+
*/
|
|
1735
|
+
tryAcquireCooldown(tenantId: string, recipient: string, purpose: string, ttlSeconds: number): Promise<boolean>;
|
|
1736
|
+
/**
|
|
1737
|
+
* Remaining cooldown in seconds.
|
|
1738
|
+
*
|
|
1739
|
+
* @param tenantId - Tenant isolation scope.
|
|
1740
|
+
* @param recipient - Pre-normalized recipient identifier.
|
|
1741
|
+
* @param purpose - OTP purpose.
|
|
1742
|
+
* @returns Remaining seconds, or `0` when there is no active cooldown.
|
|
1743
|
+
*/
|
|
1744
|
+
getCooldown(tenantId: string, recipient: string, purpose: string): Promise<number>;
|
|
1745
|
+
/**
|
|
1746
|
+
* Clears the cooldown key. Idempotent.
|
|
1747
|
+
*
|
|
1748
|
+
* @param tenantId - Tenant isolation scope.
|
|
1749
|
+
* @param recipient - Pre-normalized recipient identifier.
|
|
1750
|
+
* @param purpose - OTP purpose.
|
|
1751
|
+
*/
|
|
1752
|
+
clearCooldown(tenantId: string, recipient: string, purpose: string): Promise<void>;
|
|
1753
|
+
/** Builds the OTP entry key: `{namespace}:otp:{purpose}:{sha256(tenantId:recipient)}`. */
|
|
1754
|
+
private otpKey;
|
|
1755
|
+
/** Builds the cooldown key: `{namespace}:otp_cd:{purpose}:{sha256(tenantId:recipient)}`. */
|
|
1756
|
+
private cooldownKey;
|
|
1757
|
+
}
|
|
1758
|
+
|
|
1759
|
+
/**
|
|
1760
|
+
* @fileoverview SHA-256 hashing of `(tenantId, recipient)` for storage keys.
|
|
1761
|
+
* @layer infrastructure
|
|
1762
|
+
*
|
|
1763
|
+
* Storage keys are `sha256(`${tenantId}:${recipient}`)` for two reasons:
|
|
1764
|
+
* 1. Privacy — an operator with `KEYS`-level access to the store cannot enumerate
|
|
1765
|
+
* the email/phone of every recipient with a pending OTP.
|
|
1766
|
+
* 2. Multi-tenancy — SHA-256 preimage resistance makes a cross-tenant key
|
|
1767
|
+
* collision computationally infeasible.
|
|
1768
|
+
*/
|
|
1769
|
+
/**
|
|
1770
|
+
* Derives a deterministic, PII-free storage key fragment from a tenant and recipient.
|
|
1771
|
+
*
|
|
1772
|
+
* @param tenantId - Tenant isolation scope.
|
|
1773
|
+
* @param recipient - Pre-normalized recipient identifier.
|
|
1774
|
+
* @returns A 64-character lowercase hex SHA-256 digest. Order-sensitive.
|
|
1775
|
+
*/
|
|
1776
|
+
declare function hashTenantRecipient(tenantId: string, recipient: string): string;
|
|
1777
|
+
|
|
1778
|
+
/**
|
|
1779
|
+
* @fileoverview CSPRNG OTP code generation.
|
|
1780
|
+
* @layer infrastructure
|
|
1781
|
+
*
|
|
1782
|
+
* Every code is built character-by-character from a charset using
|
|
1783
|
+
* `node:crypto.randomInt` (CSPRNG-backed, never `Math.random`). The numeric path
|
|
1784
|
+
* deliberately does NOT use `randomInt(0, 10 ** length)`: for `length >= 15` that
|
|
1785
|
+
* exceeds `randomInt`'s 2**48 ceiling and loses integer precision (and would drop
|
|
1786
|
+
* leading zeros). Per-character `randomInt(0, charset.length)` is unbiased, works
|
|
1787
|
+
* for any length, and preserves leading zeros naturally.
|
|
1788
|
+
*/
|
|
1789
|
+
/**
|
|
1790
|
+
* Generates a crypto-secure OTP code.
|
|
1791
|
+
*
|
|
1792
|
+
* @param length - Code length; an integer in `[1, 32]`.
|
|
1793
|
+
* @param type - Charset to draw from.
|
|
1794
|
+
* @returns The generated code.
|
|
1795
|
+
* @throws NotificationException With `OTP_INVALID_LENGTH` when `length` is not an integer in `[1, 32]`.
|
|
1796
|
+
*/
|
|
1797
|
+
declare function generateOtpCode(length: number, type: 'numeric' | 'alpha' | 'alphanumeric'): string;
|
|
1798
|
+
|
|
1799
|
+
/**
|
|
1800
|
+
* @fileoverview Constant-time string comparison for OTP verification.
|
|
1801
|
+
* @layer infrastructure
|
|
1802
|
+
*
|
|
1803
|
+
* Comparing OTP codes with `===` is unsafe: JavaScript string equality
|
|
1804
|
+
* short-circuits on the first differing character, leaking the match position via
|
|
1805
|
+
* timing. `safeCompare` length-guards first (so a wrong-length guess fails closed
|
|
1806
|
+
* instead of throwing the `RangeError` that `timingSafeEqual` raises on
|
|
1807
|
+
* unequal-length buffers) and then compares in constant time.
|
|
1808
|
+
*/
|
|
1809
|
+
/**
|
|
1810
|
+
* Compares two strings in constant time (after a length guard).
|
|
1811
|
+
*
|
|
1812
|
+
* @param expected - The reference value.
|
|
1813
|
+
* @param actual - The value to check.
|
|
1814
|
+
* @returns `true` when the strings are byte-equal; `false` otherwise, including
|
|
1815
|
+
* on a length mismatch (which leaks only the already-public expected length).
|
|
1816
|
+
*/
|
|
1817
|
+
declare function safeCompare(expected: string, actual: string): boolean;
|
|
1818
|
+
|
|
1819
|
+
/**
|
|
1820
|
+
* @fileoverview Pure helpers for resend-cooldown presentation.
|
|
1821
|
+
* @layer application
|
|
1822
|
+
*
|
|
1823
|
+
* Used by `OtpService` to enrich the `OTP_COOLDOWN_ACTIVE` exception and exposed
|
|
1824
|
+
* to consumers building an HTTP `Retry-After` header or a countdown UI from the
|
|
1825
|
+
* remaining-seconds value returned by `IOtpStorage.getCooldown()` — without
|
|
1826
|
+
* pulling in a date library (date-fns / dayjs).
|
|
1827
|
+
*/
|
|
1828
|
+
/**
|
|
1829
|
+
* Computes the HTTP `Retry-After` header value (in whole seconds).
|
|
1830
|
+
*
|
|
1831
|
+
* Rounds up (a partial second still requires waiting) and clamps to a
|
|
1832
|
+
* non-negative integer, so an already-expired cooldown yields `'0'`.
|
|
1833
|
+
*
|
|
1834
|
+
* @param remainingSeconds - Remaining cooldown, as returned by `storage.getCooldown()`.
|
|
1835
|
+
* @returns A string suitable for `res.setHeader('Retry-After', value)`.
|
|
1836
|
+
* @example
|
|
1837
|
+
* ```ts
|
|
1838
|
+
* toRetryAfterHeader(47.3) // '48'
|
|
1839
|
+
* toRetryAfterHeader(-5) // '0'
|
|
1840
|
+
* ```
|
|
1841
|
+
*/
|
|
1842
|
+
declare function toRetryAfterHeader(remainingSeconds: number): string;
|
|
1843
|
+
/**
|
|
1844
|
+
* Computes the epoch-ms timestamp at which the cooldown will expire.
|
|
1845
|
+
*
|
|
1846
|
+
* @param remainingSeconds - Current remaining cooldown in seconds.
|
|
1847
|
+
* @returns Epoch ms when the cooldown expires; `Date.now()` when already expired.
|
|
1848
|
+
* @example
|
|
1849
|
+
* ```ts
|
|
1850
|
+
* cooldownExpiresAt(60) // ~Date.now() + 60_000
|
|
1851
|
+
* cooldownExpiresAt(0) // ~Date.now()
|
|
1852
|
+
* ```
|
|
1853
|
+
*/
|
|
1854
|
+
declare function cooldownExpiresAt(remainingSeconds: number): number;
|
|
1855
|
+
/**
|
|
1856
|
+
* Formats a remaining cooldown as a compact human-readable string for a UI.
|
|
1857
|
+
*
|
|
1858
|
+
* Zero-valued units are omitted; an expired or zero cooldown floors to `'0s'`.
|
|
1859
|
+
*
|
|
1860
|
+
* @param remainingSeconds - Remaining cooldown in seconds.
|
|
1861
|
+
* @returns A string such as `'0s'`, `'47s'`, `'2m'`, `'2m 5s'`, `'1h'`, or `'1h 2m 5s'`.
|
|
1862
|
+
* @example
|
|
1863
|
+
* ```ts
|
|
1864
|
+
* formatCooldown(125) // '2m 5s'
|
|
1865
|
+
* formatCooldown(3725) // '1h 2m 5s'
|
|
1866
|
+
* ```
|
|
1867
|
+
*/
|
|
1868
|
+
declare function formatCooldown(remainingSeconds: number): string;
|
|
1869
|
+
|
|
1870
|
+
/**
|
|
1871
|
+
* @fileoverview Public error-code catalog for the shared subpath.
|
|
1872
|
+
* @layer shared
|
|
1873
|
+
*
|
|
1874
|
+
* Zero-dependency map of every notification error code. The string values are
|
|
1875
|
+
* the single source of truth a frontend matches against; the server's
|
|
1876
|
+
* `NOTIFICATION_ERROR_DEFINITIONS` re-states the same codes (with HTTP status +
|
|
1877
|
+
* message) and a CI gate asserts the two stay byte-for-byte identical.
|
|
1878
|
+
*/
|
|
1879
|
+
/**
|
|
1880
|
+
* Stable error-code identifiers, keyed by their symbolic name.
|
|
1881
|
+
*
|
|
1882
|
+
* Values are namespaced under `notification.*` and never change once published —
|
|
1883
|
+
* consumers branch on them to localize messages. The 22 entries cover the email,
|
|
1884
|
+
* template, OTP, SMS, push, audit, and channel-config failure surfaces.
|
|
1885
|
+
*/
|
|
1886
|
+
declare const NOTIFICATION_ERROR_CODES: {
|
|
1887
|
+
readonly EMAIL_PROVIDER_NOT_CONFIGURED: "notification.email_provider_not_configured";
|
|
1888
|
+
readonly EMAIL_SEND_FAILED: "notification.email_send_failed";
|
|
1889
|
+
readonly EMAIL_ATTACHMENTS_TOO_LARGE: "notification.email_attachments_too_large";
|
|
1890
|
+
readonly EMAIL_INVALID_RECIPIENT: "notification.email_invalid_recipient";
|
|
1891
|
+
/** The email payload carries neither a `template` nor a `subject` + `html` body source. */
|
|
1892
|
+
readonly EMAIL_MISSING_BODY: "notification.email_missing_body";
|
|
1893
|
+
readonly TEMPLATE_NOT_FOUND: "notification.template_not_found";
|
|
1894
|
+
readonly TEMPLATE_RENDER_FAILED: "notification.template_render_failed";
|
|
1895
|
+
readonly OTP_STORAGE_NOT_CONFIGURED: "notification.otp_storage_not_configured";
|
|
1896
|
+
readonly OTP_EMAIL_DELIVERY_NOT_CONFIGURED: "notification.otp_email_delivery_not_configured";
|
|
1897
|
+
readonly OTP_COOLDOWN_ACTIVE: "notification.otp_cooldown_active";
|
|
1898
|
+
readonly OTP_NOT_FOUND: "notification.otp_not_found";
|
|
1899
|
+
readonly OTP_EXPIRED: "notification.otp_expired";
|
|
1900
|
+
readonly OTP_MAX_ATTEMPTS_EXCEEDED: "notification.otp_max_attempts_exceeded";
|
|
1901
|
+
readonly OTP_INVALID_CODE: "notification.otp_invalid_code";
|
|
1902
|
+
readonly OTP_INVALID_LENGTH: "notification.otp_invalid_length";
|
|
1903
|
+
readonly SMS_PROVIDER_NOT_CONFIGURED: "notification.sms_provider_not_configured";
|
|
1904
|
+
readonly SMS_SEND_FAILED: "notification.sms_send_failed";
|
|
1905
|
+
readonly SMS_INVALID_RECIPIENT: "notification.sms_invalid_recipient";
|
|
1906
|
+
readonly PUSH_PROVIDER_NOT_CONFIGURED: "notification.push_provider_not_configured";
|
|
1907
|
+
readonly PUSH_SEND_FAILED: "notification.push_send_failed";
|
|
1908
|
+
readonly AUDIT_LOG_FAILED: "notification.audit_log_failed";
|
|
1909
|
+
readonly CHANNEL_DISABLED: "notification.channel_disabled";
|
|
1910
|
+
};
|
|
1911
|
+
/**
|
|
1912
|
+
* The literal-union type of every value in {@link NOTIFICATION_ERROR_CODES}.
|
|
1913
|
+
*/
|
|
1914
|
+
type NotificationErrorCode = (typeof NOTIFICATION_ERROR_CODES)[keyof typeof NOTIFICATION_ERROR_CODES];
|
|
1915
|
+
|
|
1916
|
+
/**
|
|
1917
|
+
* @fileoverview Server-side error catalog: code + HTTP status + default message.
|
|
1918
|
+
* @layer domain
|
|
1919
|
+
*
|
|
1920
|
+
* Each definition pairs a stable error code with the HTTP status and English
|
|
1921
|
+
* message `NotificationException` emits. The code strings are byte-for-byte
|
|
1922
|
+
* identical to `shared/constants/error-codes.ts`; a CI gate asserts the two stay
|
|
1923
|
+
* in sync.
|
|
1924
|
+
*/
|
|
1925
|
+
|
|
1926
|
+
/** Shape of one entry in {@link NOTIFICATION_ERROR_DEFINITIONS}. */
|
|
1927
|
+
interface NotificationErrorDefinition {
|
|
1928
|
+
code: string;
|
|
1929
|
+
status: HttpStatus;
|
|
1930
|
+
message: string;
|
|
1931
|
+
}
|
|
1932
|
+
/**
|
|
1933
|
+
* The complete error catalog, keyed by symbolic name. Drives both the HTTP status
|
|
1934
|
+
* and the default message of every `NotificationException`.
|
|
1935
|
+
*/
|
|
1936
|
+
declare const NOTIFICATION_ERROR_DEFINITIONS: {
|
|
1937
|
+
readonly EMAIL_PROVIDER_NOT_CONFIGURED: {
|
|
1938
|
+
readonly code: "notification.email_provider_not_configured";
|
|
1939
|
+
readonly status: HttpStatus.INTERNAL_SERVER_ERROR;
|
|
1940
|
+
readonly message: "Email provider not configured";
|
|
1941
|
+
};
|
|
1942
|
+
readonly EMAIL_SEND_FAILED: {
|
|
1943
|
+
readonly code: "notification.email_send_failed";
|
|
1944
|
+
readonly status: HttpStatus.BAD_GATEWAY;
|
|
1945
|
+
readonly message: "Failed to send email";
|
|
1946
|
+
};
|
|
1947
|
+
readonly EMAIL_ATTACHMENTS_TOO_LARGE: {
|
|
1948
|
+
readonly code: "notification.email_attachments_too_large";
|
|
1949
|
+
readonly status: HttpStatus.PAYLOAD_TOO_LARGE;
|
|
1950
|
+
readonly message: "Email attachments exceed size limit";
|
|
1951
|
+
};
|
|
1952
|
+
readonly EMAIL_INVALID_RECIPIENT: {
|
|
1953
|
+
readonly code: "notification.email_invalid_recipient";
|
|
1954
|
+
readonly status: HttpStatus.BAD_REQUEST;
|
|
1955
|
+
readonly message: "Invalid recipient email";
|
|
1956
|
+
};
|
|
1957
|
+
readonly EMAIL_MISSING_BODY: {
|
|
1958
|
+
readonly code: "notification.email_missing_body";
|
|
1959
|
+
readonly status: HttpStatus.BAD_REQUEST;
|
|
1960
|
+
readonly message: "Email payload requires either a template or a subject and html body";
|
|
1961
|
+
};
|
|
1962
|
+
readonly TEMPLATE_NOT_FOUND: {
|
|
1963
|
+
readonly code: "notification.template_not_found";
|
|
1964
|
+
readonly status: HttpStatus.INTERNAL_SERVER_ERROR;
|
|
1965
|
+
readonly message: "Email template not found";
|
|
1966
|
+
};
|
|
1967
|
+
readonly TEMPLATE_RENDER_FAILED: {
|
|
1968
|
+
readonly code: "notification.template_render_failed";
|
|
1969
|
+
readonly status: HttpStatus.INTERNAL_SERVER_ERROR;
|
|
1970
|
+
readonly message: "Failed to render email template";
|
|
1971
|
+
};
|
|
1972
|
+
readonly OTP_STORAGE_NOT_CONFIGURED: {
|
|
1973
|
+
readonly code: "notification.otp_storage_not_configured";
|
|
1974
|
+
readonly status: HttpStatus.INTERNAL_SERVER_ERROR;
|
|
1975
|
+
readonly message: "OTP storage not configured";
|
|
1976
|
+
};
|
|
1977
|
+
readonly OTP_EMAIL_DELIVERY_NOT_CONFIGURED: {
|
|
1978
|
+
readonly code: "notification.otp_email_delivery_not_configured";
|
|
1979
|
+
readonly status: HttpStatus.INTERNAL_SERVER_ERROR;
|
|
1980
|
+
readonly message: "OTP email delivery requested but email channel not configured";
|
|
1981
|
+
};
|
|
1982
|
+
readonly OTP_COOLDOWN_ACTIVE: {
|
|
1983
|
+
readonly code: "notification.otp_cooldown_active";
|
|
1984
|
+
readonly status: HttpStatus.TOO_MANY_REQUESTS;
|
|
1985
|
+
readonly message: "Resend cooldown is active";
|
|
1986
|
+
};
|
|
1987
|
+
readonly OTP_NOT_FOUND: {
|
|
1988
|
+
readonly code: "notification.otp_not_found";
|
|
1989
|
+
readonly status: HttpStatus.NOT_FOUND;
|
|
1990
|
+
readonly message: "OTP not found or expired";
|
|
1991
|
+
};
|
|
1992
|
+
readonly OTP_EXPIRED: {
|
|
1993
|
+
readonly code: "notification.otp_expired";
|
|
1994
|
+
readonly status: HttpStatus.GONE;
|
|
1995
|
+
readonly message: "OTP code expired";
|
|
1996
|
+
};
|
|
1997
|
+
readonly OTP_MAX_ATTEMPTS_EXCEEDED: {
|
|
1998
|
+
readonly code: "notification.otp_max_attempts_exceeded";
|
|
1999
|
+
readonly status: HttpStatus.TOO_MANY_REQUESTS;
|
|
2000
|
+
readonly message: "Maximum OTP attempts exceeded";
|
|
2001
|
+
};
|
|
2002
|
+
readonly OTP_INVALID_CODE: {
|
|
2003
|
+
readonly code: "notification.otp_invalid_code";
|
|
2004
|
+
readonly status: HttpStatus.UNAUTHORIZED;
|
|
2005
|
+
readonly message: "Invalid OTP code";
|
|
2006
|
+
};
|
|
2007
|
+
readonly OTP_INVALID_LENGTH: {
|
|
2008
|
+
readonly code: "notification.otp_invalid_length";
|
|
2009
|
+
readonly status: HttpStatus.BAD_REQUEST;
|
|
2010
|
+
readonly message: "Invalid OTP length config";
|
|
2011
|
+
};
|
|
2012
|
+
readonly SMS_PROVIDER_NOT_CONFIGURED: {
|
|
2013
|
+
readonly code: "notification.sms_provider_not_configured";
|
|
2014
|
+
readonly status: HttpStatus.INTERNAL_SERVER_ERROR;
|
|
2015
|
+
readonly message: "SMS provider not configured";
|
|
2016
|
+
};
|
|
2017
|
+
readonly SMS_SEND_FAILED: {
|
|
2018
|
+
readonly code: "notification.sms_send_failed";
|
|
2019
|
+
readonly status: HttpStatus.BAD_GATEWAY;
|
|
2020
|
+
readonly message: "Failed to send SMS";
|
|
2021
|
+
};
|
|
2022
|
+
readonly SMS_INVALID_RECIPIENT: {
|
|
2023
|
+
readonly code: "notification.sms_invalid_recipient";
|
|
2024
|
+
readonly status: HttpStatus.BAD_REQUEST;
|
|
2025
|
+
readonly message: "Invalid phone number";
|
|
2026
|
+
};
|
|
2027
|
+
readonly PUSH_PROVIDER_NOT_CONFIGURED: {
|
|
2028
|
+
readonly code: "notification.push_provider_not_configured";
|
|
2029
|
+
readonly status: HttpStatus.INTERNAL_SERVER_ERROR;
|
|
2030
|
+
readonly message: "Push provider not configured";
|
|
2031
|
+
};
|
|
2032
|
+
readonly PUSH_SEND_FAILED: {
|
|
2033
|
+
readonly code: "notification.push_send_failed";
|
|
2034
|
+
readonly status: HttpStatus.BAD_GATEWAY;
|
|
2035
|
+
readonly message: "Failed to send push notification";
|
|
2036
|
+
};
|
|
2037
|
+
readonly AUDIT_LOG_FAILED: {
|
|
2038
|
+
readonly code: "notification.audit_log_failed";
|
|
2039
|
+
readonly status: HttpStatus.INTERNAL_SERVER_ERROR;
|
|
2040
|
+
readonly message: "Audit log write failed";
|
|
2041
|
+
};
|
|
2042
|
+
readonly CHANNEL_DISABLED: {
|
|
2043
|
+
readonly code: "notification.channel_disabled";
|
|
2044
|
+
readonly status: HttpStatus.NOT_IMPLEMENTED;
|
|
2045
|
+
readonly message: "Channel not enabled in module config";
|
|
2046
|
+
};
|
|
2047
|
+
};
|
|
2048
|
+
/** The symbolic key of any entry in {@link NOTIFICATION_ERROR_DEFINITIONS}. */
|
|
2049
|
+
type NotificationErrorKey = keyof typeof NOTIFICATION_ERROR_DEFINITIONS;
|
|
2050
|
+
|
|
2051
|
+
/**
|
|
2052
|
+
* @fileoverview `NotificationException` — the library's single typed HTTP error.
|
|
2053
|
+
* @layer domain
|
|
2054
|
+
*
|
|
2055
|
+
* Wraps every failure in the catalog shape `{ error: { code, message, details } }`
|
|
2056
|
+
* (mirrors `@bymax-one/nest-auth`). Because it extends NestJS's `HttpException`,
|
|
2057
|
+
* the framework's exception filter serializes it automatically; consumers branch
|
|
2058
|
+
* on `error.code` to localize the message.
|
|
2059
|
+
*/
|
|
2060
|
+
|
|
2061
|
+
/**
|
|
2062
|
+
* Typed HTTP exception over the notification error catalog.
|
|
2063
|
+
*
|
|
2064
|
+
* @example
|
|
2065
|
+
* ```ts
|
|
2066
|
+
* throw new NotificationException('OTP_INVALID_LENGTH', { provided: 0, allowed: '1-32' })
|
|
2067
|
+
* ```
|
|
2068
|
+
*/
|
|
2069
|
+
declare class NotificationException extends HttpException {
|
|
2070
|
+
/** The stable error code (e.g. `'notification.otp_invalid_code'`). */
|
|
2071
|
+
readonly code: string;
|
|
2072
|
+
/**
|
|
2073
|
+
* @param key - Catalog key selecting the code, default HTTP status, and message.
|
|
2074
|
+
* @param details - Optional structured context placed under `error.details`.
|
|
2075
|
+
* @param overrideStatus - Replaces the catalog's default HTTP status when supplied.
|
|
2076
|
+
* @param overrideMessage - Replaces the catalog's default message when supplied.
|
|
2077
|
+
*/
|
|
2078
|
+
constructor(key: NotificationErrorKey, details?: Record<string, unknown>, overrideStatus?: HttpStatus, overrideMessage?: string);
|
|
2079
|
+
}
|
|
2080
|
+
|
|
2081
|
+
/**
|
|
2082
|
+
* @fileoverview Public `OtpPurpose` string union for the shared subpath.
|
|
2083
|
+
* @layer shared
|
|
2084
|
+
*
|
|
2085
|
+
* Zero-dependency type importable from backend and frontend alike (e.g. to label
|
|
2086
|
+
* an OTP flow in the UI). No runtime code.
|
|
2087
|
+
*/
|
|
2088
|
+
/**
|
|
2089
|
+
* Purpose of an OTP flow.
|
|
2090
|
+
*
|
|
2091
|
+
* The five canonical purposes are listed as string literals so editors offer
|
|
2092
|
+
* autocompletion, while the `(string & {})` escape hatch keeps the union open to
|
|
2093
|
+
* custom purposes (e.g. `'invoice_verification'`) without losing that
|
|
2094
|
+
* autocompletion — a widening to a bare `string` would drop the literal hints.
|
|
2095
|
+
*
|
|
2096
|
+
* - `email_verification` — confirm ownership of an email address.
|
|
2097
|
+
* - `password_reset` — authorize a password change.
|
|
2098
|
+
* - `mfa_oob` — out-of-band multi-factor challenge.
|
|
2099
|
+
* - `phone_verification` — confirm a phone number; delivered manually until an SMS channel exists.
|
|
2100
|
+
* - `magic_link` — long, single-use token delivered as a URL rather than typed.
|
|
2101
|
+
*/
|
|
2102
|
+
type OtpPurpose = 'email_verification' | 'password_reset' | 'mfa_oob' | 'phone_verification' | 'magic_link' | (string & {});
|
|
2103
|
+
|
|
2104
|
+
/**
|
|
2105
|
+
* @fileoverview Public error-response envelope for the shared subpath.
|
|
2106
|
+
* @layer shared
|
|
2107
|
+
*
|
|
2108
|
+
* Zero-dependency type mirroring the body shape `NotificationException` emits on
|
|
2109
|
+
* the server, so a frontend can type the parsed JSON and match on `error.code`.
|
|
2110
|
+
*/
|
|
2111
|
+
/**
|
|
2112
|
+
* The JSON envelope every `NotificationException` serializes to.
|
|
2113
|
+
*
|
|
2114
|
+
* The frontend matches on `error.code` (a stable identifier from
|
|
2115
|
+
* `NOTIFICATION_ERROR_CODES`) to render a localized message; `error.message` is
|
|
2116
|
+
* the English default; `error.details` carries optional structured context and
|
|
2117
|
+
* is `null` when absent.
|
|
2118
|
+
*/
|
|
2119
|
+
interface NotificationErrorResponse {
|
|
2120
|
+
error: {
|
|
2121
|
+
code: string;
|
|
2122
|
+
message: string;
|
|
2123
|
+
details: Record<string, unknown> | null;
|
|
2124
|
+
};
|
|
2125
|
+
}
|
|
2126
|
+
|
|
2127
|
+
/**
|
|
2128
|
+
* @fileoverview Recommended OTP/cooldown TTLs for the shared subpath.
|
|
2129
|
+
* @layer shared
|
|
2130
|
+
*
|
|
2131
|
+
* Zero-dependency reference values a consumer can wire into per-purpose OTP
|
|
2132
|
+
* config (or display as "expires in N minutes" in the UI). They are suggestions,
|
|
2133
|
+
* not enforced defaults — the server defaults live in the OTP channel options.
|
|
2134
|
+
*/
|
|
2135
|
+
/**
|
|
2136
|
+
* Recommended time-to-live values (in seconds), with rationale per entry.
|
|
2137
|
+
*/
|
|
2138
|
+
declare const DEFAULT_TTLS: {
|
|
2139
|
+
/** Email verification: 1h — lets the user check their inbox at leisure. */
|
|
2140
|
+
readonly OTP_EMAIL_VERIFICATION_SECONDS: 3600;
|
|
2141
|
+
/** Password reset: 10min — short window limits exposure of a sensitive flow. */
|
|
2142
|
+
readonly OTP_PASSWORD_RESET_SECONDS: 600;
|
|
2143
|
+
/** MFA out-of-band: 5min — tight window for an interactive challenge. */
|
|
2144
|
+
readonly OTP_MFA_OOB_SECONDS: 300;
|
|
2145
|
+
/** Phone verification: 10min — covers SMS delivery latency. */
|
|
2146
|
+
readonly OTP_PHONE_VERIFICATION_SECONDS: 600;
|
|
2147
|
+
/** Magic link: 15min — slightly longer; a URL is often opened on another device. */
|
|
2148
|
+
readonly OTP_MAGIC_LINK_SECONDS: 900;
|
|
2149
|
+
/** Resend cooldown: 60s — throttles repeated sends to the same recipient. */
|
|
2150
|
+
readonly RESEND_COOLDOWN_SECONDS: 60;
|
|
2151
|
+
/** Generic fallback: 10min — used when no purpose-specific TTL applies. */
|
|
2152
|
+
readonly OTP_GENERIC_SECONDS: 600;
|
|
2153
|
+
};
|
|
2154
|
+
|
|
2155
|
+
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 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 TemplateDefinition, cooldownExpiresAt, formatCooldown, generateOtpCode, hashTenantRecipient, safeCompare, toRetryAfterHeader };
|