@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.
@@ -0,0 +1,2067 @@
1
+ import { HttpStatus, Injectable, Inject, Optional, Logger, Module, HttpException } from '@nestjs/common';
2
+ import { randomInt, timingSafeEqual, randomUUID, createHash } from 'crypto';
3
+ import { catchError, from, concatMap, throwError, map } from 'rxjs';
4
+
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __decorateClass = (decorators, target, key, kind) => {
7
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
8
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
9
+ if (decorator = decorators[i])
10
+ result = (decorator(result)) || result;
11
+ return result;
12
+ };
13
+ var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
14
+
15
+ // src/server/bymax-notification.constants.ts
16
+ var BYMAX_NOTIFICATION_OPTIONS = /* @__PURE__ */ Symbol("BYMAX_NOTIFICATION_OPTIONS");
17
+ var BYMAX_NOTIFICATION_EMAIL_PROVIDER = /* @__PURE__ */ Symbol("BYMAX_NOTIFICATION_EMAIL_PROVIDER");
18
+ var BYMAX_NOTIFICATION_OTP_STORAGE = /* @__PURE__ */ Symbol("BYMAX_NOTIFICATION_OTP_STORAGE");
19
+ var BYMAX_NOTIFICATION_SMS_PROVIDER = /* @__PURE__ */ Symbol("BYMAX_NOTIFICATION_SMS_PROVIDER");
20
+ var BYMAX_NOTIFICATION_PUSH_PROVIDER = /* @__PURE__ */ Symbol("BYMAX_NOTIFICATION_PUSH_PROVIDER");
21
+ var BYMAX_NOTIFICATION_TEMPLATE_RENDERER = /* @__PURE__ */ Symbol("BYMAX_NOTIFICATION_TEMPLATE_RENDERER");
22
+ var BYMAX_NOTIFICATION_LOG_REPOSITORY = /* @__PURE__ */ Symbol("BYMAX_NOTIFICATION_LOG_REPOSITORY");
23
+
24
+ // src/server/constants/default-options.constants.ts
25
+ var DEFAULT_MAX_ATTACHMENT_BYTES = 10485760;
26
+ var DEFAULT_GLOBAL_OPTIONS = {
27
+ redisNamespace: "notification",
28
+ defaultLocale: "en"
29
+ };
30
+ var DEFAULT_OTP_OPTIONS = {
31
+ defaultLength: 6,
32
+ defaultCodeType: "numeric",
33
+ defaultTtlSeconds: 600,
34
+ defaultMaxAttempts: 5,
35
+ resendCooldownSeconds: 60,
36
+ consumeOnVerify: false};
37
+ var DEFAULT_EMAIL_OPTIONS = {
38
+ defaultTags: [],
39
+ maxAttachmentBytes: DEFAULT_MAX_ATTACHMENT_BYTES
40
+ };
41
+ var DEFAULT_AUDIT_OPTIONS = {
42
+ swallowErrors: true
43
+ };
44
+
45
+ // src/server/config/resolved-options.ts
46
+ function resolveOptions(options) {
47
+ const resolved = {
48
+ global: resolveGlobal(options.global),
49
+ audit: resolveAudit(options),
50
+ ...options.email ? { email: resolveEmail(options.email) } : {},
51
+ ...options.otp ? { otp: resolveOtp(options.otp) } : {}
52
+ };
53
+ return deepFreeze(resolved);
54
+ }
55
+ function resolveGlobal(global) {
56
+ return {
57
+ redisNamespace: global?.redisNamespace ?? DEFAULT_GLOBAL_OPTIONS.redisNamespace,
58
+ defaultLocale: global?.defaultLocale ?? DEFAULT_GLOBAL_OPTIONS.defaultLocale,
59
+ ...global?.tenantIdResolver ? { tenantIdResolver: global.tenantIdResolver } : {}
60
+ };
61
+ }
62
+ function resolveEmail(email) {
63
+ return {
64
+ defaultFrom: email.defaultFrom,
65
+ defaultTags: email.defaultTags ?? DEFAULT_EMAIL_OPTIONS.defaultTags,
66
+ maxAttachmentBytes: email.maxAttachmentBytes ?? DEFAULT_EMAIL_OPTIONS.maxAttachmentBytes,
67
+ ...email.defaultFromName !== void 0 ? { defaultFromName: email.defaultFromName } : {},
68
+ ...email.defaultReplyTo !== void 0 ? { defaultReplyTo: email.defaultReplyTo } : {}
69
+ };
70
+ }
71
+ function resolveOtp(otp) {
72
+ const base = Object.freeze({
73
+ length: otp.defaultLength ?? DEFAULT_OTP_OPTIONS.defaultLength,
74
+ codeType: otp.defaultCodeType ?? DEFAULT_OTP_OPTIONS.defaultCodeType,
75
+ ttlSeconds: otp.defaultTtlSeconds ?? DEFAULT_OTP_OPTIONS.defaultTtlSeconds,
76
+ maxAttempts: otp.defaultMaxAttempts ?? DEFAULT_OTP_OPTIONS.defaultMaxAttempts,
77
+ resendCooldownSeconds: otp.resendCooldownSeconds ?? DEFAULT_OTP_OPTIONS.resendCooldownSeconds
78
+ });
79
+ const entries = Object.entries(otp.perPurpose ?? {}).map(
80
+ ([purpose, partial]) => [purpose, { ...base, ...partial }]
81
+ );
82
+ const perPurpose = Object.fromEntries(entries);
83
+ const perPurposeMap = new Map(entries);
84
+ return {
85
+ defaultLength: base.length,
86
+ defaultCodeType: base.codeType,
87
+ defaultTtlSeconds: base.ttlSeconds,
88
+ defaultMaxAttempts: base.maxAttempts,
89
+ resendCooldownSeconds: base.resendCooldownSeconds,
90
+ consumeOnVerify: otp.consumeOnVerify ?? DEFAULT_OTP_OPTIONS.consumeOnVerify,
91
+ perPurpose,
92
+ resolveForPurpose: (purpose) => perPurposeMap.get(purpose) ?? base
93
+ };
94
+ }
95
+ function resolveAudit(options) {
96
+ return {
97
+ swallowErrors: options.audit?.swallowErrors ?? DEFAULT_AUDIT_OPTIONS.swallowErrors,
98
+ maskRecipient: options.audit?.maskRecipient ?? ((recipient) => recipient)
99
+ };
100
+ }
101
+ function deepFreeze(value) {
102
+ if (Object(value) === value) {
103
+ for (const nested of Object.values(value)) {
104
+ deepFreeze(nested);
105
+ }
106
+ Object.freeze(value);
107
+ }
108
+ return value;
109
+ }
110
+
111
+ // src/server/config/default-options.ts
112
+ var VALID_CODE_TYPES = ["numeric", "alpha", "alphanumeric"];
113
+ var OTP_MIN_LENGTH = 1;
114
+ var OTP_MAX_LENGTH = 32;
115
+
116
+ // src/shared/constants/error-codes.ts
117
+ var NOTIFICATION_ERROR_CODES = {
118
+ EMAIL_PROVIDER_NOT_CONFIGURED: "notification.email_provider_not_configured",
119
+ EMAIL_SEND_FAILED: "notification.email_send_failed",
120
+ EMAIL_ATTACHMENTS_TOO_LARGE: "notification.email_attachments_too_large",
121
+ EMAIL_INVALID_RECIPIENT: "notification.email_invalid_recipient",
122
+ /** The email payload carries neither a `template` nor a `subject` + `html` body source. */
123
+ EMAIL_MISSING_BODY: "notification.email_missing_body",
124
+ TEMPLATE_NOT_FOUND: "notification.template_not_found",
125
+ TEMPLATE_RENDER_FAILED: "notification.template_render_failed",
126
+ OTP_STORAGE_NOT_CONFIGURED: "notification.otp_storage_not_configured",
127
+ OTP_EMAIL_DELIVERY_NOT_CONFIGURED: "notification.otp_email_delivery_not_configured",
128
+ OTP_COOLDOWN_ACTIVE: "notification.otp_cooldown_active",
129
+ OTP_NOT_FOUND: "notification.otp_not_found",
130
+ OTP_EXPIRED: "notification.otp_expired",
131
+ OTP_MAX_ATTEMPTS_EXCEEDED: "notification.otp_max_attempts_exceeded",
132
+ OTP_INVALID_CODE: "notification.otp_invalid_code",
133
+ OTP_INVALID_LENGTH: "notification.otp_invalid_length",
134
+ SMS_PROVIDER_NOT_CONFIGURED: "notification.sms_provider_not_configured",
135
+ SMS_SEND_FAILED: "notification.sms_send_failed",
136
+ SMS_INVALID_RECIPIENT: "notification.sms_invalid_recipient",
137
+ PUSH_PROVIDER_NOT_CONFIGURED: "notification.push_provider_not_configured",
138
+ PUSH_SEND_FAILED: "notification.push_send_failed",
139
+ AUDIT_LOG_FAILED: "notification.audit_log_failed",
140
+ CHANNEL_DISABLED: "notification.channel_disabled"
141
+ };
142
+
143
+ // src/server/errors/notification-error-codes.ts
144
+ var NOTIFICATION_ERROR_DEFINITIONS = {
145
+ EMAIL_PROVIDER_NOT_CONFIGURED: {
146
+ code: NOTIFICATION_ERROR_CODES.EMAIL_PROVIDER_NOT_CONFIGURED,
147
+ status: HttpStatus.INTERNAL_SERVER_ERROR,
148
+ message: "Email provider not configured"
149
+ },
150
+ EMAIL_SEND_FAILED: {
151
+ code: NOTIFICATION_ERROR_CODES.EMAIL_SEND_FAILED,
152
+ status: HttpStatus.BAD_GATEWAY,
153
+ message: "Failed to send email"
154
+ },
155
+ EMAIL_ATTACHMENTS_TOO_LARGE: {
156
+ code: NOTIFICATION_ERROR_CODES.EMAIL_ATTACHMENTS_TOO_LARGE,
157
+ status: HttpStatus.PAYLOAD_TOO_LARGE,
158
+ message: "Email attachments exceed size limit"
159
+ },
160
+ EMAIL_INVALID_RECIPIENT: {
161
+ code: NOTIFICATION_ERROR_CODES.EMAIL_INVALID_RECIPIENT,
162
+ status: HttpStatus.BAD_REQUEST,
163
+ message: "Invalid recipient email"
164
+ },
165
+ EMAIL_MISSING_BODY: {
166
+ code: NOTIFICATION_ERROR_CODES.EMAIL_MISSING_BODY,
167
+ status: HttpStatus.BAD_REQUEST,
168
+ message: "Email payload requires either a template or a subject and html body"
169
+ },
170
+ TEMPLATE_NOT_FOUND: {
171
+ code: NOTIFICATION_ERROR_CODES.TEMPLATE_NOT_FOUND,
172
+ status: HttpStatus.INTERNAL_SERVER_ERROR,
173
+ message: "Email template not found"
174
+ },
175
+ TEMPLATE_RENDER_FAILED: {
176
+ code: NOTIFICATION_ERROR_CODES.TEMPLATE_RENDER_FAILED,
177
+ status: HttpStatus.INTERNAL_SERVER_ERROR,
178
+ message: "Failed to render email template"
179
+ },
180
+ OTP_STORAGE_NOT_CONFIGURED: {
181
+ code: NOTIFICATION_ERROR_CODES.OTP_STORAGE_NOT_CONFIGURED,
182
+ status: HttpStatus.INTERNAL_SERVER_ERROR,
183
+ message: "OTP storage not configured"
184
+ },
185
+ OTP_EMAIL_DELIVERY_NOT_CONFIGURED: {
186
+ code: NOTIFICATION_ERROR_CODES.OTP_EMAIL_DELIVERY_NOT_CONFIGURED,
187
+ status: HttpStatus.INTERNAL_SERVER_ERROR,
188
+ message: "OTP email delivery requested but email channel not configured"
189
+ },
190
+ OTP_COOLDOWN_ACTIVE: {
191
+ code: NOTIFICATION_ERROR_CODES.OTP_COOLDOWN_ACTIVE,
192
+ status: HttpStatus.TOO_MANY_REQUESTS,
193
+ message: "Resend cooldown is active"
194
+ },
195
+ OTP_NOT_FOUND: {
196
+ code: NOTIFICATION_ERROR_CODES.OTP_NOT_FOUND,
197
+ status: HttpStatus.NOT_FOUND,
198
+ message: "OTP not found or expired"
199
+ },
200
+ OTP_EXPIRED: {
201
+ code: NOTIFICATION_ERROR_CODES.OTP_EXPIRED,
202
+ status: HttpStatus.GONE,
203
+ message: "OTP code expired"
204
+ },
205
+ OTP_MAX_ATTEMPTS_EXCEEDED: {
206
+ code: NOTIFICATION_ERROR_CODES.OTP_MAX_ATTEMPTS_EXCEEDED,
207
+ status: HttpStatus.TOO_MANY_REQUESTS,
208
+ message: "Maximum OTP attempts exceeded"
209
+ },
210
+ OTP_INVALID_CODE: {
211
+ code: NOTIFICATION_ERROR_CODES.OTP_INVALID_CODE,
212
+ status: HttpStatus.UNAUTHORIZED,
213
+ message: "Invalid OTP code"
214
+ },
215
+ OTP_INVALID_LENGTH: {
216
+ code: NOTIFICATION_ERROR_CODES.OTP_INVALID_LENGTH,
217
+ status: HttpStatus.BAD_REQUEST,
218
+ message: "Invalid OTP length config"
219
+ },
220
+ SMS_PROVIDER_NOT_CONFIGURED: {
221
+ code: NOTIFICATION_ERROR_CODES.SMS_PROVIDER_NOT_CONFIGURED,
222
+ status: HttpStatus.INTERNAL_SERVER_ERROR,
223
+ message: "SMS provider not configured"
224
+ },
225
+ SMS_SEND_FAILED: {
226
+ code: NOTIFICATION_ERROR_CODES.SMS_SEND_FAILED,
227
+ status: HttpStatus.BAD_GATEWAY,
228
+ message: "Failed to send SMS"
229
+ },
230
+ SMS_INVALID_RECIPIENT: {
231
+ code: NOTIFICATION_ERROR_CODES.SMS_INVALID_RECIPIENT,
232
+ status: HttpStatus.BAD_REQUEST,
233
+ message: "Invalid phone number"
234
+ },
235
+ PUSH_PROVIDER_NOT_CONFIGURED: {
236
+ code: NOTIFICATION_ERROR_CODES.PUSH_PROVIDER_NOT_CONFIGURED,
237
+ status: HttpStatus.INTERNAL_SERVER_ERROR,
238
+ message: "Push provider not configured"
239
+ },
240
+ PUSH_SEND_FAILED: {
241
+ code: NOTIFICATION_ERROR_CODES.PUSH_SEND_FAILED,
242
+ status: HttpStatus.BAD_GATEWAY,
243
+ message: "Failed to send push notification"
244
+ },
245
+ AUDIT_LOG_FAILED: {
246
+ code: NOTIFICATION_ERROR_CODES.AUDIT_LOG_FAILED,
247
+ status: HttpStatus.INTERNAL_SERVER_ERROR,
248
+ message: "Audit log write failed"
249
+ },
250
+ CHANNEL_DISABLED: {
251
+ code: NOTIFICATION_ERROR_CODES.CHANNEL_DISABLED,
252
+ status: HttpStatus.NOT_IMPLEMENTED,
253
+ message: "Channel not enabled in module config"
254
+ }
255
+ };
256
+ var NOTIFICATION_ERROR_DEFINITION_MAP = new Map(
257
+ Object.entries(NOTIFICATION_ERROR_DEFINITIONS)
258
+ );
259
+
260
+ // src/server/errors/notification-exception.ts
261
+ var FALLBACK_DEFINITION = {
262
+ code: "notification.unknown_error",
263
+ status: HttpStatus.INTERNAL_SERVER_ERROR,
264
+ message: "Unknown notification error"
265
+ };
266
+ var NotificationException = class extends HttpException {
267
+ /**
268
+ * @param key - Catalog key selecting the code, default HTTP status, and message.
269
+ * @param details - Optional structured context placed under `error.details`.
270
+ * @param overrideStatus - Replaces the catalog's default HTTP status when supplied.
271
+ * @param overrideMessage - Replaces the catalog's default message when supplied.
272
+ */
273
+ constructor(key, details, overrideStatus, overrideMessage) {
274
+ const definition = NOTIFICATION_ERROR_DEFINITION_MAP.get(key) ?? FALLBACK_DEFINITION;
275
+ const body = {
276
+ error: {
277
+ code: definition.code,
278
+ message: overrideMessage ?? definition.message,
279
+ details: details ?? null
280
+ }
281
+ };
282
+ super(body, overrideStatus ?? definition.status);
283
+ this.code = definition.code;
284
+ }
285
+ };
286
+
287
+ // src/server/config/validate-options.ts
288
+ function validateOptions(options) {
289
+ if (!options.email && !options.otp && !options.sms && !options.push) {
290
+ throw new Error(
291
+ "[BymaxNotificationModule] At least one channel must be configured (email, otp, sms, or push)"
292
+ );
293
+ }
294
+ if (options.sms) {
295
+ throw new Error(
296
+ "[BymaxNotificationModule] SMS channel is not yet implemented. Remove 'sms' from options."
297
+ );
298
+ }
299
+ if (options.push) {
300
+ throw new Error(
301
+ "[BymaxNotificationModule] Push channel is not yet implemented. Remove 'push' from options."
302
+ );
303
+ }
304
+ if (options.email) {
305
+ validateEmailOptions(options.email);
306
+ }
307
+ if (options.otp) {
308
+ validateOtpOptions(options.otp);
309
+ }
310
+ if (options.audit && !options.audit.repository) {
311
+ throw new Error(
312
+ "[BymaxNotificationModule] options.audit.repository is required when 'audit' is configured"
313
+ );
314
+ }
315
+ }
316
+ function validateEmailOptions(email) {
317
+ if (!email.provider) {
318
+ throw new Error(
319
+ "[BymaxNotificationModule] options.email.provider is required when 'email' is configured"
320
+ );
321
+ }
322
+ if (typeof email.defaultFrom !== "string" || email.defaultFrom.trim() === "") {
323
+ throw new Error(
324
+ "[BymaxNotificationModule] options.email.defaultFrom must be a non-empty string"
325
+ );
326
+ }
327
+ if (!email.defaultFrom.includes("@")) {
328
+ throw new Error(
329
+ "[BymaxNotificationModule] options.email.defaultFrom does not look like an email"
330
+ );
331
+ }
332
+ }
333
+ function validateOtpOptions(otp) {
334
+ if (!otp.storage) {
335
+ throw new Error(
336
+ "[BymaxNotificationModule] options.otp.storage is required when 'otp' is configured"
337
+ );
338
+ }
339
+ if (otp.defaultLength !== void 0) {
340
+ const length = otp.defaultLength;
341
+ if (!Number.isInteger(length) || length < OTP_MIN_LENGTH || length > OTP_MAX_LENGTH) {
342
+ throw new NotificationException("OTP_INVALID_LENGTH", {
343
+ provided: length,
344
+ allowed: `${OTP_MIN_LENGTH}-${OTP_MAX_LENGTH}`
345
+ });
346
+ }
347
+ }
348
+ if (otp.defaultCodeType !== void 0 && !VALID_CODE_TYPES.includes(otp.defaultCodeType)) {
349
+ throw new Error(
350
+ `[BymaxNotificationModule] options.otp.defaultCodeType must be one of: ${VALID_CODE_TYPES.join(", ")}`
351
+ );
352
+ }
353
+ if (otp.defaultTtlSeconds !== void 0 && otp.defaultTtlSeconds <= 0) {
354
+ throw new Error(
355
+ "[BymaxNotificationModule] options.otp.defaultTtlSeconds must be greater than 0"
356
+ );
357
+ }
358
+ if (otp.defaultMaxAttempts !== void 0 && otp.defaultMaxAttempts < 1) {
359
+ throw new Error("[BymaxNotificationModule] options.otp.defaultMaxAttempts must be at least 1");
360
+ }
361
+ if (otp.resendCooldownSeconds !== void 0 && otp.resendCooldownSeconds < 0) {
362
+ throw new Error(
363
+ "[BymaxNotificationModule] options.otp.resendCooldownSeconds must be 0 or greater"
364
+ );
365
+ }
366
+ }
367
+ var TEMPLATE_VAR_PATTERN = /\{\{\s*([\w.]+)\s*\}\}/g;
368
+ var DEFAULT_FALLBACK_LOCALES = ["en"];
369
+ var DefaultTemplateRenderer = class {
370
+ /**
371
+ * @param options - Templates plus locale/missing-variable/nested-path policy.
372
+ * @throws Error When a registered template lacks a string `subject`/`html`, or
373
+ * carries a non-string `text`.
374
+ */
375
+ constructor(options = {}) {
376
+ this.name = "default-interpolation";
377
+ const entries = Object.entries(options.templates ?? {});
378
+ for (const [key, template] of entries) {
379
+ this.assertValidTemplate(key, template);
380
+ }
381
+ this.templates = new Map(entries);
382
+ this.fallbackLocales = options.fallbackLocales ?? DEFAULT_FALLBACK_LOCALES;
383
+ this.onMissingVar = options.onMissingVar ?? "empty";
384
+ this.enableNestedPaths = options.enableNestedPaths ?? false;
385
+ }
386
+ /**
387
+ * Whether a template is registered for the exact name + locale.
388
+ *
389
+ * @param templateName - Template name.
390
+ * @param locale - Requested locale.
391
+ * @returns `true` when the `${name}::${locale}` key exists.
392
+ */
393
+ async hasTemplate(templateName, locale) {
394
+ return this.templates.has(this.key(templateName, locale));
395
+ }
396
+ /**
397
+ * Renders a template, escaping interpolated values in the html body only.
398
+ *
399
+ * @param templateName - Template name.
400
+ * @param data - Variables to interpolate.
401
+ * @param locale - Requested locale; resolved via the fallback chain.
402
+ * @returns The rendered subject + html (+ text when the template has one).
403
+ * @throws Error When no template in the fallback chain matches, or a variable is
404
+ * missing and `onMissingVar` is `'throw'`.
405
+ */
406
+ async render(templateName, data, locale) {
407
+ const template = this.resolveTemplate(templateName, locale);
408
+ const resolve = this.buildResolver(data);
409
+ return {
410
+ subject: this.interpolate(template.subject, false, resolve),
411
+ html: this.interpolate(template.html, true, resolve),
412
+ ...template.text !== void 0 ? { text: this.interpolate(template.text, false, resolve) } : {}
413
+ };
414
+ }
415
+ /** Resolves the first registered template along `[locale, ...fallbackLocales]`. */
416
+ resolveTemplate(templateName, locale) {
417
+ const chain = [locale, ...this.fallbackLocales.filter((candidate) => candidate !== locale)];
418
+ for (const candidate of chain) {
419
+ const template = this.templates.get(this.key(templateName, candidate));
420
+ if (template) {
421
+ return template;
422
+ }
423
+ }
424
+ throw new Error(
425
+ `Template not found: ${templateName} (locale=${locale}, tried=${chain.join(",")})`
426
+ );
427
+ }
428
+ /** Replaces every `{{path}}` placeholder, escaping only when `escape` is `true`. */
429
+ interpolate(source, escape, resolve) {
430
+ return source.replace(TEMPLATE_VAR_PATTERN, (_match, path) => {
431
+ const value = resolve(path);
432
+ if (value === void 0 || value === null) {
433
+ if (this.onMissingVar === "throw") {
434
+ throw new Error(`Missing template variable: ${path}`);
435
+ }
436
+ return "";
437
+ }
438
+ const stringValue = String(value);
439
+ return escape ? this.escapeHtml(stringValue) : stringValue;
440
+ });
441
+ }
442
+ /**
443
+ * Builds a variable resolver for one render call. Lookups go through a `Map`
444
+ * built from own enumerable entries (never bracket indexing) so neither flat
445
+ * nor nested resolution can reach inherited/prototype keys.
446
+ */
447
+ buildResolver(data) {
448
+ if (!this.enableNestedPaths) {
449
+ const values = new Map(Object.entries(data));
450
+ return (path) => values.get(path);
451
+ }
452
+ return (path) => this.resolveNested(data, path);
453
+ }
454
+ /** Walks a dotted path through own enumerable keys, stopping at any non-object. */
455
+ resolveNested(data, path) {
456
+ let current = data;
457
+ for (const key of path.split(".")) {
458
+ if (current === null || current === void 0 || typeof current !== "object") {
459
+ return void 0;
460
+ }
461
+ current = new Map(Object.entries(current)).get(key);
462
+ }
463
+ return current;
464
+ }
465
+ /**
466
+ * Validates a registered template shape, throwing on the offending key. The
467
+ * optional `text` body, when present, must be a string — a non-string `text`
468
+ * would otherwise pass construction and crash at render time inside
469
+ * `String.prototype.replace`.
470
+ */
471
+ assertValidTemplate(key, template) {
472
+ const shape = template;
473
+ if (shape === null || typeof shape !== "object" || typeof shape.subject !== "string" || typeof shape.html !== "string" || shape.text !== void 0 && typeof shape.text !== "string") {
474
+ throw new Error(`Invalid template "${key}" \u2014 must have { subject: string, html: string }`);
475
+ }
476
+ }
477
+ /** Builds the `${templateName}::${locale}` registry key. */
478
+ key(templateName, locale) {
479
+ return `${templateName}::${locale}`;
480
+ }
481
+ /** Escapes the five HTML-significant characters. */
482
+ escapeHtml(value) {
483
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
484
+ }
485
+ };
486
+ DefaultTemplateRenderer = __decorateClass([
487
+ Injectable()
488
+ ], DefaultTemplateRenderer);
489
+ var NoOpNotificationLogRepository = class {
490
+ constructor() {
491
+ this.name = "noop";
492
+ }
493
+ /**
494
+ * Discards the entry.
495
+ *
496
+ * @param _entry - The audit entry; intentionally ignored.
497
+ */
498
+ async create(_entry) {
499
+ }
500
+ };
501
+ NoOpNotificationLogRepository = __decorateClass([
502
+ Injectable()
503
+ ], NoOpNotificationLogRepository);
504
+ var FALLBACK_LOCALE = "en";
505
+ var EmailService = class {
506
+ /**
507
+ * @param options - The resolved, frozen module options.
508
+ * @param provider - The configured email send provider.
509
+ * @param renderer - The configured template renderer.
510
+ * @param auditLog - The audit-log repository (no-op when none configured).
511
+ */
512
+ constructor(options, provider, renderer, auditLog) {
513
+ this.options = options;
514
+ this.provider = provider;
515
+ this.renderer = renderer;
516
+ this.auditLog = auditLog;
517
+ }
518
+ /**
519
+ * Whether the email channel is configured and its provider is ready.
520
+ *
521
+ * @returns `true` when both hold.
522
+ */
523
+ isConfigured() {
524
+ return Boolean(this.options.email) && this.provider.isConfigured();
525
+ }
526
+ /**
527
+ * Sends an email whose subject/html/text the caller already produced.
528
+ *
529
+ * @param input - The message envelope and rendered body.
530
+ * @returns The provider's message id.
531
+ * @throws NotificationException `EMAIL_PROVIDER_NOT_CONFIGURED`, `EMAIL_ATTACHMENTS_TOO_LARGE`,
532
+ * `EMAIL_SEND_FAILED`, or `AUDIT_LOG_FAILED` (only when `audit.swallowErrors` is `false`).
533
+ */
534
+ async send(input) {
535
+ const email = this.requireEmailOptions();
536
+ this.guardAttachmentSize(input.attachments, email.maxAttachmentBytes);
537
+ const sendOptions = this.buildSendOptions(input, email);
538
+ const recipient = this.maskRecipients(input.to);
539
+ try {
540
+ const result = await this.provider.send(sendOptions);
541
+ await this.audit(
542
+ this.auditEntry("sent", input.tenantId, recipient, input.userId, {
543
+ messageId: result.messageId
544
+ })
545
+ );
546
+ return { messageId: result.messageId };
547
+ } catch (error) {
548
+ if (error instanceof NotificationException) {
549
+ throw error;
550
+ }
551
+ await this.audit(
552
+ this.auditEntry("failed", input.tenantId, recipient, input.userId, {
553
+ errorMessage: error instanceof Error ? error.message : String(error)
554
+ })
555
+ );
556
+ throw new NotificationException("EMAIL_SEND_FAILED", { providerName: this.provider.name });
557
+ }
558
+ }
559
+ /**
560
+ * Renders a template (with an `en` fallback) and sends the result.
561
+ *
562
+ * @param input - The template name, data, and envelope.
563
+ * @returns The provider's message id.
564
+ * @throws NotificationException `TEMPLATE_NOT_FOUND` (no template for the locale nor `en`),
565
+ * `TEMPLATE_RENDER_FAILED` (the renderer threw), plus anything {@link EmailService.send} throws.
566
+ */
567
+ async sendTemplate(input) {
568
+ const requestedLocale = input.locale ?? this.options.global.defaultLocale;
569
+ const locale = await this.resolveTemplateLocale(input.template, requestedLocale);
570
+ const rendered = await this.renderTemplate(input.template, input.data, locale);
571
+ const tags = [...input.tags ?? [], { name: "template", value: input.template }];
572
+ return this.send({
573
+ tenantId: input.tenantId,
574
+ to: input.to,
575
+ subject: rendered.subject,
576
+ html: rendered.html,
577
+ tags,
578
+ ...rendered.text !== void 0 ? { text: rendered.text } : {},
579
+ ...input.from !== void 0 ? { from: input.from } : {},
580
+ ...input.fromName !== void 0 ? { fromName: input.fromName } : {},
581
+ ...input.replyTo !== void 0 ? { replyTo: input.replyTo } : {},
582
+ ...input.userId !== void 0 ? { userId: input.userId } : {}
583
+ });
584
+ }
585
+ /** Returns the resolved email options or throws when the channel is not configured. */
586
+ requireEmailOptions() {
587
+ if (!this.options.email || !this.provider.isConfigured()) {
588
+ throw new NotificationException("EMAIL_PROVIDER_NOT_CONFIGURED");
589
+ }
590
+ return this.options.email;
591
+ }
592
+ /** Throws `EMAIL_ATTACHMENTS_TOO_LARGE` when the attachments exceed the byte budget. */
593
+ guardAttachmentSize(attachments, maxBytes) {
594
+ if (!attachments) {
595
+ return;
596
+ }
597
+ const totalBytes = attachments.reduce(
598
+ (sum, { content }) => sum + (typeof content === "string" ? Buffer.byteLength(content) : content.length),
599
+ 0
600
+ );
601
+ if (totalBytes > maxBytes) {
602
+ throw new NotificationException("EMAIL_ATTACHMENTS_TOO_LARGE", {
603
+ totalBytes,
604
+ limit: maxBytes
605
+ });
606
+ }
607
+ }
608
+ /** Applies channel defaults and concatenates default + caller tags. */
609
+ buildSendOptions(input, email) {
610
+ const fromName = input.fromName ?? email.defaultFromName;
611
+ const replyTo = input.replyTo ?? email.defaultReplyTo;
612
+ return {
613
+ to: input.to,
614
+ from: input.from ?? email.defaultFrom,
615
+ subject: input.subject,
616
+ html: input.html,
617
+ tags: [...email.defaultTags, ...input.tags ?? []],
618
+ ...fromName !== void 0 ? { fromName } : {},
619
+ ...replyTo !== void 0 ? { replyTo } : {},
620
+ ...input.text !== void 0 ? { text: input.text } : {},
621
+ ...input.cc !== void 0 ? { cc: input.cc } : {},
622
+ ...input.bcc !== void 0 ? { bcc: input.bcc } : {},
623
+ ...input.attachments !== void 0 ? { attachments: input.attachments } : {}
624
+ };
625
+ }
626
+ /** Picks the locale that has a template, falling back to `en`, else throws `TEMPLATE_NOT_FOUND`. */
627
+ async resolveTemplateLocale(template, locale) {
628
+ if (await this.renderer.hasTemplate(template, locale)) {
629
+ return locale;
630
+ }
631
+ if (await this.renderer.hasTemplate(template, FALLBACK_LOCALE)) {
632
+ return FALLBACK_LOCALE;
633
+ }
634
+ throw new NotificationException("TEMPLATE_NOT_FOUND", { template, locale });
635
+ }
636
+ /** Renders the template, mapping a renderer failure to `TEMPLATE_RENDER_FAILED`. */
637
+ async renderTemplate(template, data, locale) {
638
+ try {
639
+ return await this.renderer.render(template, data, locale);
640
+ } catch {
641
+ throw new NotificationException("TEMPLATE_RENDER_FAILED", { template });
642
+ }
643
+ }
644
+ /** Builds an audit entry with the recipient already masked. */
645
+ auditEntry(verb, tenantId, recipient, userId, extra) {
646
+ return {
647
+ timestamp: Date.now(),
648
+ tenantId,
649
+ channel: "email",
650
+ verb,
651
+ recipient,
652
+ providerName: this.provider.name,
653
+ ...extra.messageId !== void 0 ? { messageId: extra.messageId } : {},
654
+ ...extra.errorMessage !== void 0 ? { errorMessage: extra.errorMessage } : {},
655
+ ...userId !== void 0 ? { userId } : {}
656
+ };
657
+ }
658
+ /** Writes an audit entry, swallowing failures unless `audit.swallowErrors` is `false`. */
659
+ async audit(entry) {
660
+ try {
661
+ await this.auditLog.create(entry);
662
+ } catch (error) {
663
+ if (!this.options.audit.swallowErrors) {
664
+ throw new NotificationException("AUDIT_LOG_FAILED", {
665
+ cause: error instanceof Error ? error.message : String(error)
666
+ });
667
+ }
668
+ }
669
+ }
670
+ /** Masks the recipient(s) per `audit.maskRecipient`, joining an array with `', '`. */
671
+ maskRecipients(to) {
672
+ const mask = this.options.audit.maskRecipient;
673
+ return Array.isArray(to) ? to.map((recipient) => mask(recipient)).join(", ") : mask(to);
674
+ }
675
+ };
676
+ EmailService = __decorateClass([
677
+ Injectable(),
678
+ __decorateParam(0, Inject(BYMAX_NOTIFICATION_OPTIONS)),
679
+ __decorateParam(1, Inject(BYMAX_NOTIFICATION_EMAIL_PROVIDER)),
680
+ __decorateParam(2, Inject(BYMAX_NOTIFICATION_TEMPLATE_RENDERER)),
681
+ __decorateParam(3, Inject(BYMAX_NOTIFICATION_LOG_REPOSITORY))
682
+ ], EmailService);
683
+ var NotificationService = class {
684
+ /**
685
+ * @param emailService - The email service, present only when the email channel is configured.
686
+ * @param otpService - The OTP service, present only when the OTP channel is configured.
687
+ */
688
+ constructor(emailService, otpService) {
689
+ this.emailService = emailService;
690
+ this.otpService = otpService;
691
+ }
692
+ /**
693
+ * Dispatches a notification to the channel named in `input`.
694
+ *
695
+ * @param input - The channel-discriminated dispatch request.
696
+ * @returns The channel-discriminated result.
697
+ * @throws NotificationException `CHANNEL_DISABLED` (channel not configured) or
698
+ * `EMAIL_MISSING_BODY` (email payload has neither a template nor subject+html).
699
+ */
700
+ async dispatch(input) {
701
+ if (input.channel === "email") {
702
+ return {
703
+ channel: "email",
704
+ messageId: await this.dispatchEmail(input.tenantId, input.payload)
705
+ };
706
+ }
707
+ return { channel: "otp", result: await this.dispatchOtp(input.tenantId, input.payload) };
708
+ }
709
+ /**
710
+ * Lists the channels whose service is present and reports itself configured.
711
+ *
712
+ * @returns The enabled channels.
713
+ */
714
+ getEnabledChannels() {
715
+ const channels = [];
716
+ if (this.emailService?.isConfigured()) {
717
+ channels.push("email");
718
+ }
719
+ if (this.otpService?.isConfigured()) {
720
+ channels.push("otp");
721
+ }
722
+ return channels;
723
+ }
724
+ /**
725
+ * Returns the email service or throws when the email channel is not enabled.
726
+ *
727
+ * @returns The email service.
728
+ * @throws NotificationException `CHANNEL_DISABLED` when email is not configured.
729
+ */
730
+ getEmail() {
731
+ if (!this.emailService) {
732
+ throw new NotificationException("CHANNEL_DISABLED", { channel: "email" });
733
+ }
734
+ return this.emailService;
735
+ }
736
+ /**
737
+ * Returns the OTP service or throws when the OTP channel is not enabled.
738
+ *
739
+ * @returns The OTP service.
740
+ * @throws NotificationException `CHANNEL_DISABLED` when OTP is not configured.
741
+ */
742
+ getOtp() {
743
+ if (!this.otpService) {
744
+ throw new NotificationException("CHANNEL_DISABLED", { channel: "otp" });
745
+ }
746
+ return this.otpService;
747
+ }
748
+ /** Routes an email dispatch to `sendTemplate` (template) or `send` (raw body). */
749
+ async dispatchEmail(tenantId, payload) {
750
+ const email = this.getEmail();
751
+ if (payload.template !== void 0) {
752
+ const input = this.toTemplateInput(tenantId, payload.template, payload);
753
+ return (await email.sendTemplate(input)).messageId;
754
+ }
755
+ if (payload.subject !== void 0 && payload.html !== void 0) {
756
+ const input = this.toSendInput(tenantId, payload.subject, payload.html, payload);
757
+ return (await email.send(input)).messageId;
758
+ }
759
+ throw new NotificationException("EMAIL_MISSING_BODY", {
760
+ hint: "payload requires either `template` OR `{ subject, html }`"
761
+ });
762
+ }
763
+ /** Routes an OTP dispatch by `action`, defaulting to `generate`. */
764
+ async dispatchOtp(tenantId, payload) {
765
+ const otp = this.getOtp();
766
+ const action = payload.action ?? "generate";
767
+ const ref = {
768
+ tenantId,
769
+ recipient: payload.recipient,
770
+ purpose: payload.purpose,
771
+ ...payload.userId !== void 0 ? { userId: payload.userId } : {}
772
+ };
773
+ if (action === "verify") {
774
+ return otp.verify({ ...ref, code: payload.code ?? "" });
775
+ }
776
+ if (action === "consume") {
777
+ return otp.consume(ref);
778
+ }
779
+ return otp.generate(this.toGenerateInput(ref, payload));
780
+ }
781
+ /** Builds the `sendTemplate` input from a resolved template name and payload. */
782
+ toTemplateInput(tenantId, template, payload) {
783
+ return {
784
+ tenantId,
785
+ to: payload.to,
786
+ template,
787
+ data: payload.data ?? {},
788
+ ...payload.locale !== void 0 ? { locale: payload.locale } : {},
789
+ ...this.commonEmailFields(payload)
790
+ };
791
+ }
792
+ /** Builds the raw `send` input from a resolved subject/html and payload. */
793
+ toSendInput(tenantId, subject, html, payload) {
794
+ return {
795
+ tenantId,
796
+ to: payload.to,
797
+ subject,
798
+ html,
799
+ ...payload.text !== void 0 ? { text: payload.text } : {},
800
+ ...this.commonEmailFields(payload)
801
+ };
802
+ }
803
+ /** The optional envelope fields shared by both email paths. */
804
+ commonEmailFields(payload) {
805
+ return {
806
+ ...payload.from !== void 0 ? { from: payload.from } : {},
807
+ ...payload.fromName !== void 0 ? { fromName: payload.fromName } : {},
808
+ ...payload.replyTo !== void 0 ? { replyTo: payload.replyTo } : {},
809
+ ...payload.tags !== void 0 ? { tags: payload.tags } : {},
810
+ ...payload.userId !== void 0 ? { userId: payload.userId } : {}
811
+ };
812
+ }
813
+ /** Builds the `generate` input from a reference and an OTP dispatch payload. */
814
+ toGenerateInput(ref, payload) {
815
+ return {
816
+ ...ref,
817
+ ...payload.deliverVia !== void 0 ? { deliverVia: payload.deliverVia } : {},
818
+ ...payload.emailTemplate !== void 0 ? { emailTemplate: payload.emailTemplate } : {},
819
+ ...payload.emailData !== void 0 ? { emailData: payload.emailData } : {},
820
+ ...payload.locale !== void 0 ? { locale: payload.locale } : {}
821
+ };
822
+ }
823
+ };
824
+ NotificationService = __decorateClass([
825
+ Injectable(),
826
+ __decorateParam(0, Optional()),
827
+ __decorateParam(1, Optional())
828
+ ], NotificationService);
829
+ var NUMERIC = "0123456789";
830
+ var ALPHA = "ABCDEFGHJKLMNPQRSTUVWXYZ";
831
+ var ALPHANUMERIC = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
832
+ var MIN_LENGTH = 1;
833
+ var MAX_LENGTH = 32;
834
+ function charsetFor(type) {
835
+ if (type === "numeric") {
836
+ return NUMERIC;
837
+ }
838
+ if (type === "alpha") {
839
+ return ALPHA;
840
+ }
841
+ return ALPHANUMERIC;
842
+ }
843
+ function generateOtpCode(length, type) {
844
+ if (!Number.isInteger(length) || length < MIN_LENGTH || length > MAX_LENGTH) {
845
+ throw new NotificationException("OTP_INVALID_LENGTH", {
846
+ provided: length,
847
+ allowed: `${MIN_LENGTH}-${MAX_LENGTH}`
848
+ });
849
+ }
850
+ const charset = charsetFor(type);
851
+ let code = "";
852
+ for (let i = 0; i < length; i++) {
853
+ code += charset.charAt(randomInt(0, charset.length));
854
+ }
855
+ return code;
856
+ }
857
+
858
+ // src/server/utils/cooldown-helpers.ts
859
+ var MS_PER_SECOND = 1e3;
860
+ var SECONDS_PER_MINUTE = 60;
861
+ var SECONDS_PER_HOUR = 3600;
862
+ function toRetryAfterHeader(remainingSeconds) {
863
+ return String(Math.max(0, Math.ceil(remainingSeconds)));
864
+ }
865
+ function cooldownExpiresAt(remainingSeconds) {
866
+ if (remainingSeconds <= 0) {
867
+ return Date.now();
868
+ }
869
+ return Date.now() + remainingSeconds * MS_PER_SECOND;
870
+ }
871
+ function formatCooldown(remainingSeconds) {
872
+ if (remainingSeconds <= 0) {
873
+ return "0s";
874
+ }
875
+ const totalSeconds = Math.ceil(remainingSeconds);
876
+ const hours = Math.floor(totalSeconds / SECONDS_PER_HOUR);
877
+ const minutes = Math.floor(totalSeconds % SECONDS_PER_HOUR / SECONDS_PER_MINUTE);
878
+ const seconds = totalSeconds % SECONDS_PER_MINUTE;
879
+ const parts = [];
880
+ if (hours > 0) {
881
+ parts.push(`${hours}h`);
882
+ }
883
+ if (minutes > 0) {
884
+ parts.push(`${minutes}m`);
885
+ }
886
+ if (seconds > 0 || parts.length === 0) {
887
+ parts.push(`${seconds}s`);
888
+ }
889
+ return parts.join(" ");
890
+ }
891
+ function safeCompare(expected, actual) {
892
+ const expectedBytes = Buffer.from(expected, "utf8");
893
+ const actualBytes = Buffer.from(actual, "utf8");
894
+ if (expectedBytes.length !== actualBytes.length) {
895
+ return false;
896
+ }
897
+ return timingSafeEqual(expectedBytes, actualBytes);
898
+ }
899
+
900
+ // src/server/services/otp.service.ts
901
+ var MS_PER_SECOND2 = 1e3;
902
+ var SECONDS_PER_MINUTE2 = 60;
903
+ var DEFAULT_OTP_TEMPLATE = "otp_code";
904
+ var OtpService = class {
905
+ /**
906
+ * @param options - The resolved, frozen module options.
907
+ * @param storage - The configured OTP storage.
908
+ * @param auditLog - The audit-log repository (no-op when none configured).
909
+ * @param emailService - The email service; present only when the email channel is configured.
910
+ */
911
+ constructor(options, storage, auditLog, emailService) {
912
+ this.options = options;
913
+ this.storage = storage;
914
+ this.auditLog = auditLog;
915
+ this.emailService = emailService;
916
+ }
917
+ /**
918
+ * Whether the OTP channel is configured and its storage is ready.
919
+ *
920
+ * @returns `true` when both hold.
921
+ */
922
+ isConfigured() {
923
+ return Boolean(this.options.otp) && this.storage.isConfigured();
924
+ }
925
+ /**
926
+ * Generates, persists, and (optionally) delivers an OTP by email.
927
+ *
928
+ * @param input - The recipient, purpose, and delivery options.
929
+ * @returns The expiry timestamp and the resend cooldown length.
930
+ * @throws NotificationException `OTP_STORAGE_NOT_CONFIGURED`, `OTP_COOLDOWN_ACTIVE`,
931
+ * `OTP_EMAIL_DELIVERY_NOT_CONFIGURED`, or rethrows a persistence/delivery error after
932
+ * releasing the cooldown lock.
933
+ */
934
+ async generate(input) {
935
+ const otp = this.requireOtpOptions();
936
+ const cfg = otp.resolveForPurpose(input.purpose);
937
+ await this.acquireCooldownOrThrow(input, cfg.resendCooldownSeconds);
938
+ const code = generateOtpCode(cfg.length, cfg.codeType);
939
+ const expiresAt = Date.now() + cfg.ttlSeconds * MS_PER_SECOND2;
940
+ await this.persistAndDeliver(input, code, expiresAt, cfg);
941
+ await this.audit(this.otpAuditEntry("generated", input, void 0));
942
+ return { expiresAt, cooldownSeconds: cfg.resendCooldownSeconds };
943
+ }
944
+ /**
945
+ * Verifies a guessed code against the stored OTP (constant-time).
946
+ *
947
+ * @param input - The recipient, purpose, and guessed code.
948
+ * @returns The discriminated verification result.
949
+ * @throws NotificationException `OTP_STORAGE_NOT_CONFIGURED` when the channel is absent.
950
+ */
951
+ async verify(input) {
952
+ const otp = this.requireOtpOptions();
953
+ const result = await this.storage.consumeAttempt(input.tenantId, input.recipient, input.purpose);
954
+ if (result.status === "not_found") {
955
+ await this.audit(this.otpAuditEntry("failed", input, { reason: "not_found" }));
956
+ return { valid: false, reason: "not_found" };
957
+ }
958
+ if (result.status === "max_attempts") {
959
+ await this.audit(
960
+ this.otpAuditEntry("max_attempts_exceeded", input, { reason: "max_attempts" })
961
+ );
962
+ return { valid: false, reason: "max_attempts" };
963
+ }
964
+ const { entry } = result;
965
+ if (!safeCompare(entry.code, input.code)) {
966
+ await this.audit(this.otpAuditEntry("failed", input, { reason: "invalid_code" }));
967
+ return {
968
+ valid: false,
969
+ reason: "invalid_code",
970
+ remainingAttempts: entry.maxAttempts - entry.attempts
971
+ };
972
+ }
973
+ await this.finalizeVerifySuccess(input, entry, otp.consumeOnVerify);
974
+ return { valid: true };
975
+ }
976
+ /**
977
+ * Deletes an OTP and clears its resend cooldown. Idempotent.
978
+ *
979
+ * @param input - The recipient and purpose.
980
+ * @throws NotificationException `OTP_STORAGE_NOT_CONFIGURED` when the channel is absent.
981
+ */
982
+ async consume(input) {
983
+ this.requireOtpOptions();
984
+ await this.storage.delete(input.tenantId, input.recipient, input.purpose);
985
+ await this.storage.clearCooldown(input.tenantId, input.recipient, input.purpose);
986
+ }
987
+ /**
988
+ * Explicit resend — a functional alias of {@link OtpService.generate}.
989
+ *
990
+ * @param input - The recipient, purpose, and delivery options.
991
+ * @returns The expiry timestamp and the resend cooldown length.
992
+ */
993
+ async resend(input) {
994
+ return this.generate(input);
995
+ }
996
+ /**
997
+ * Returns the current OTP status without ever exposing the plaintext code.
998
+ *
999
+ * @param input - The recipient and purpose.
1000
+ * @returns Existence, expiry, attempt counters, validation flag, and cooldown.
1001
+ */
1002
+ async getStatus(input) {
1003
+ const [entry, cooldownSeconds] = await Promise.all([
1004
+ this.storage.get(input.tenantId, input.recipient, input.purpose),
1005
+ this.storage.getCooldown(input.tenantId, input.recipient, input.purpose)
1006
+ ]);
1007
+ if (!entry) {
1008
+ return { exists: false, cooldownSeconds };
1009
+ }
1010
+ return {
1011
+ exists: true,
1012
+ expiresAt: entry.expiresAt,
1013
+ attempts: entry.attempts,
1014
+ maxAttempts: entry.maxAttempts,
1015
+ cooldownSeconds,
1016
+ ...entry.validated !== void 0 ? { validated: entry.validated } : {}
1017
+ };
1018
+ }
1019
+ /** Acquires the cooldown lock or throws `OTP_COOLDOWN_ACTIVE` with retry hints. */
1020
+ async acquireCooldownOrThrow(ref, cooldownSeconds) {
1021
+ const hasCooldownLock = await this.storage.tryAcquireCooldown(
1022
+ ref.tenantId,
1023
+ ref.recipient,
1024
+ ref.purpose,
1025
+ cooldownSeconds
1026
+ );
1027
+ if (hasCooldownLock) {
1028
+ return;
1029
+ }
1030
+ const remainingSeconds = await this.storage.getCooldown(
1031
+ ref.tenantId,
1032
+ ref.recipient,
1033
+ ref.purpose
1034
+ );
1035
+ await this.audit(this.otpAuditEntry("cooldown_blocked", ref, { remainingSeconds }));
1036
+ throw new NotificationException("OTP_COOLDOWN_ACTIVE", {
1037
+ remainingSeconds,
1038
+ retryAfter: toRetryAfterHeader(remainingSeconds),
1039
+ expiresAt: cooldownExpiresAt(remainingSeconds)
1040
+ });
1041
+ }
1042
+ /**
1043
+ * Persists the OTP then delivers it, releasing the cooldown lock (and deleting the
1044
+ * orphan entry) if EITHER step fails — so a storage outage or a bounced email can
1045
+ * never leave the recipient locked out behind a cooldown with no live code. The
1046
+ * plaintext code is never placed in the failure audit entry. The original typed
1047
+ * error is re-thrown after the lock is released.
1048
+ */
1049
+ async persistAndDeliver(input, code, expiresAt, cfg) {
1050
+ try {
1051
+ await this.storage.set(input.tenantId, input.recipient, input.purpose, {
1052
+ code,
1053
+ expiresAt,
1054
+ attempts: 0,
1055
+ maxAttempts: cfg.maxAttempts
1056
+ });
1057
+ await this.deliverOtp(input, code, cfg);
1058
+ } catch (error) {
1059
+ await this.releaseOtp(input);
1060
+ await this.audit(
1061
+ this.otpAuditEntry("failed", input, {
1062
+ errorMessage: error instanceof Error ? error.message : String(error)
1063
+ })
1064
+ );
1065
+ throw error;
1066
+ }
1067
+ }
1068
+ /** Delivers the code by email when requested; throws on failure (release is handled by the caller). */
1069
+ async deliverOtp(input, code, cfg) {
1070
+ const deliverVia = input.deliverVia ?? (this.emailService ? "email" : "manual");
1071
+ if (deliverVia !== "email") {
1072
+ return;
1073
+ }
1074
+ if (!this.emailService) {
1075
+ throw new NotificationException("OTP_EMAIL_DELIVERY_NOT_CONFIGURED");
1076
+ }
1077
+ await this.emailService.sendTemplate(this.buildOtpEmail(input, code, cfg));
1078
+ }
1079
+ /** Clears the cooldown and deletes the OTP — used to undo a failed delivery. */
1080
+ async releaseOtp(ref) {
1081
+ await this.storage.clearCooldown(ref.tenantId, ref.recipient, ref.purpose);
1082
+ await this.storage.delete(ref.tenantId, ref.recipient, ref.purpose);
1083
+ }
1084
+ /** Builds the OTP email payload with the auto-injected `{ code, expiresInMinutes, purpose }`. */
1085
+ buildOtpEmail(input, code, cfg) {
1086
+ const expiresInMinutes = Math.ceil(cfg.ttlSeconds / SECONDS_PER_MINUTE2);
1087
+ return {
1088
+ tenantId: input.tenantId,
1089
+ to: input.recipient,
1090
+ template: input.emailTemplate ?? DEFAULT_OTP_TEMPLATE,
1091
+ data: { ...input.emailData, code, expiresInMinutes, purpose: input.purpose },
1092
+ ...input.locale !== void 0 ? { locale: input.locale } : {},
1093
+ ...input.userId !== void 0 ? { userId: input.userId } : {}
1094
+ };
1095
+ }
1096
+ /** Finalizes a correct verification: consume-and-clear, or mark `validated`. */
1097
+ async finalizeVerifySuccess(input, entry, consumeOnVerify) {
1098
+ if (consumeOnVerify) {
1099
+ await this.storage.delete(input.tenantId, input.recipient, input.purpose);
1100
+ await this.storage.clearCooldown(input.tenantId, input.recipient, input.purpose);
1101
+ } else {
1102
+ await this.storage.update(input.tenantId, input.recipient, input.purpose, {
1103
+ ...entry,
1104
+ validated: true
1105
+ });
1106
+ }
1107
+ await this.audit(this.otpAuditEntry("verified", input, void 0));
1108
+ }
1109
+ /** Returns the resolved OTP options or throws `OTP_STORAGE_NOT_CONFIGURED`. */
1110
+ requireOtpOptions() {
1111
+ if (!this.options.otp) {
1112
+ throw new NotificationException("OTP_STORAGE_NOT_CONFIGURED");
1113
+ }
1114
+ return this.options.otp;
1115
+ }
1116
+ /** Builds an OTP audit entry with the recipient masked and never the code. */
1117
+ otpAuditEntry(verb, ref, metadata) {
1118
+ return {
1119
+ timestamp: Date.now(),
1120
+ tenantId: ref.tenantId,
1121
+ channel: "otp",
1122
+ verb,
1123
+ recipient: this.options.audit.maskRecipient(ref.recipient),
1124
+ purpose: ref.purpose,
1125
+ providerName: this.storage.name,
1126
+ ...ref.userId !== void 0 ? { userId: ref.userId } : {},
1127
+ ...metadata !== void 0 ? { metadata } : {}
1128
+ };
1129
+ }
1130
+ /** Writes an audit entry, swallowing failures unless `audit.swallowErrors` is `false`. */
1131
+ async audit(entry) {
1132
+ try {
1133
+ await this.auditLog.create(entry);
1134
+ } catch (error) {
1135
+ if (!this.options.audit.swallowErrors) {
1136
+ throw new NotificationException("AUDIT_LOG_FAILED", {
1137
+ cause: error instanceof Error ? error.message : String(error)
1138
+ });
1139
+ }
1140
+ }
1141
+ }
1142
+ };
1143
+ OtpService = __decorateClass([
1144
+ Injectable(),
1145
+ __decorateParam(0, Inject(BYMAX_NOTIFICATION_OPTIONS)),
1146
+ __decorateParam(1, Inject(BYMAX_NOTIFICATION_OTP_STORAGE)),
1147
+ __decorateParam(2, Inject(BYMAX_NOTIFICATION_LOG_REPOSITORY)),
1148
+ __decorateParam(3, Optional()),
1149
+ __decorateParam(3, Inject(EmailService))
1150
+ ], OtpService);
1151
+
1152
+ // src/server/bymax-notification.module.ts
1153
+ var RAW_NOTIFICATION_OPTIONS = /* @__PURE__ */ Symbol("RAW_NOTIFICATION_OPTIONS");
1154
+ var BymaxNotificationModule = class {
1155
+ /**
1156
+ * Registers the module synchronously from static options.
1157
+ *
1158
+ * @param options - The channel configuration; at least one channel is required.
1159
+ * @returns A global `DynamicModule` exposing only the configured channels' tokens.
1160
+ * @throws Error When validation fails (no channel, malformed channel, or an unsupported channel).
1161
+ */
1162
+ static forRoot(options) {
1163
+ validateOptions(options);
1164
+ const resolved = resolveOptions(options);
1165
+ const tokenProviders = this.buildProviders(options, resolved);
1166
+ const serviceProviders = this.buildServiceProviders(resolved);
1167
+ this.logger.log(
1168
+ `[BYMAX_NOTIFICATION_MODULE_BOOTSTRAP_OK] Initialized with channels: ${activeChannels(resolved).join(", ")}`
1169
+ );
1170
+ return {
1171
+ module: BymaxNotificationModule,
1172
+ global: true,
1173
+ providers: [...tokenProviders, ...serviceProviders],
1174
+ exports: [...tokenProviders.map((provider) => provider.provide), ...serviceProviders]
1175
+ };
1176
+ }
1177
+ /**
1178
+ * Registers the module with options resolved at runtime through DI.
1179
+ *
1180
+ * Only the `useFactory` + `inject` form is supported — `useClass`/`useExisting`
1181
+ * are rejected with an explicit error. The factory runs once (under an internal
1182
+ * token); every channel token and all three services derive from its result, so
1183
+ * a `ConfigService`-driven async bootstrap wires the same graph as `forRoot`.
1184
+ *
1185
+ * @param asyncOptions - The async options factory and its dependencies.
1186
+ * @returns A global `DynamicModule` exposing the resolved options token, every
1187
+ * channel token, and the three services.
1188
+ * @throws Error When `useClass`/`useExisting` is supplied, or `useFactory` is missing.
1189
+ */
1190
+ static forRootAsync(asyncOptions) {
1191
+ assertUseFactory(asyncOptions);
1192
+ const rawOptionsProvider = {
1193
+ provide: RAW_NOTIFICATION_OPTIONS,
1194
+ useFactory: async (...args) => {
1195
+ const options = await asyncOptions.useFactory(...args);
1196
+ validateOptions(options);
1197
+ return options;
1198
+ },
1199
+ inject: asyncOptions.inject ?? []
1200
+ };
1201
+ const tokenProviders = this.buildAsyncTokenProviders();
1202
+ const serviceProviders = this.buildAsyncServiceProviders();
1203
+ return {
1204
+ module: BymaxNotificationModule,
1205
+ global: true,
1206
+ imports: asyncOptions.imports ?? [],
1207
+ providers: [rawOptionsProvider, ...tokenProviders, ...serviceProviders],
1208
+ exports: [
1209
+ BYMAX_NOTIFICATION_OPTIONS,
1210
+ BYMAX_NOTIFICATION_LOG_REPOSITORY,
1211
+ BYMAX_NOTIFICATION_EMAIL_PROVIDER,
1212
+ BYMAX_NOTIFICATION_TEMPLATE_RENDERER,
1213
+ BYMAX_NOTIFICATION_OTP_STORAGE,
1214
+ EmailService,
1215
+ OtpService,
1216
+ NotificationService
1217
+ ]
1218
+ };
1219
+ }
1220
+ /**
1221
+ * Builds the async channel-service providers, mirroring the conditional wiring of
1222
+ * the sync path. `EmailService`/`OtpService` are factory providers that resolve to
1223
+ * `undefined` when their required channel dependency (the email provider / OTP
1224
+ * storage token) is absent, so the `@Optional()`-injected `NotificationService`
1225
+ * keeps throwing `CHANNEL_DISABLED` for that channel and `getEnabledChannels()`
1226
+ * omits it. `NotificationService` is always registered.
1227
+ */
1228
+ static buildAsyncServiceProviders() {
1229
+ return [
1230
+ {
1231
+ provide: EmailService,
1232
+ useFactory: (options, provider, renderer, auditLog) => provider ? new EmailService(options, provider, renderer, auditLog) : void 0,
1233
+ inject: [
1234
+ BYMAX_NOTIFICATION_OPTIONS,
1235
+ BYMAX_NOTIFICATION_EMAIL_PROVIDER,
1236
+ BYMAX_NOTIFICATION_TEMPLATE_RENDERER,
1237
+ BYMAX_NOTIFICATION_LOG_REPOSITORY
1238
+ ]
1239
+ },
1240
+ {
1241
+ provide: OtpService,
1242
+ useFactory: (options, storage, auditLog, emailService) => storage ? new OtpService(options, storage, auditLog, emailService) : void 0,
1243
+ inject: [
1244
+ BYMAX_NOTIFICATION_OPTIONS,
1245
+ BYMAX_NOTIFICATION_OTP_STORAGE,
1246
+ BYMAX_NOTIFICATION_LOG_REPOSITORY,
1247
+ // Stryker disable next-line BooleanLiteral: the EmailService token is ALWAYS registered in async mode (as a factory that resolves to `undefined` when email is absent), so Nest resolves it whether optional is true or false — `optional: false` would still inject `undefined`, never throw, making the flag observationally inert here.
1248
+ { token: EmailService, optional: true }
1249
+ ]
1250
+ },
1251
+ NotificationService
1252
+ ];
1253
+ }
1254
+ /**
1255
+ * Builds the async channel-token factories. Each derives from the validated raw
1256
+ * options under {@link RAW_NOTIFICATION_OPTIONS}: an unconfigured email/OTP token
1257
+ * resolves to `null` (the owning service guards against it), the audit token
1258
+ * defaults to {@link NoOpNotificationLogRepository}, and the renderer defaults to
1259
+ * {@link DefaultTemplateRenderer}.
1260
+ */
1261
+ static buildAsyncTokenProviders() {
1262
+ return [
1263
+ {
1264
+ provide: BYMAX_NOTIFICATION_OPTIONS,
1265
+ useFactory: (raw) => resolveOptions(raw),
1266
+ inject: [RAW_NOTIFICATION_OPTIONS]
1267
+ },
1268
+ {
1269
+ provide: BYMAX_NOTIFICATION_LOG_REPOSITORY,
1270
+ useFactory: (raw) => raw.audit ? instantiate(raw.audit.repository) : new NoOpNotificationLogRepository(),
1271
+ inject: [RAW_NOTIFICATION_OPTIONS]
1272
+ },
1273
+ {
1274
+ provide: BYMAX_NOTIFICATION_EMAIL_PROVIDER,
1275
+ useFactory: (raw) => raw.email ? instantiate(raw.email.provider) : null,
1276
+ inject: [RAW_NOTIFICATION_OPTIONS]
1277
+ },
1278
+ {
1279
+ provide: BYMAX_NOTIFICATION_TEMPLATE_RENDERER,
1280
+ useFactory: (raw) => raw.email?.templateRenderer ? instantiate(raw.email.templateRenderer) : new DefaultTemplateRenderer({}),
1281
+ inject: [RAW_NOTIFICATION_OPTIONS]
1282
+ },
1283
+ {
1284
+ provide: BYMAX_NOTIFICATION_OTP_STORAGE,
1285
+ useFactory: (raw) => raw.otp ? instantiate(raw.otp.storage) : null,
1286
+ inject: [RAW_NOTIFICATION_OPTIONS]
1287
+ }
1288
+ ];
1289
+ }
1290
+ /** Assembles the provider list for the configured channels. */
1291
+ static buildProviders(options, resolved) {
1292
+ const providers = [
1293
+ { provide: BYMAX_NOTIFICATION_OPTIONS, useValue: resolved },
1294
+ options.audit?.repository ? resolveAsProvider(BYMAX_NOTIFICATION_LOG_REPOSITORY, options.audit.repository) : { provide: BYMAX_NOTIFICATION_LOG_REPOSITORY, useClass: NoOpNotificationLogRepository }
1295
+ ];
1296
+ if (resolved.email && options.email) {
1297
+ providers.push(resolveAsProvider(BYMAX_NOTIFICATION_EMAIL_PROVIDER, options.email.provider));
1298
+ providers.push(resolveRenderer(options.email.templateRenderer));
1299
+ }
1300
+ if (resolved.otp && options.otp) {
1301
+ providers.push(resolveAsProvider(BYMAX_NOTIFICATION_OTP_STORAGE, options.otp.storage));
1302
+ }
1303
+ return providers;
1304
+ }
1305
+ /**
1306
+ * Builds the channel service providers. `EmailService`/`OtpService` are
1307
+ * registered only when their channel is configured; `NotificationService` is
1308
+ * always registered (it injects the channel services with `@Optional()`).
1309
+ */
1310
+ static buildServiceProviders(resolved) {
1311
+ const services = [];
1312
+ if (resolved.email) {
1313
+ services.push(EmailService);
1314
+ }
1315
+ if (resolved.otp) {
1316
+ services.push(OtpService);
1317
+ }
1318
+ services.push(NotificationService);
1319
+ return services;
1320
+ }
1321
+ };
1322
+ BymaxNotificationModule.logger = new Logger(BymaxNotificationModule.name);
1323
+ BymaxNotificationModule = __decorateClass([
1324
+ Module({})
1325
+ ], BymaxNotificationModule);
1326
+ function activeChannels(resolved) {
1327
+ const channels = [];
1328
+ if (resolved.email) {
1329
+ channels.push("email");
1330
+ }
1331
+ if (resolved.otp) {
1332
+ channels.push("otp");
1333
+ }
1334
+ return channels;
1335
+ }
1336
+ function resolveRenderer(renderer) {
1337
+ if (renderer === void 0) {
1338
+ return {
1339
+ provide: BYMAX_NOTIFICATION_TEMPLATE_RENDERER,
1340
+ useFactory: () => new DefaultTemplateRenderer({})
1341
+ };
1342
+ }
1343
+ return resolveAsProvider(BYMAX_NOTIFICATION_TEMPLATE_RENDERER, renderer);
1344
+ }
1345
+ function resolveAsProvider(token, valueOrClass) {
1346
+ if (isType(valueOrClass)) {
1347
+ return { provide: token, useClass: valueOrClass };
1348
+ }
1349
+ return { provide: token, useValue: valueOrClass };
1350
+ }
1351
+ function isType(value) {
1352
+ return typeof value === "function";
1353
+ }
1354
+ function assertUseFactory(asyncOptions) {
1355
+ const candidate = asyncOptions;
1356
+ if (candidate.useClass !== void 0 || candidate.useExisting !== void 0) {
1357
+ throw new Error(
1358
+ "[BymaxNotificationModule] forRootAsync supports only `useFactory`; `useClass` / `useExisting` are not yet implemented."
1359
+ );
1360
+ }
1361
+ if (typeof asyncOptions.useFactory !== "function") {
1362
+ throw new Error("[BymaxNotificationModule] forRootAsync requires a `useFactory` function.");
1363
+ }
1364
+ }
1365
+ function instantiate(valueOrClass) {
1366
+ if (typeof valueOrClass !== "function") {
1367
+ return valueOrClass;
1368
+ }
1369
+ const ctor = valueOrClass;
1370
+ if (ctor.length > 0) {
1371
+ throw new Error(
1372
+ `[BymaxNotificationModule] forRootAsync cannot construct '${ctor.name}': its constructor declares required parameters and would need NestJS DI. Pass a ready instance instead of a DI-dependent class in async mode.`
1373
+ );
1374
+ }
1375
+ return new ctor();
1376
+ }
1377
+ var INTERCEPTOR_PROVIDER_NAME = "__interceptor__";
1378
+ function toErrorMessage(error) {
1379
+ return error instanceof Error ? error.message : String(error);
1380
+ }
1381
+ var NotificationAuditInterceptor = class {
1382
+ /**
1383
+ * @param options - The resolved, frozen module options (carries the tenant resolver + mask).
1384
+ * @param auditLog - The audit-log repository (no-op when none configured).
1385
+ */
1386
+ constructor(options, auditLog) {
1387
+ this.options = options;
1388
+ this.auditLog = auditLog;
1389
+ }
1390
+ /**
1391
+ * Taps the handler stream: records `'sent'` after a successful dispatch and
1392
+ * `'failed'` before re-throwing a rejected one. The success recording runs
1393
+ * downstream of the error handler so a failure is audited exactly once.
1394
+ *
1395
+ * @param context - The execution context exposing the handler arguments + request.
1396
+ * @param next - The downstream call handler.
1397
+ * @returns The original stream, unchanged except for the audit side effect.
1398
+ */
1399
+ intercept(context, next) {
1400
+ return next.handle().pipe(
1401
+ catchError(
1402
+ (error) => from(this.recordMeta(context, "failed", toErrorMessage(error))).pipe(
1403
+ concatMap(() => throwError(() => error))
1404
+ )
1405
+ ),
1406
+ concatMap((value) => from(this.recordMeta(context, "sent")).pipe(map(() => value)))
1407
+ );
1408
+ }
1409
+ /**
1410
+ * Builds and writes the audit entry for one intercepted dispatch. Does nothing
1411
+ * when no argument matches the dispatch shape. Swallows write failures unless
1412
+ * `audit.swallowErrors` is `false`.
1413
+ */
1414
+ async recordMeta(context, verb, errorMessage) {
1415
+ try {
1416
+ const input = this.extractDispatchInput(context);
1417
+ if (input === null) {
1418
+ return;
1419
+ }
1420
+ const tenantId = await this.resolveTenantId(context, input.tenantId);
1421
+ await this.auditLog.create(this.buildEntry(input, tenantId, verb, errorMessage));
1422
+ } catch (error) {
1423
+ if (!this.options.audit.swallowErrors) {
1424
+ throw new NotificationException("AUDIT_LOG_FAILED", { cause: toErrorMessage(error) });
1425
+ }
1426
+ }
1427
+ }
1428
+ /** Returns the first handler argument shaped like a {@link DispatchInput}, else `null`. */
1429
+ extractDispatchInput(context) {
1430
+ for (const arg of context.getArgs()) {
1431
+ if (this.isDispatchInput(arg)) {
1432
+ return arg;
1433
+ }
1434
+ }
1435
+ return null;
1436
+ }
1437
+ /** Narrows an unknown argument to a {@link DispatchInput} by structural shape. */
1438
+ isDispatchInput(value) {
1439
+ if (typeof value !== "object" || value === null) {
1440
+ return false;
1441
+ }
1442
+ const candidate = value;
1443
+ if (candidate.channel !== "email" && candidate.channel !== "otp") {
1444
+ return false;
1445
+ }
1446
+ if (typeof candidate.tenantId !== "string") {
1447
+ return false;
1448
+ }
1449
+ return typeof candidate.payload === "object" && candidate.payload !== null;
1450
+ }
1451
+ /**
1452
+ * Resolves the trusted tenant id: `tenantIdResolver(request)` when configured and
1453
+ * a request is available, otherwise the payload-supplied `fallback`.
1454
+ */
1455
+ async resolveTenantId(context, fallback) {
1456
+ const resolver = this.options.global.tenantIdResolver;
1457
+ if (resolver === void 0) {
1458
+ return fallback;
1459
+ }
1460
+ const request = this.extractRequest(context);
1461
+ if (request === null) {
1462
+ return fallback;
1463
+ }
1464
+ return resolver(request);
1465
+ }
1466
+ /** Reads the HTTP request from the context, returning `null` outside an HTTP context. */
1467
+ extractRequest(context) {
1468
+ try {
1469
+ return context.switchToHttp().getRequest() ?? null;
1470
+ } catch {
1471
+ return null;
1472
+ }
1473
+ }
1474
+ /** Assembles the audit entry — masked recipient, never the dispatched payload. */
1475
+ buildEntry(input, tenantId, verb, errorMessage) {
1476
+ const purpose = this.extractPurpose(input);
1477
+ return {
1478
+ timestamp: Date.now(),
1479
+ tenantId,
1480
+ channel: input.channel,
1481
+ verb,
1482
+ recipient: this.options.audit.maskRecipient(this.extractRecipient(input)),
1483
+ providerName: INTERCEPTOR_PROVIDER_NAME,
1484
+ metadata: { interceptedBy: "NotificationAuditInterceptor" },
1485
+ ...purpose !== void 0 ? { purpose } : {},
1486
+ ...errorMessage !== void 0 ? { errorMessage } : {}
1487
+ };
1488
+ }
1489
+ /** Extracts the (unmasked) recipient from the dispatch payload. */
1490
+ extractRecipient(input) {
1491
+ if (input.channel === "email") {
1492
+ return Array.isArray(input.payload.to) ? input.payload.to[0] ?? "" : input.payload.to;
1493
+ }
1494
+ return input.payload.recipient;
1495
+ }
1496
+ /** Extracts the audit `purpose`: the OTP purpose, or the email template name. */
1497
+ extractPurpose(input) {
1498
+ return input.channel === "otp" ? input.payload.purpose : input.payload.template;
1499
+ }
1500
+ };
1501
+ NotificationAuditInterceptor = __decorateClass([
1502
+ Injectable(),
1503
+ __decorateParam(0, Inject(BYMAX_NOTIFICATION_OPTIONS)),
1504
+ __decorateParam(1, Inject(BYMAX_NOTIFICATION_LOG_REPOSITORY))
1505
+ ], NotificationAuditInterceptor);
1506
+
1507
+ // src/server/constants/notification-purposes.ts
1508
+ var NOTIFICATION_PURPOSES = {
1509
+ EMAIL_VERIFICATION: "email_verification",
1510
+ PASSWORD_RESET: "password_reset",
1511
+ MFA_OOB: "mfa_oob",
1512
+ PHONE_VERIFICATION: "phone_verification",
1513
+ MAGIC_LINK: "magic_link"
1514
+ };
1515
+
1516
+ // src/server/constants/canonical-templates.ts
1517
+ var CANONICAL_EMAIL_TEMPLATES = {
1518
+ /** OTP for email verification — variables: `code`, `expiresInMinutes`, `purpose`, `name`, `appName`. */
1519
+ OTP_CODE: "otp_code",
1520
+ /** OTP for password reset (distinct copy; may carry a deep link) — variables: `code`, `expiresInMinutes`, `name`, `appName`, `verificationLink`. */
1521
+ OTP_PASSWORD_RESET: "otp_password_reset",
1522
+ /** OTP resend — same variables as the originating OTP template. */
1523
+ OTP_RESENT: "otp_resent",
1524
+ /** Welcome after email verification — variables: `name`, `appName`, `appUrl`. */
1525
+ WELCOME: "welcome",
1526
+ /** Password reset success — variables: `name`, `appName`, `supportEmail`. */
1527
+ PASSWORD_RESET_SUCCESS: "password_reset_success",
1528
+ /** Trial ending soon — variables: `name`, `appName`, `trialPlanName`, `daysLeft`, `appUrl`. */
1529
+ TRIAL_EXPIRING: "trial_expiring",
1530
+ /** Trial ended — variables: `name`, `appName`, `trialPlanName`, `durationDays`, `appUrl`. */
1531
+ TRIAL_EXPIRED: "trial_expired",
1532
+ /** New device login — variables: `device`, `ip`, `timestamp`, `name`, `appName`. */
1533
+ NEW_LOGIN_ALERT: "new_login_alert",
1534
+ /** MFA enabled — variables: `name`, `appName`. */
1535
+ MFA_ENABLED: "mfa_enabled",
1536
+ /** MFA disabled — variables: `name`, `appName`. */
1537
+ MFA_DISABLED: "mfa_disabled"
1538
+ };
1539
+ var NoOpEmailProvider = class {
1540
+ constructor() {
1541
+ this.name = "noop";
1542
+ this.logger = new Logger(NoOpEmailProvider.name);
1543
+ }
1544
+ /** Always ready — the no-op provider has nothing to configure. */
1545
+ isConfigured() {
1546
+ return true;
1547
+ }
1548
+ /**
1549
+ * Pretends to send: logs the recipient and subject and returns a synthetic id.
1550
+ *
1551
+ * @param options - The message to "send". Only `to` and `subject` are logged.
1552
+ * @returns A synthetic `messageId` prefixed with `noop-`.
1553
+ */
1554
+ async send(options) {
1555
+ const to = Array.isArray(options.to) ? options.to.join(",") : options.to;
1556
+ this.logger.debug(`[NoOpEmail] to=${to} subject="${options.subject}"`);
1557
+ return { messageId: `noop-${randomUUID()}` };
1558
+ }
1559
+ };
1560
+ NoOpEmailProvider = __decorateClass([
1561
+ Injectable()
1562
+ ], NoOpEmailProvider);
1563
+ var RESEND_MODULE = "resend";
1564
+ var ResendEmailProvider = class {
1565
+ /**
1566
+ * @param options - Adapter options; `apiKey` is required to actually send.
1567
+ */
1568
+ constructor(options = {}) {
1569
+ this.options = options;
1570
+ this.name = "resend";
1571
+ this.logger = new Logger(ResendEmailProvider.name);
1572
+ /**
1573
+ * Cached in-flight (or resolved) SDK client initialization. `null` until the first
1574
+ * `send()` and after a failed init. Caching the PROMISE (not just the client)
1575
+ * collapses concurrent first sends onto a single dynamic `import()` + instantiation;
1576
+ * a failed init resets this back to `null` so a transient error can be retried.
1577
+ */
1578
+ this.clientPromise = null;
1579
+ }
1580
+ /**
1581
+ * Whether an API key was supplied. Does not load the SDK.
1582
+ *
1583
+ * @returns `true` when an `apiKey` is present.
1584
+ */
1585
+ isConfigured() {
1586
+ return Boolean(this.options.apiKey);
1587
+ }
1588
+ /**
1589
+ * Sends one transactional email through Resend.
1590
+ *
1591
+ * @param options - The message envelope and body.
1592
+ * @returns The Resend message id.
1593
+ * @throws Error When the API key is missing, the `resend` package is not
1594
+ * installed, the SDK returns an error, or no message id comes back. `EmailService`
1595
+ * maps any thrown `Error` to `EMAIL_SEND_FAILED`.
1596
+ */
1597
+ async send(options) {
1598
+ const client = await this.getClient();
1599
+ const from2 = this.formatFrom(options.from, options.fromName);
1600
+ const result = await client.emails.send({
1601
+ from: from2,
1602
+ to: options.to,
1603
+ subject: options.subject,
1604
+ html: options.html,
1605
+ text: options.text,
1606
+ replyTo: options.replyTo,
1607
+ cc: options.cc,
1608
+ bcc: options.bcc,
1609
+ tags: options.tags,
1610
+ headers: options.headers,
1611
+ attachments: options.attachments
1612
+ });
1613
+ if (result.error) {
1614
+ this.logger.warn(`[RESEND_SEND_FAILED] ${result.error.message}`);
1615
+ throw new Error(`Resend send failed: ${result.error.message}`);
1616
+ }
1617
+ if (!result.data?.id) {
1618
+ throw new Error("Resend returned no message ID");
1619
+ }
1620
+ return { messageId: result.data.id };
1621
+ }
1622
+ /**
1623
+ * Formats the RFC-5322 `from` header. The `Name <address>` display-name form is
1624
+ * only used when a non-empty address exists — otherwise it would emit the literal
1625
+ * `Name <undefined>` / `Name <>`. Falls back to the bare address (or `''`).
1626
+ *
1627
+ * @param from - The sender address, if any.
1628
+ * @param fromName - The sender display name, if any.
1629
+ * @returns `"Name <address>"`, the bare address, or `''`.
1630
+ */
1631
+ formatFrom(from2, fromName) {
1632
+ const address = from2 ?? "";
1633
+ if (fromName && address) {
1634
+ return `${fromName} <${address}>`;
1635
+ }
1636
+ return address;
1637
+ }
1638
+ /**
1639
+ * Returns the cached SDK client, lazily importing `resend` on first use. Concurrent
1640
+ * first calls share one in-flight initialization promise so the dynamic import and
1641
+ * constructor run exactly once; a failed init is dropped from the cache so a later
1642
+ * call can retry instead of being permanently bricked.
1643
+ *
1644
+ * @returns The instantiated client.
1645
+ * @throws Error When `apiKey` is missing or the `resend` package is not installed.
1646
+ */
1647
+ getClient() {
1648
+ this.clientPromise ??= this.createClient();
1649
+ return this.clientPromise;
1650
+ }
1651
+ /**
1652
+ * Builds a fresh SDK client, resetting the cached promise on any failure so the
1653
+ * provider is not permanently bricked by a transient init error.
1654
+ *
1655
+ * @returns The instantiated client.
1656
+ * @throws Error When `apiKey` is missing or the `resend` package is not installed.
1657
+ */
1658
+ async createClient() {
1659
+ try {
1660
+ const apiKey = this.options.apiKey;
1661
+ if (!apiKey) {
1662
+ throw new Error("ResendEmailProvider: missing API key \u2014 pass { apiKey } to the constructor");
1663
+ }
1664
+ const ResendCtor = await this.loadResendConstructor();
1665
+ return new ResendCtor(apiKey);
1666
+ } catch (error) {
1667
+ this.clientPromise = null;
1668
+ throw error;
1669
+ }
1670
+ }
1671
+ /**
1672
+ * Dynamically imports the optional `resend` peer dependency.
1673
+ *
1674
+ * @returns The SDK's `Resend` constructor.
1675
+ * @throws Error When the package is not installed in the consumer app.
1676
+ */
1677
+ async loadResendConstructor() {
1678
+ try {
1679
+ const mod = await import(RESEND_MODULE);
1680
+ return mod.Resend;
1681
+ } catch {
1682
+ throw new Error(
1683
+ "`resend` package is not installed. Run `pnpm add resend` in the consumer app."
1684
+ );
1685
+ }
1686
+ }
1687
+ };
1688
+ ResendEmailProvider = __decorateClass([
1689
+ Injectable()
1690
+ ], ResendEmailProvider);
1691
+ var MS_PER_SECOND3 = 1e3;
1692
+ var InMemoryOtpStorage = class {
1693
+ constructor() {
1694
+ this.name = "memory";
1695
+ /** OTP entries keyed by `${tenantId}::${recipient}::${purpose}`. */
1696
+ this.store = /* @__PURE__ */ new Map();
1697
+ /** Cooldown expiries (epoch ms) keyed by the same composite key. */
1698
+ this.cooldowns = /* @__PURE__ */ new Map();
1699
+ }
1700
+ /** Always ready — there is nothing to configure.
1701
+ *
1702
+ * @returns `true`.
1703
+ */
1704
+ isConfigured() {
1705
+ return true;
1706
+ }
1707
+ /**
1708
+ * Creates or replaces an OTP entry.
1709
+ *
1710
+ * @param tenantId - Tenant isolation scope.
1711
+ * @param recipient - Pre-normalized recipient identifier.
1712
+ * @param purpose - OTP purpose.
1713
+ * @param entry - The entry to persist.
1714
+ */
1715
+ async set(tenantId, recipient, purpose, entry) {
1716
+ this.store.set(this.key(tenantId, recipient, purpose), entry);
1717
+ }
1718
+ /**
1719
+ * Reads an entry, self-evicting it when its TTL has lapsed.
1720
+ *
1721
+ * @param tenantId - Tenant isolation scope.
1722
+ * @param recipient - Pre-normalized recipient identifier.
1723
+ * @param purpose - OTP purpose.
1724
+ * @returns The entry, or `null` when absent or expired.
1725
+ */
1726
+ async get(tenantId, recipient, purpose) {
1727
+ const key = this.key(tenantId, recipient, purpose);
1728
+ const entry = this.store.get(key);
1729
+ if (!entry) {
1730
+ return null;
1731
+ }
1732
+ if (entry.expiresAt < Date.now()) {
1733
+ this.store.delete(key);
1734
+ return null;
1735
+ }
1736
+ return entry;
1737
+ }
1738
+ /**
1739
+ * Atomic verification primitive — read → expiry/max checks → increment → write,
1740
+ * with no `await` between read and write.
1741
+ *
1742
+ * @param tenantId - Tenant isolation scope.
1743
+ * @param recipient - Pre-normalized recipient identifier.
1744
+ * @param purpose - OTP purpose.
1745
+ * @returns `not_found` (missing/expired), `max_attempts` (ceiling reached, entry
1746
+ * deleted), or `ok` with the entry whose `attempts` was incremented by one.
1747
+ */
1748
+ async consumeAttempt(tenantId, recipient, purpose) {
1749
+ const key = this.key(tenantId, recipient, purpose);
1750
+ const entry = this.store.get(key);
1751
+ if (!entry) {
1752
+ return { status: "not_found" };
1753
+ }
1754
+ if (entry.expiresAt < Date.now()) {
1755
+ this.store.delete(key);
1756
+ return { status: "not_found" };
1757
+ }
1758
+ if (entry.attempts >= entry.maxAttempts) {
1759
+ this.store.delete(key);
1760
+ return { status: "max_attempts" };
1761
+ }
1762
+ entry.attempts += 1;
1763
+ this.store.set(key, entry);
1764
+ return { status: "ok", entry };
1765
+ }
1766
+ /**
1767
+ * Updates an existing entry; a no-op when the key is absent (no resurrection).
1768
+ *
1769
+ * @param tenantId - Tenant isolation scope.
1770
+ * @param recipient - Pre-normalized recipient identifier.
1771
+ * @param purpose - OTP purpose.
1772
+ * @param entry - The replacement entry.
1773
+ */
1774
+ async update(tenantId, recipient, purpose, entry) {
1775
+ const key = this.key(tenantId, recipient, purpose);
1776
+ if (this.store.has(key)) {
1777
+ this.store.set(key, entry);
1778
+ }
1779
+ }
1780
+ /**
1781
+ * Removes the OTP entry. Idempotent.
1782
+ *
1783
+ * @param tenantId - Tenant isolation scope.
1784
+ * @param recipient - Pre-normalized recipient identifier.
1785
+ * @param purpose - OTP purpose.
1786
+ */
1787
+ async delete(tenantId, recipient, purpose) {
1788
+ this.store.delete(this.key(tenantId, recipient, purpose));
1789
+ }
1790
+ /**
1791
+ * Acquires the cooldown lock only when one is not already active.
1792
+ *
1793
+ * @param tenantId - Tenant isolation scope.
1794
+ * @param recipient - Pre-normalized recipient identifier.
1795
+ * @param purpose - OTP purpose.
1796
+ * @param ttlSeconds - Cooldown duration in seconds.
1797
+ * @returns `true` when acquired, `false` when a cooldown is already active.
1798
+ */
1799
+ async tryAcquireCooldown(tenantId, recipient, purpose, ttlSeconds) {
1800
+ const key = this.key(tenantId, recipient, purpose);
1801
+ const existing = this.cooldowns.get(key);
1802
+ if (existing && existing > Date.now()) {
1803
+ return false;
1804
+ }
1805
+ this.cooldowns.set(key, Date.now() + ttlSeconds * MS_PER_SECOND3);
1806
+ return true;
1807
+ }
1808
+ /**
1809
+ * Remaining cooldown in seconds, self-evicting a lapsed cooldown.
1810
+ *
1811
+ * @param tenantId - Tenant isolation scope.
1812
+ * @param recipient - Pre-normalized recipient identifier.
1813
+ * @param purpose - OTP purpose.
1814
+ * @returns Remaining seconds, or `0` when there is no active cooldown.
1815
+ */
1816
+ async getCooldown(tenantId, recipient, purpose) {
1817
+ const key = this.key(tenantId, recipient, purpose);
1818
+ const expiry = this.cooldowns.get(key);
1819
+ if (!expiry) {
1820
+ return 0;
1821
+ }
1822
+ const remaining = Math.ceil((expiry - Date.now()) / MS_PER_SECOND3);
1823
+ if (remaining <= 0) {
1824
+ this.cooldowns.delete(key);
1825
+ return 0;
1826
+ }
1827
+ return remaining;
1828
+ }
1829
+ /**
1830
+ * Clears the cooldown. Idempotent.
1831
+ *
1832
+ * @param tenantId - Tenant isolation scope.
1833
+ * @param recipient - Pre-normalized recipient identifier.
1834
+ * @param purpose - OTP purpose.
1835
+ */
1836
+ async clearCooldown(tenantId, recipient, purpose) {
1837
+ this.cooldowns.delete(this.key(tenantId, recipient, purpose));
1838
+ }
1839
+ /**
1840
+ * Test helper — wipes all entries and cooldowns. Not part of `IOtpStorage`.
1841
+ */
1842
+ clear() {
1843
+ this.store.clear();
1844
+ this.cooldowns.clear();
1845
+ }
1846
+ /**
1847
+ * Test helper — current map sizes. Not part of `IOtpStorage`.
1848
+ *
1849
+ * @returns The number of stored OTP entries and active cooldowns.
1850
+ */
1851
+ size() {
1852
+ return { otps: this.store.size, cooldowns: this.cooldowns.size };
1853
+ }
1854
+ /** Collapses the `(tenantId, recipient, purpose)` tuple into one map key. */
1855
+ key(tenantId, recipient, purpose) {
1856
+ return `${tenantId}::${recipient}::${purpose}`;
1857
+ }
1858
+ };
1859
+ InMemoryOtpStorage = __decorateClass([
1860
+ Injectable()
1861
+ ], InMemoryOtpStorage);
1862
+ function hashTenantRecipient(tenantId, recipient) {
1863
+ return createHash("sha256").update(`${tenantId}:${recipient}`).digest("hex");
1864
+ }
1865
+
1866
+ // src/server/providers/redis-otp.storage.ts
1867
+ var MS_PER_SECOND4 = 1e3;
1868
+ var RedisOtpStorage = class {
1869
+ /**
1870
+ * @param options - The Redis client and optional namespace.
1871
+ */
1872
+ constructor(options) {
1873
+ this.name = "redis";
1874
+ this.redis = options.redisClient;
1875
+ this.namespace = options.namespace ?? "notification";
1876
+ }
1877
+ /** Whether a Redis client was supplied.
1878
+ *
1879
+ * @returns `true` when a client is present.
1880
+ */
1881
+ isConfigured() {
1882
+ return Boolean(this.redis);
1883
+ }
1884
+ /**
1885
+ * Creates or replaces an OTP entry with a TTL derived from `expiresAt`.
1886
+ *
1887
+ * @param tenantId - Tenant isolation scope.
1888
+ * @param recipient - Pre-normalized recipient identifier.
1889
+ * @param purpose - OTP purpose.
1890
+ * @param entry - The entry to persist.
1891
+ */
1892
+ async set(tenantId, recipient, purpose, entry) {
1893
+ const ttlSeconds = Math.max(1, Math.ceil((entry.expiresAt - Date.now()) / MS_PER_SECOND4));
1894
+ await this.redis.setex(
1895
+ this.otpKey(tenantId, recipient, purpose),
1896
+ ttlSeconds,
1897
+ JSON.stringify(entry)
1898
+ );
1899
+ }
1900
+ /**
1901
+ * Reads an entry, deleting and returning `null` for corrupted JSON.
1902
+ *
1903
+ * @param tenantId - Tenant isolation scope.
1904
+ * @param recipient - Pre-normalized recipient identifier.
1905
+ * @param purpose - OTP purpose.
1906
+ * @returns The parsed entry, or `null` when absent/corrupted.
1907
+ */
1908
+ async get(tenantId, recipient, purpose) {
1909
+ const raw = await this.redis.get(this.otpKey(tenantId, recipient, purpose));
1910
+ if (!raw) {
1911
+ return null;
1912
+ }
1913
+ try {
1914
+ return JSON.parse(raw);
1915
+ } catch {
1916
+ await this.delete(tenantId, recipient, purpose);
1917
+ return null;
1918
+ }
1919
+ }
1920
+ /**
1921
+ * Atomic verification primitive (single `EVAL`).
1922
+ *
1923
+ * @param tenantId - Tenant isolation scope.
1924
+ * @param recipient - Pre-normalized recipient identifier.
1925
+ * @param purpose - OTP purpose.
1926
+ * @returns `not_found`, `max_attempts`, or `ok` with the incremented entry.
1927
+ */
1928
+ async consumeAttempt(tenantId, recipient, purpose) {
1929
+ const raw = await this.redis.eval(
1930
+ RedisOtpStorage.CONSUME_ATTEMPT_LUA,
1931
+ 1,
1932
+ this.otpKey(tenantId, recipient, purpose),
1933
+ Date.now().toString()
1934
+ );
1935
+ return JSON.parse(raw);
1936
+ }
1937
+ /**
1938
+ * Updates an entry with `SET … KEEPTTL XX` — preserves the TTL and never
1939
+ * resurrects an already-expired key.
1940
+ *
1941
+ * @param tenantId - Tenant isolation scope.
1942
+ * @param recipient - Pre-normalized recipient identifier.
1943
+ * @param purpose - OTP purpose.
1944
+ * @param entry - The replacement entry.
1945
+ */
1946
+ async update(tenantId, recipient, purpose, entry) {
1947
+ await this.redis.set(
1948
+ this.otpKey(tenantId, recipient, purpose),
1949
+ JSON.stringify(entry),
1950
+ "KEEPTTL",
1951
+ "XX"
1952
+ );
1953
+ }
1954
+ /**
1955
+ * Removes the OTP entry. Idempotent.
1956
+ *
1957
+ * @param tenantId - Tenant isolation scope.
1958
+ * @param recipient - Pre-normalized recipient identifier.
1959
+ * @param purpose - OTP purpose.
1960
+ */
1961
+ async delete(tenantId, recipient, purpose) {
1962
+ await this.redis.del(this.otpKey(tenantId, recipient, purpose));
1963
+ }
1964
+ /**
1965
+ * Atomic cooldown acquire with `SET … NX EX` — only the first concurrent caller wins.
1966
+ *
1967
+ * A non-positive `ttlSeconds` means "no resend cooldown is configured". Redis rejects
1968
+ * `SET … EX 0` with `ERR invalid expire time`, so this short-circuits: it never issues
1969
+ * the `SET`, clears any stale cooldown key, and reports success (there is nothing to
1970
+ * lock, so the caller is always free to proceed).
1971
+ *
1972
+ * @param tenantId - Tenant isolation scope.
1973
+ * @param recipient - Pre-normalized recipient identifier.
1974
+ * @param purpose - OTP purpose.
1975
+ * @param ttlSeconds - Cooldown duration in seconds; `<= 0` means no cooldown.
1976
+ * @returns `true` when acquired (or when no cooldown applies), `false` when a cooldown is already active.
1977
+ */
1978
+ async tryAcquireCooldown(tenantId, recipient, purpose, ttlSeconds) {
1979
+ const key = this.cooldownKey(tenantId, recipient, purpose);
1980
+ if (ttlSeconds <= 0) {
1981
+ await this.redis.del(key);
1982
+ return true;
1983
+ }
1984
+ const result = await this.redis.set(key, "1", "EX", ttlSeconds, "NX");
1985
+ return result === "OK";
1986
+ }
1987
+ /**
1988
+ * Remaining cooldown in seconds.
1989
+ *
1990
+ * @param tenantId - Tenant isolation scope.
1991
+ * @param recipient - Pre-normalized recipient identifier.
1992
+ * @param purpose - OTP purpose.
1993
+ * @returns Remaining seconds, or `0` when there is no active cooldown.
1994
+ */
1995
+ async getCooldown(tenantId, recipient, purpose) {
1996
+ const ttl = await this.redis.ttl(this.cooldownKey(tenantId, recipient, purpose));
1997
+ return ttl > 0 ? ttl : 0;
1998
+ }
1999
+ /**
2000
+ * Clears the cooldown key. Idempotent.
2001
+ *
2002
+ * @param tenantId - Tenant isolation scope.
2003
+ * @param recipient - Pre-normalized recipient identifier.
2004
+ * @param purpose - OTP purpose.
2005
+ */
2006
+ async clearCooldown(tenantId, recipient, purpose) {
2007
+ await this.redis.del(this.cooldownKey(tenantId, recipient, purpose));
2008
+ }
2009
+ /** Builds the OTP entry key: `{namespace}:otp:{purpose}:{sha256(tenantId:recipient)}`. */
2010
+ otpKey(tenantId, recipient, purpose) {
2011
+ return `${this.namespace}:otp:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
2012
+ }
2013
+ /** Builds the cooldown key: `{namespace}:otp_cd:{purpose}:{sha256(tenantId:recipient)}`. */
2014
+ cooldownKey(tenantId, recipient, purpose) {
2015
+ return `${this.namespace}:otp_cd:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
2016
+ }
2017
+ };
2018
+ /**
2019
+ * Atomic verify primitive. The entire read → expiry/max check → increment → write
2020
+ * runs in this single script, so concurrent calls cannot overshoot `maxAttempts`.
2021
+ * `PTTL` is read inside the script to preserve the original expiry on rewrite.
2022
+ */
2023
+ // Stryker disable next-line StringLiteral: the Lua body executes only on a real Redis server; unit tests drive a JS fake whose `eval` ignores the script text, so an emptied-string mutant is unkillable without a live Redis integration run.
2024
+ RedisOtpStorage.CONSUME_ATTEMPT_LUA = `
2025
+ local raw = redis.call('GET', KEYS[1])
2026
+ if not raw then return cjson.encode({ status = 'not_found' }) end
2027
+ local entry = cjson.decode(raw)
2028
+ if entry.expiresAt and tonumber(entry.expiresAt) < tonumber(ARGV[1]) then
2029
+ redis.call('DEL', KEYS[1])
2030
+ return cjson.encode({ status = 'not_found' })
2031
+ end
2032
+ if entry.attempts >= entry.maxAttempts then
2033
+ redis.call('DEL', KEYS[1])
2034
+ return cjson.encode({ status = 'max_attempts' })
2035
+ end
2036
+ entry.attempts = entry.attempts + 1
2037
+ local ttl = redis.call('PTTL', KEYS[1])
2038
+ if ttl and ttl > 0 then
2039
+ redis.call('SET', KEYS[1], cjson.encode(entry), 'PX', ttl)
2040
+ else
2041
+ redis.call('SET', KEYS[1], cjson.encode(entry))
2042
+ end
2043
+ return cjson.encode({ status = 'ok', entry = entry })
2044
+ `;
2045
+ RedisOtpStorage = __decorateClass([
2046
+ Injectable()
2047
+ ], RedisOtpStorage);
2048
+
2049
+ // src/shared/constants/default-ttls.ts
2050
+ var DEFAULT_TTLS = {
2051
+ /** Email verification: 1h — lets the user check their inbox at leisure. */
2052
+ OTP_EMAIL_VERIFICATION_SECONDS: 3600,
2053
+ /** Password reset: 10min — short window limits exposure of a sensitive flow. */
2054
+ OTP_PASSWORD_RESET_SECONDS: 600,
2055
+ /** MFA out-of-band: 5min — tight window for an interactive challenge. */
2056
+ OTP_MFA_OOB_SECONDS: 300,
2057
+ /** Phone verification: 10min — covers SMS delivery latency. */
2058
+ OTP_PHONE_VERIFICATION_SECONDS: 600,
2059
+ /** Magic link: 15min — slightly longer; a URL is often opened on another device. */
2060
+ OTP_MAGIC_LINK_SECONDS: 900,
2061
+ /** Resend cooldown: 60s — throttles repeated sends to the same recipient. */
2062
+ RESEND_COOLDOWN_SECONDS: 60,
2063
+ /** Generic fallback: 10min — used when no purpose-specific TTL applies. */
2064
+ OTP_GENERIC_SECONDS: 600
2065
+ };
2066
+
2067
+ export { BYMAX_NOTIFICATION_EMAIL_PROVIDER, BYMAX_NOTIFICATION_LOG_REPOSITORY, BYMAX_NOTIFICATION_OPTIONS, BYMAX_NOTIFICATION_OTP_STORAGE, BYMAX_NOTIFICATION_PUSH_PROVIDER, BYMAX_NOTIFICATION_SMS_PROVIDER, BYMAX_NOTIFICATION_TEMPLATE_RENDERER, BymaxNotificationModule, CANONICAL_EMAIL_TEMPLATES, DEFAULT_TTLS, DefaultTemplateRenderer, EmailService, InMemoryOtpStorage, NOTIFICATION_ERROR_CODES, NOTIFICATION_ERROR_DEFINITIONS, NOTIFICATION_PURPOSES, NoOpEmailProvider, NoOpNotificationLogRepository, NotificationAuditInterceptor, NotificationException, NotificationService, OtpService, RedisOtpStorage, ResendEmailProvider, cooldownExpiresAt, formatCooldown, generateOtpCode, hashTenantRecipient, safeCompare, toRetryAfterHeader };