@bymax-one/nest-notification 1.4.8 → 1.4.10
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 +214 -3
- package/README.md +86 -61
- package/dist/server/index.cjs +809 -160
- package/dist/server/index.d.cts +159 -17
- package/dist/server/index.d.ts +159 -17
- package/dist/server/index.mjs +809 -160
- package/dist/shared/index.cjs +5 -2
- package/dist/shared/index.d.cts +5 -2
- package/dist/shared/index.d.ts +5 -2
- package/dist/shared/index.mjs +5 -2
- package/dist/testing/index.cjs +79 -3
- package/dist/testing/index.d.cts +21 -0
- package/dist/testing/index.d.ts +21 -0
- package/dist/testing/index.mjs +79 -3
- package/package.json +2 -2
package/dist/server/index.cjs
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
var common = require('@nestjs/common');
|
|
4
4
|
var crypto = require('crypto');
|
|
5
|
+
var url = require('url');
|
|
5
6
|
var rxjs = require('rxjs');
|
|
6
7
|
|
|
7
8
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -29,6 +30,7 @@ var BYMAX_NOTIFICATION_SMS_PROVIDER = /* @__PURE__ */ Symbol("BYMAX_NOTIFICATION
|
|
|
29
30
|
var BYMAX_NOTIFICATION_PUSH_PROVIDER = /* @__PURE__ */ Symbol("BYMAX_NOTIFICATION_PUSH_PROVIDER");
|
|
30
31
|
var BYMAX_NOTIFICATION_TEMPLATE_RENDERER = /* @__PURE__ */ Symbol("BYMAX_NOTIFICATION_TEMPLATE_RENDERER");
|
|
31
32
|
var BYMAX_NOTIFICATION_LOG_REPOSITORY = /* @__PURE__ */ Symbol("BYMAX_NOTIFICATION_LOG_REPOSITORY");
|
|
33
|
+
var BYMAX_NOTIFICATION_AUDIT_SINK = /* @__PURE__ */ Symbol("BYMAX_NOTIFICATION_AUDIT_SINK");
|
|
32
34
|
|
|
33
35
|
// src/server/constants/default-options.constants.ts
|
|
34
36
|
var DEFAULT_MAX_ATTACHMENT_BYTES = 10485760;
|
|
@@ -45,7 +47,8 @@ var DEFAULT_OTP_OPTIONS = {
|
|
|
45
47
|
consumeOnVerify: false};
|
|
46
48
|
var DEFAULT_EMAIL_OPTIONS = {
|
|
47
49
|
defaultTags: [],
|
|
48
|
-
maxAttachmentBytes: DEFAULT_MAX_ATTACHMENT_BYTES
|
|
50
|
+
maxAttachmentBytes: DEFAULT_MAX_ATTACHMENT_BYTES,
|
|
51
|
+
maxRecipients: 50
|
|
49
52
|
};
|
|
50
53
|
var DEFAULT_AUDIT_OPTIONS = {
|
|
51
54
|
swallowErrors: true
|
|
@@ -83,6 +86,7 @@ function resolveEmail(email) {
|
|
|
83
86
|
defaultFrom: email.defaultFrom,
|
|
84
87
|
defaultTags: email.defaultTags ?? DEFAULT_EMAIL_OPTIONS.defaultTags,
|
|
85
88
|
maxAttachmentBytes: email.maxAttachmentBytes ?? DEFAULT_EMAIL_OPTIONS.maxAttachmentBytes,
|
|
89
|
+
maxRecipients: email.maxRecipients ?? DEFAULT_EMAIL_OPTIONS.maxRecipients,
|
|
86
90
|
...email.defaultFromName !== void 0 ? { defaultFromName: email.defaultFromName } : {},
|
|
87
91
|
...email.defaultReplyTo !== void 0 ? { defaultReplyTo: email.defaultReplyTo } : {}
|
|
88
92
|
};
|
|
@@ -128,10 +132,16 @@ function deepFreeze(value) {
|
|
|
128
132
|
return value;
|
|
129
133
|
}
|
|
130
134
|
|
|
131
|
-
// src/server/
|
|
132
|
-
var
|
|
133
|
-
|
|
134
|
-
|
|
135
|
+
// src/server/utils/describe-error.ts
|
|
136
|
+
var UNPRINTABLE_ERROR = "unprintable error";
|
|
137
|
+
function describeError(reason, fallback = UNPRINTABLE_ERROR) {
|
|
138
|
+
try {
|
|
139
|
+
const message = reason?.message;
|
|
140
|
+
return typeof message === "string" ? message : String(reason);
|
|
141
|
+
} catch {
|
|
142
|
+
return fallback;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
135
145
|
|
|
136
146
|
// src/shared/constants/error-codes.ts
|
|
137
147
|
var NOTIFICATION_ERROR_CODES = {
|
|
@@ -151,6 +161,7 @@ var NOTIFICATION_ERROR_CODES = {
|
|
|
151
161
|
OTP_EXPIRED: "notification.otp_expired",
|
|
152
162
|
OTP_MAX_ATTEMPTS_EXCEEDED: "notification.otp_max_attempts_exceeded",
|
|
153
163
|
OTP_INVALID_CODE: "notification.otp_invalid_code",
|
|
164
|
+
OTP_STORAGE_UNAVAILABLE: "notification.otp_storage_unavailable",
|
|
154
165
|
OTP_INVALID_LENGTH: "notification.otp_invalid_length",
|
|
155
166
|
SMS_PROVIDER_NOT_CONFIGURED: "notification.sms_provider_not_configured",
|
|
156
167
|
SMS_SEND_FAILED: "notification.sms_send_failed",
|
|
@@ -160,8 +171,10 @@ var NOTIFICATION_ERROR_CODES = {
|
|
|
160
171
|
AUDIT_LOG_FAILED: "notification.audit_log_failed",
|
|
161
172
|
CHANNEL_DISABLED: "notification.channel_disabled",
|
|
162
173
|
/**
|
|
163
|
-
* A `tenantId` or `
|
|
164
|
-
* boundary
|
|
174
|
+
* A `tenantId`, `recipient` or `purpose` that cannot scope an OTP reached a
|
|
175
|
+
* scoping boundary: empty, whitespace-only, not a string at all, carrying a
|
|
176
|
+
* control character, or, for a purpose, longer than 64 characters or made of
|
|
177
|
+
* anything but `A-Z a-z 0-9 : _ -`. Distinct from
|
|
165
178
|
* {@link EMAIL_INVALID_RECIPIENT}, which is about a malformed address rather
|
|
166
179
|
* than a value that cannot scope anything.
|
|
167
180
|
*/
|
|
@@ -185,7 +198,7 @@ var NOTIFICATION_ERROR_DEFINITIONS = {
|
|
|
185
198
|
status: common.HttpStatus.PAYLOAD_TOO_LARGE,
|
|
186
199
|
message: "Email attachments exceed size limit"
|
|
187
200
|
},
|
|
188
|
-
/**
|
|
201
|
+
/** Raised for an OTP recipient that is not one mailbox, and for a message over `maxRecipients`. */
|
|
189
202
|
EMAIL_INVALID_RECIPIENT: {
|
|
190
203
|
code: NOTIFICATION_ERROR_CODES.EMAIL_INVALID_RECIPIENT,
|
|
191
204
|
status: common.HttpStatus.BAD_REQUEST,
|
|
@@ -244,6 +257,12 @@ var NOTIFICATION_ERROR_DEFINITIONS = {
|
|
|
244
257
|
status: common.HttpStatus.TOO_MANY_REQUESTS,
|
|
245
258
|
message: "Maximum OTP attempts exceeded"
|
|
246
259
|
},
|
|
260
|
+
/** Raised when the OTP store cannot be reached, is closed, or timed out: the caller may retry. */
|
|
261
|
+
OTP_STORAGE_UNAVAILABLE: {
|
|
262
|
+
code: NOTIFICATION_ERROR_CODES.OTP_STORAGE_UNAVAILABLE,
|
|
263
|
+
status: common.HttpStatus.SERVICE_UNAVAILABLE,
|
|
264
|
+
message: "OTP storage unavailable"
|
|
265
|
+
},
|
|
247
266
|
/** Reserved: `verify()` returns `{ valid: false, reason: 'invalid_code' }` instead of throwing. */
|
|
248
267
|
OTP_INVALID_CODE: {
|
|
249
268
|
code: NOTIFICATION_ERROR_CODES.OTP_INVALID_CODE,
|
|
@@ -298,24 +317,13 @@ var NOTIFICATION_ERROR_DEFINITIONS = {
|
|
|
298
317
|
INVALID_SCOPE_IDENTIFIER: {
|
|
299
318
|
code: NOTIFICATION_ERROR_CODES.INVALID_SCOPE_IDENTIFIER,
|
|
300
319
|
status: common.HttpStatus.BAD_REQUEST,
|
|
301
|
-
message: "
|
|
320
|
+
message: "A tenant, recipient or purpose identifier is not valid"
|
|
302
321
|
}
|
|
303
322
|
};
|
|
304
323
|
var NOTIFICATION_ERROR_DEFINITION_MAP = new Map(
|
|
305
324
|
Object.entries(NOTIFICATION_ERROR_DEFINITIONS)
|
|
306
325
|
);
|
|
307
326
|
|
|
308
|
-
// src/server/utils/describe-error.ts
|
|
309
|
-
var UNPRINTABLE_ERROR = "unprintable error";
|
|
310
|
-
function describeError(reason, fallback = UNPRINTABLE_ERROR) {
|
|
311
|
-
try {
|
|
312
|
-
const message = reason?.message;
|
|
313
|
-
return typeof message === "string" ? message : String(reason);
|
|
314
|
-
} catch {
|
|
315
|
-
return fallback;
|
|
316
|
-
}
|
|
317
|
-
}
|
|
318
|
-
|
|
319
327
|
// src/server/errors/notification-exception.ts
|
|
320
328
|
var FALLBACK_DEFINITION = {
|
|
321
329
|
code: "notification.unknown_error",
|
|
@@ -374,6 +382,52 @@ var NotificationException = class extends common.HttpException {
|
|
|
374
382
|
}
|
|
375
383
|
};
|
|
376
384
|
|
|
385
|
+
// src/server/utils/tenant-scope.ts
|
|
386
|
+
var CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
|
|
387
|
+
function refuse(owner, label, reason) {
|
|
388
|
+
return new NotificationException(
|
|
389
|
+
"INVALID_SCOPE_IDENTIFIER",
|
|
390
|
+
{ boundary: owner, parameter: label, reason },
|
|
391
|
+
{ message: `[${owner}] ${label} ${reason}` }
|
|
392
|
+
);
|
|
393
|
+
}
|
|
394
|
+
function assertIdentifies(owner, label, value) {
|
|
395
|
+
if (typeof value !== "string") {
|
|
396
|
+
throw refuse(owner, label, `expected a string, received ${typeof value}`);
|
|
397
|
+
}
|
|
398
|
+
if (value.trim() === "") {
|
|
399
|
+
throw refuse(owner, label, "empty or whitespace-only");
|
|
400
|
+
}
|
|
401
|
+
if (CONTROL_CHARACTER.test(value)) {
|
|
402
|
+
throw refuse(owner, label, "contains a control character");
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
var MAX_PURPOSE_LENGTH = 64;
|
|
406
|
+
var PURPOSE_CHARACTERS = /^[A-Za-z0-9:_-]+$/;
|
|
407
|
+
function purposeProblem(value) {
|
|
408
|
+
if (typeof value !== "string") {
|
|
409
|
+
return `expected a string, received ${typeof value}`;
|
|
410
|
+
}
|
|
411
|
+
if (value === "") {
|
|
412
|
+
return "empty";
|
|
413
|
+
}
|
|
414
|
+
if (value.length > MAX_PURPOSE_LENGTH) {
|
|
415
|
+
return `longer than ${String(MAX_PURPOSE_LENGTH)} characters`;
|
|
416
|
+
}
|
|
417
|
+
return PURPOSE_CHARACTERS.test(value) ? void 0 : "contains a character outside A-Z a-z 0-9 : _ -";
|
|
418
|
+
}
|
|
419
|
+
function assertPurpose(owner, value) {
|
|
420
|
+
const problem = purposeProblem(value);
|
|
421
|
+
if (problem !== void 0) {
|
|
422
|
+
throw refuse(owner, "purpose", problem);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
// src/server/config/default-options.ts
|
|
427
|
+
var VALID_CODE_TYPES = ["numeric", "alpha", "alphanumeric"];
|
|
428
|
+
var OTP_MIN_LENGTH = 1;
|
|
429
|
+
var OTP_MAX_LENGTH = 32;
|
|
430
|
+
|
|
377
431
|
// src/server/config/validate-options.ts
|
|
378
432
|
function validateOptions(options) {
|
|
379
433
|
if (!options.email && !options.otp && !options.sms && !options.push) {
|
|
@@ -419,6 +473,11 @@ function validateEmailOptions(email) {
|
|
|
419
473
|
"[BymaxNotificationModule] options.email.defaultFrom does not look like an email"
|
|
420
474
|
);
|
|
421
475
|
}
|
|
476
|
+
if (email.maxRecipients !== void 0 && (!Number.isInteger(email.maxRecipients) || email.maxRecipients < 1)) {
|
|
477
|
+
throw new Error(
|
|
478
|
+
"[BymaxNotificationModule] options.email.maxRecipients must be a positive integer"
|
|
479
|
+
);
|
|
480
|
+
}
|
|
422
481
|
}
|
|
423
482
|
function validateCodeSecret(secret) {
|
|
424
483
|
if (typeof secret !== "string" || Buffer.byteLength(secret, "utf8") < MIN_CODE_SECRET_BYTES) {
|
|
@@ -458,6 +517,14 @@ function validateOtpOptions(otp) {
|
|
|
458
517
|
if (otp.defaultMaxAttempts !== void 0 && otp.defaultMaxAttempts < 1) {
|
|
459
518
|
throw new Error("[BymaxNotificationModule] options.otp.defaultMaxAttempts must be at least 1");
|
|
460
519
|
}
|
|
520
|
+
for (const key of Object.keys(otp.perPurpose ?? {})) {
|
|
521
|
+
const problem = purposeProblem(key);
|
|
522
|
+
if (problem !== void 0) {
|
|
523
|
+
throw new Error(
|
|
524
|
+
`[BymaxNotificationModule] options.otp.perPurpose has the key ${JSON.stringify(key)}, which is not a valid purpose: ${problem}`
|
|
525
|
+
);
|
|
526
|
+
}
|
|
527
|
+
}
|
|
461
528
|
if (otp.resendCooldownSeconds !== void 0 && otp.resendCooldownSeconds < 0) {
|
|
462
529
|
throw new Error(
|
|
463
530
|
"[BymaxNotificationModule] options.otp.resendCooldownSeconds must be 0 or greater"
|
|
@@ -540,14 +607,13 @@ exports.DefaultTemplateRenderer = class DefaultTemplateRenderer {
|
|
|
540
607
|
});
|
|
541
608
|
}
|
|
542
609
|
/**
|
|
543
|
-
* Builds a variable resolver for one render call.
|
|
544
|
-
*
|
|
545
|
-
*
|
|
610
|
+
* Builds a variable resolver for one render call. A key resolves only when the object holds it as
|
|
611
|
+
* an own enumerable property, so neither flat nor nested resolution can reach inherited or
|
|
612
|
+
* prototype keys, and only the property that is named is read.
|
|
546
613
|
*/
|
|
547
614
|
buildResolver(data) {
|
|
548
615
|
if (!this.enableNestedPaths) {
|
|
549
|
-
|
|
550
|
-
return (path) => values.get(path);
|
|
616
|
+
return (path) => this.ownValue(data, path);
|
|
551
617
|
}
|
|
552
618
|
return (path) => this.resolveNested(data, path);
|
|
553
619
|
}
|
|
@@ -558,10 +624,17 @@ exports.DefaultTemplateRenderer = class DefaultTemplateRenderer {
|
|
|
558
624
|
if (current === null || current === void 0 || typeof current !== "object") {
|
|
559
625
|
return void 0;
|
|
560
626
|
}
|
|
561
|
-
current =
|
|
627
|
+
current = this.ownValue(current, key);
|
|
562
628
|
}
|
|
563
629
|
return current;
|
|
564
630
|
}
|
|
631
|
+
/**
|
|
632
|
+
* The value of `key` when `object` holds it as an own enumerable property, otherwise `undefined`.
|
|
633
|
+
* Called through `Object.prototype` so an object without a prototype works too.
|
|
634
|
+
*/
|
|
635
|
+
ownValue(object, key) {
|
|
636
|
+
return Object.prototype.propertyIsEnumerable.call(object, key) ? Reflect.get(object, key) : void 0;
|
|
637
|
+
}
|
|
565
638
|
/**
|
|
566
639
|
* Validates a registered template shape, throwing on the offending key. The
|
|
567
640
|
* optional `text` body, when present, must be a string — a non-string `text`
|
|
@@ -586,6 +659,87 @@ exports.DefaultTemplateRenderer = class DefaultTemplateRenderer {
|
|
|
586
659
|
exports.DefaultTemplateRenderer = __decorateClass([
|
|
587
660
|
common.Injectable()
|
|
588
661
|
], exports.DefaultTemplateRenderer);
|
|
662
|
+
|
|
663
|
+
// src/server/utils/audit-escape.ts
|
|
664
|
+
var MAX_METADATA_DEPTH = 4;
|
|
665
|
+
var DEPTH_LIMIT_MARKER = "[depth limit]";
|
|
666
|
+
var CIRCULAR_MARKER = "[circular]";
|
|
667
|
+
var NON_PLAIN_MARKER = "[non-plain value]";
|
|
668
|
+
var ESCAPED = /[\p{Cc}\p{Zl}\p{Zp}\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/gu;
|
|
669
|
+
var NAMED = /* @__PURE__ */ new Map([
|
|
670
|
+
["\n", "\\n"],
|
|
671
|
+
["\r", "\\r"],
|
|
672
|
+
[" ", "\\t"]
|
|
673
|
+
]);
|
|
674
|
+
function sequenceOf(character) {
|
|
675
|
+
return NAMED.get(character) ?? `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`;
|
|
676
|
+
}
|
|
677
|
+
function escapeAuditString(value) {
|
|
678
|
+
return value.replace(ESCAPED, sequenceOf);
|
|
679
|
+
}
|
|
680
|
+
function isPlainObject(value) {
|
|
681
|
+
const prototype = Object.getPrototypeOf(value);
|
|
682
|
+
return prototype === Object.prototype || prototype === null;
|
|
683
|
+
}
|
|
684
|
+
function escapeRecord(record, level, ancestors) {
|
|
685
|
+
const escaped = /* @__PURE__ */ new Map();
|
|
686
|
+
for (const [key, value] of Object.entries(record)) {
|
|
687
|
+
const base = escapeAuditString(key);
|
|
688
|
+
let name = base;
|
|
689
|
+
for (let attempt = 2; escaped.has(name); attempt++) {
|
|
690
|
+
name = `${base}#${attempt}`;
|
|
691
|
+
}
|
|
692
|
+
escaped.set(name, escapeValue(value, level + 1, ancestors));
|
|
693
|
+
}
|
|
694
|
+
return Object.fromEntries(escaped);
|
|
695
|
+
}
|
|
696
|
+
function escapeValue(value, level, ancestors) {
|
|
697
|
+
if (typeof value === "string") {
|
|
698
|
+
return escapeAuditString(value);
|
|
699
|
+
}
|
|
700
|
+
if (typeof value === "function" || typeof value === "symbol") {
|
|
701
|
+
return NON_PLAIN_MARKER;
|
|
702
|
+
}
|
|
703
|
+
if (typeof value !== "object" || value === null) {
|
|
704
|
+
return value;
|
|
705
|
+
}
|
|
706
|
+
if (level > MAX_METADATA_DEPTH) {
|
|
707
|
+
return DEPTH_LIMIT_MARKER;
|
|
708
|
+
}
|
|
709
|
+
if (ancestors.has(value)) {
|
|
710
|
+
return CIRCULAR_MARKER;
|
|
711
|
+
}
|
|
712
|
+
const isArray = Array.isArray(value);
|
|
713
|
+
if (!isArray && !isPlainObject(value)) {
|
|
714
|
+
return NON_PLAIN_MARKER;
|
|
715
|
+
}
|
|
716
|
+
ancestors.add(value);
|
|
717
|
+
try {
|
|
718
|
+
return isArray ? value.map((item) => escapeValue(item, level + 1, ancestors)) : escapeRecord(value, level, ancestors);
|
|
719
|
+
} finally {
|
|
720
|
+
ancestors.delete(value);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
function escapeAuditEntry(entry) {
|
|
724
|
+
return escapeRecord(
|
|
725
|
+
entry,
|
|
726
|
+
0,
|
|
727
|
+
/* @__PURE__ */ new WeakSet()
|
|
728
|
+
);
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
// src/server/providers/escaping-log-repository.ts
|
|
732
|
+
var EscapingLogRepository = class {
|
|
733
|
+
/** @param inner - The host's repository that receives the escaped entries. */
|
|
734
|
+
constructor(inner) {
|
|
735
|
+
this.inner = inner;
|
|
736
|
+
this.name = inner.name;
|
|
737
|
+
}
|
|
738
|
+
/** Writes `entry` to the wrapped repository with its strings escaped. */
|
|
739
|
+
async create(entry) {
|
|
740
|
+
await this.inner.create(escapeAuditEntry(entry));
|
|
741
|
+
}
|
|
742
|
+
};
|
|
589
743
|
exports.NoOpNotificationLogRepository = class NoOpNotificationLogRepository {
|
|
590
744
|
constructor() {
|
|
591
745
|
this.name = "noop";
|
|
@@ -685,6 +839,89 @@ var AuditWriteWarning = class {
|
|
|
685
839
|
}
|
|
686
840
|
};
|
|
687
841
|
|
|
842
|
+
// src/server/utils/availability.ts
|
|
843
|
+
var UNAVAILABLE_CODES = /* @__PURE__ */ new Set([
|
|
844
|
+
"ECONNREFUSED",
|
|
845
|
+
"ECONNRESET",
|
|
846
|
+
"ETIMEDOUT",
|
|
847
|
+
"ESOCKETTIMEDOUT",
|
|
848
|
+
"EPIPE",
|
|
849
|
+
"ENOTFOUND",
|
|
850
|
+
"EAI_AGAIN",
|
|
851
|
+
"EHOSTUNREACH",
|
|
852
|
+
"ENETUNREACH",
|
|
853
|
+
"ECONNABORTED",
|
|
854
|
+
// Set by the reference providers when a provider answered that it is down, or could not be asked.
|
|
855
|
+
"EUNAVAILABLE",
|
|
856
|
+
// nodemailer's own codes: connection, socket and DNS failures.
|
|
857
|
+
"ECONNECTION",
|
|
858
|
+
"ESOCKET",
|
|
859
|
+
"EDNS"
|
|
860
|
+
]);
|
|
861
|
+
var UNAVAILABLE_MESSAGES = [
|
|
862
|
+
/^Connection is closed\.$/,
|
|
863
|
+
/^Command timed out$/,
|
|
864
|
+
/^Stream isn't writeable and enableOfflineQueue options is false$/,
|
|
865
|
+
/^Reached the max retries per request limit \(which is \d+\)\./
|
|
866
|
+
];
|
|
867
|
+
var UNAVAILABLE_REPLY = /^(?:READONLY|LOADING|MASTERDOWN|CLUSTERDOWN|TRYAGAIN)\b/;
|
|
868
|
+
var MAX_RETRIES_NAME = "MaxRetriesPerRequestError";
|
|
869
|
+
var MAX_LINKS = 8;
|
|
870
|
+
function read(value, key) {
|
|
871
|
+
try {
|
|
872
|
+
return Reflect.get(Object(value), key);
|
|
873
|
+
} catch {
|
|
874
|
+
return void 0;
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
function isUnavailableLink(error) {
|
|
878
|
+
const code = read(error, "code");
|
|
879
|
+
if (typeof code === "string" && UNAVAILABLE_CODES.has(code)) {
|
|
880
|
+
return true;
|
|
881
|
+
}
|
|
882
|
+
if (read(error, "name") === MAX_RETRIES_NAME) {
|
|
883
|
+
return true;
|
|
884
|
+
}
|
|
885
|
+
const message = read(error, "message");
|
|
886
|
+
return typeof message === "string" && (UNAVAILABLE_REPLY.test(message) || UNAVAILABLE_MESSAGES.some((pattern) => pattern.test(message)));
|
|
887
|
+
}
|
|
888
|
+
function isUnavailableError(error) {
|
|
889
|
+
const seen = /* @__PURE__ */ new Set();
|
|
890
|
+
let current = error;
|
|
891
|
+
for (let remaining = MAX_LINKS; remaining > 0; remaining -= 1) {
|
|
892
|
+
if (seen.has(current)) {
|
|
893
|
+
return false;
|
|
894
|
+
}
|
|
895
|
+
seen.add(current);
|
|
896
|
+
if (isUnavailableLink(current)) {
|
|
897
|
+
return true;
|
|
898
|
+
}
|
|
899
|
+
current = read(current, "cause");
|
|
900
|
+
}
|
|
901
|
+
return false;
|
|
902
|
+
}
|
|
903
|
+
var CODE_TOKEN = /^[A-Z][A-Z0-9_]{1,31}$/;
|
|
904
|
+
function errorCodeOf(error) {
|
|
905
|
+
const seen = /* @__PURE__ */ new Set();
|
|
906
|
+
let current = error;
|
|
907
|
+
let first;
|
|
908
|
+
for (let remaining = MAX_LINKS; remaining > 0; remaining -= 1) {
|
|
909
|
+
if (seen.has(current)) {
|
|
910
|
+
break;
|
|
911
|
+
}
|
|
912
|
+
seen.add(current);
|
|
913
|
+
const code = read(current, "code");
|
|
914
|
+
if (typeof code === "string" && CODE_TOKEN.test(code)) {
|
|
915
|
+
if (UNAVAILABLE_CODES.has(code)) {
|
|
916
|
+
return code;
|
|
917
|
+
}
|
|
918
|
+
first ??= code;
|
|
919
|
+
}
|
|
920
|
+
current = read(current, "cause");
|
|
921
|
+
}
|
|
922
|
+
return first;
|
|
923
|
+
}
|
|
924
|
+
|
|
688
925
|
// src/server/utils/delivery-status.ts
|
|
689
926
|
var MAX_SUBFIELD_DIGITS = 3;
|
|
690
927
|
var BASIC_STATUS = /(?<![\d.])([245]\d\d)(?![\d.])/g;
|
|
@@ -724,6 +961,26 @@ function withoutDeclaredValues(status, declared) {
|
|
|
724
961
|
};
|
|
725
962
|
}
|
|
726
963
|
|
|
964
|
+
// src/server/utils/recipient-list.ts
|
|
965
|
+
var MAX_ADDRESS_LENGTH = 254;
|
|
966
|
+
var NOT_A_PLAIN_MAILBOX = /[\s\p{Cc},;<>()[\]"\\:]/u;
|
|
967
|
+
var RECIPIENT_DELIMITERS = /[,;]/;
|
|
968
|
+
function assertSingleMailbox(recipient) {
|
|
969
|
+
const address = recipient.trim();
|
|
970
|
+
const at = address.indexOf("@");
|
|
971
|
+
const refused = address.length > MAX_ADDRESS_LENGTH || NOT_A_PLAIN_MAILBOX.test(address) || at < 1 || at !== address.lastIndexOf("@") || at === address.length - 1;
|
|
972
|
+
if (refused) {
|
|
973
|
+
throw new NotificationException("EMAIL_INVALID_RECIPIENT", { reason: "not_a_single_mailbox" });
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
function countRecipients(field) {
|
|
977
|
+
if (field === void 0) {
|
|
978
|
+
return 0;
|
|
979
|
+
}
|
|
980
|
+
const entries = typeof field === "string" ? [field] : field;
|
|
981
|
+
return entries.flatMap((entry) => entry.split(RECIPIENT_DELIMITERS)).filter((segment) => segment.trim() !== "").length;
|
|
982
|
+
}
|
|
983
|
+
|
|
727
984
|
// src/server/utils/redact.ts
|
|
728
985
|
var REDACTED_VALUE = "[redacted]";
|
|
729
986
|
function redactValues(text, values) {
|
|
@@ -760,25 +1017,40 @@ function readRedactedMessage(error, values) {
|
|
|
760
1017
|
const message = describeError(error, REDACTED_VALUE);
|
|
761
1018
|
return values ? redactValues(message, values) : message;
|
|
762
1019
|
}
|
|
763
|
-
|
|
764
|
-
|
|
1020
|
+
var MAX_ERROR_CHAIN_LINKS = 32;
|
|
1021
|
+
function inspectErrorChain(error) {
|
|
1022
|
+
const { parts, truncated } = walkChain(error, true);
|
|
1023
|
+
return { parts, withheld: truncated };
|
|
765
1024
|
}
|
|
766
1025
|
function collectErrorChainMessages(error) {
|
|
767
|
-
return walkChain(error, false);
|
|
1026
|
+
return walkChain(error, false).parts.join("\n");
|
|
768
1027
|
}
|
|
769
1028
|
function walkChain(error, includeStack) {
|
|
770
1029
|
const parts = [];
|
|
771
1030
|
const seen = /* @__PURE__ */ new Set();
|
|
772
1031
|
let current = error;
|
|
1032
|
+
let truncated = false;
|
|
1033
|
+
let remaining = MAX_ECHO_SCAN_LENGTH;
|
|
1034
|
+
const take = (text) => {
|
|
1035
|
+
const kept = text.slice(0, remaining);
|
|
1036
|
+
truncated ||= kept.length < text.length;
|
|
1037
|
+
remaining -= kept.length;
|
|
1038
|
+
return kept;
|
|
1039
|
+
};
|
|
773
1040
|
while (current !== null && current !== void 0 && !seen.has(current)) {
|
|
1041
|
+
if (seen.size === MAX_ERROR_CHAIN_LINKS) {
|
|
1042
|
+
truncated = true;
|
|
1043
|
+
break;
|
|
1044
|
+
}
|
|
774
1045
|
seen.add(current);
|
|
775
|
-
parts.push(readRedactedMessage(current));
|
|
1046
|
+
parts.push(take(readRedactedMessage(current)));
|
|
776
1047
|
if (!isSafeError(current)) {
|
|
777
1048
|
break;
|
|
778
1049
|
}
|
|
779
1050
|
try {
|
|
780
|
-
|
|
781
|
-
|
|
1051
|
+
const stack = includeStack ? current.stack : void 0;
|
|
1052
|
+
if (typeof stack === "string") {
|
|
1053
|
+
parts.push(take(stack));
|
|
782
1054
|
}
|
|
783
1055
|
} catch {
|
|
784
1056
|
}
|
|
@@ -787,31 +1059,119 @@ function walkChain(error, includeStack) {
|
|
|
787
1059
|
} catch {
|
|
788
1060
|
}
|
|
789
1061
|
}
|
|
790
|
-
return parts
|
|
1062
|
+
return { parts, truncated };
|
|
791
1063
|
}
|
|
792
1064
|
var MIN_ECHO_LENGTH = 16;
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
1065
|
+
var MAX_ECHO_SCAN_LENGTH = 65536;
|
|
1066
|
+
function collectEchoedExcerpts(fields, reference) {
|
|
1067
|
+
const all = typeof fields === "string" ? [fields] : fields;
|
|
1068
|
+
let budget = MAX_ECHO_SCAN_LENGTH;
|
|
1069
|
+
const examined = [];
|
|
1070
|
+
const whole = [];
|
|
1071
|
+
for (const field of all) {
|
|
1072
|
+
if (field.length > budget) {
|
|
1073
|
+
if (field.length >= MIN_ECHO_LENGTH) {
|
|
1074
|
+
whole.push(field);
|
|
803
1075
|
}
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
1076
|
+
} else {
|
|
1077
|
+
examined.push(field);
|
|
1078
|
+
budget -= field.length;
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
const units = examined.flatMap((field) => [...field.split("").map((c) => c.charCodeAt(0)), -1]);
|
|
1082
|
+
const reach = longestEchoFrom(units, reference);
|
|
1083
|
+
const excerpts = whole;
|
|
1084
|
+
let offset = 0;
|
|
1085
|
+
for (const field of examined) {
|
|
1086
|
+
let index = 0;
|
|
1087
|
+
while (index + MIN_ECHO_LENGTH <= field.length) {
|
|
1088
|
+
const longest = reach.at(offset + index);
|
|
1089
|
+
if (longest < MIN_ECHO_LENGTH) {
|
|
1090
|
+
index += 1;
|
|
1091
|
+
continue;
|
|
1092
|
+
}
|
|
1093
|
+
excerpts.push(field.slice(index, index + longest));
|
|
1094
|
+
index += longest;
|
|
809
1095
|
}
|
|
810
|
-
|
|
811
|
-
index += longest;
|
|
1096
|
+
offset += field.length + 1;
|
|
812
1097
|
}
|
|
813
1098
|
return excerpts;
|
|
814
1099
|
}
|
|
1100
|
+
function longestEchoFrom(units, reference) {
|
|
1101
|
+
const { root, states, created } = buildEchoAutomaton(units);
|
|
1102
|
+
walkReference(root, reference);
|
|
1103
|
+
propagateMatches(states);
|
|
1104
|
+
return Int32Array.from(created.map((entry) => entry.best).reverse());
|
|
1105
|
+
}
|
|
1106
|
+
function buildEchoAutomaton(units) {
|
|
1107
|
+
const root = { length: 0, link: null, next: /* @__PURE__ */ new Map(), best: 0 };
|
|
1108
|
+
const states = [];
|
|
1109
|
+
const created = [];
|
|
1110
|
+
let last = root;
|
|
1111
|
+
for (const code of [...units].reverse()) {
|
|
1112
|
+
const current = { length: last.length + 1, link: root, next: /* @__PURE__ */ new Map(), best: 0 };
|
|
1113
|
+
states.push(current);
|
|
1114
|
+
created.push(current);
|
|
1115
|
+
extendAutomaton(states, last, current, code);
|
|
1116
|
+
last = current;
|
|
1117
|
+
}
|
|
1118
|
+
return { root, states, created };
|
|
1119
|
+
}
|
|
1120
|
+
function extendAutomaton(states, last, current, code) {
|
|
1121
|
+
let walker = last;
|
|
1122
|
+
while (walker !== null && !walker.next.has(code)) {
|
|
1123
|
+
walker.next.set(code, current);
|
|
1124
|
+
walker = walker.link;
|
|
1125
|
+
}
|
|
1126
|
+
const target = walker?.next.get(code);
|
|
1127
|
+
if (walker === null || target === void 0) {
|
|
1128
|
+
return;
|
|
1129
|
+
}
|
|
1130
|
+
if (walker.length + 1 === target.length) {
|
|
1131
|
+
current.link = target;
|
|
1132
|
+
return;
|
|
1133
|
+
}
|
|
1134
|
+
const clone = {
|
|
1135
|
+
length: walker.length + 1,
|
|
1136
|
+
link: target.link,
|
|
1137
|
+
next: new Map(target.next),
|
|
1138
|
+
best: 0
|
|
1139
|
+
};
|
|
1140
|
+
states.push(clone);
|
|
1141
|
+
while (walker !== null && walker.next.get(code) === target) {
|
|
1142
|
+
walker.next.set(code, clone);
|
|
1143
|
+
walker = walker.link;
|
|
1144
|
+
}
|
|
1145
|
+
target.link = clone;
|
|
1146
|
+
current.link = clone;
|
|
1147
|
+
}
|
|
1148
|
+
function walkReference(root, reference) {
|
|
1149
|
+
let state = root;
|
|
1150
|
+
let matched = 0;
|
|
1151
|
+
for (let position = reference.length - 1; position >= 0; position -= 1) {
|
|
1152
|
+
const code = reference.charCodeAt(position);
|
|
1153
|
+
while (state !== root && !state.next.has(code)) {
|
|
1154
|
+
state = state.link;
|
|
1155
|
+
matched = state.length;
|
|
1156
|
+
}
|
|
1157
|
+
const advanced = state.next.get(code);
|
|
1158
|
+
if (advanced !== void 0) {
|
|
1159
|
+
state = advanced;
|
|
1160
|
+
matched += 1;
|
|
1161
|
+
state.best = Math.max(state.best, matched);
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
function propagateMatches(states) {
|
|
1166
|
+
const byLength = [...states].sort((left, right) => right.length - left.length);
|
|
1167
|
+
for (const child of byLength) {
|
|
1168
|
+
const parent = child.link;
|
|
1169
|
+
parent.best = Math.max(parent.best, Math.min(child.best, parent.length));
|
|
1170
|
+
}
|
|
1171
|
+
for (const child of [...byLength].reverse()) {
|
|
1172
|
+
child.best = Math.max(child.best, child.link.best);
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
815
1175
|
function isSafeError(value) {
|
|
816
1176
|
try {
|
|
817
1177
|
return value instanceof Error;
|
|
@@ -970,27 +1330,6 @@ function buildRedactedCopy(name, message, stack) {
|
|
|
970
1330
|
return copy;
|
|
971
1331
|
}
|
|
972
1332
|
|
|
973
|
-
// src/server/utils/tenant-scope.ts
|
|
974
|
-
var CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
|
|
975
|
-
function refuse(owner, label, reason) {
|
|
976
|
-
return new NotificationException(
|
|
977
|
-
"INVALID_SCOPE_IDENTIFIER",
|
|
978
|
-
{ boundary: owner, parameter: label, reason },
|
|
979
|
-
{ message: `[${owner}] ${label} ${reason}` }
|
|
980
|
-
);
|
|
981
|
-
}
|
|
982
|
-
function assertIdentifies(owner, label, value) {
|
|
983
|
-
if (typeof value !== "string") {
|
|
984
|
-
throw refuse(owner, label, `expected a string, received ${typeof value}`);
|
|
985
|
-
}
|
|
986
|
-
if (value.trim() === "") {
|
|
987
|
-
throw refuse(owner, label, "empty or whitespace-only");
|
|
988
|
-
}
|
|
989
|
-
if (CONTROL_CHARACTER.test(value)) {
|
|
990
|
-
throw refuse(owner, label, "contains a control character");
|
|
991
|
-
}
|
|
992
|
-
}
|
|
993
|
-
|
|
994
1333
|
// src/server/services/email.service.ts
|
|
995
1334
|
var FALLBACK_LOCALE = "en";
|
|
996
1335
|
var OTP_TEMPLATE_REMEDY = "register an 'otp_code' template (for example 'otp_code::en') in your template renderer, such as DefaultTemplateRenderer; the OTP email can use another template through the emailTemplate option of generate()";
|
|
@@ -1013,6 +1352,9 @@ function readAttachedStatus(error) {
|
|
|
1013
1352
|
return void 0;
|
|
1014
1353
|
}
|
|
1015
1354
|
}
|
|
1355
|
+
function unavailableStatus(error) {
|
|
1356
|
+
return isUnavailableError(error) ? { status: common.HttpStatus.SERVICE_UNAVAILABLE } : {};
|
|
1357
|
+
}
|
|
1016
1358
|
exports.EmailService = class EmailService {
|
|
1017
1359
|
/**
|
|
1018
1360
|
* @param options - The resolved, frozen module options.
|
|
@@ -1043,12 +1385,14 @@ exports.EmailService = class EmailService {
|
|
|
1043
1385
|
* @returns The provider's message id.
|
|
1044
1386
|
* @throws NotificationException `EMAIL_PROVIDER_NOT_CONFIGURED`, `INVALID_SCOPE_IDENTIFIER`
|
|
1045
1387
|
* (a blank tenant or one with a control character), `EMAIL_ATTACHMENTS_TOO_LARGE`,
|
|
1388
|
+
* `EMAIL_INVALID_RECIPIENT` (more recipients than `maxRecipients`),
|
|
1046
1389
|
* `EMAIL_SEND_FAILED`, or `AUDIT_LOG_FAILED` (only when `audit.swallowErrors` is `false`).
|
|
1047
1390
|
*/
|
|
1048
1391
|
async send(input) {
|
|
1049
1392
|
const email = this.requireEmailOptions();
|
|
1050
1393
|
assertIdentifies("EmailService", "tenantId", input.tenantId);
|
|
1051
1394
|
this.guardAttachmentSize(input.attachments, email.maxAttachmentBytes);
|
|
1395
|
+
this.guardRecipientCount(input, email.maxRecipients);
|
|
1052
1396
|
const sendOptions = this.buildSendOptions(input, email);
|
|
1053
1397
|
const recipient = this.maskRecipients(input.to);
|
|
1054
1398
|
const result = await this.deliver(sendOptions, input, recipient);
|
|
@@ -1081,10 +1425,15 @@ exports.EmailService = class EmailService {
|
|
|
1081
1425
|
try {
|
|
1082
1426
|
return await this.provider.send(sendOptions);
|
|
1083
1427
|
} catch (error) {
|
|
1084
|
-
|
|
1428
|
+
const chain = inspectErrorChain(error);
|
|
1429
|
+
if (input.publishProviderText === false || chain.withheld) {
|
|
1085
1430
|
await this.failWithoutProviderText(error, input, recipient);
|
|
1086
1431
|
}
|
|
1087
|
-
const secretValues = this.gatherRedactionValues(
|
|
1432
|
+
const secretValues = this.gatherRedactionValues(
|
|
1433
|
+
chain.parts,
|
|
1434
|
+
input.auditRedactValues,
|
|
1435
|
+
sendOptions
|
|
1436
|
+
);
|
|
1088
1437
|
await this.audit(
|
|
1089
1438
|
this.auditEntry("failed", input.tenantId, recipient, input.userId, {
|
|
1090
1439
|
errorMessage: readRedactedMessage(error, secretValues)
|
|
@@ -1093,7 +1442,10 @@ exports.EmailService = class EmailService {
|
|
|
1093
1442
|
throw new NotificationException(
|
|
1094
1443
|
"EMAIL_SEND_FAILED",
|
|
1095
1444
|
{ providerName: this.provider.name },
|
|
1096
|
-
{
|
|
1445
|
+
{
|
|
1446
|
+
cause: secretValues.length > 0 ? scrubValuesFromErrorChain(error, secretValues) : error,
|
|
1447
|
+
...unavailableStatus(error)
|
|
1448
|
+
}
|
|
1097
1449
|
);
|
|
1098
1450
|
}
|
|
1099
1451
|
}
|
|
@@ -1107,6 +1459,9 @@ exports.EmailService = class EmailService {
|
|
|
1107
1459
|
*/
|
|
1108
1460
|
async sendTemplate(input) {
|
|
1109
1461
|
assertIdentifies("EmailService", "tenantId", input.tenantId);
|
|
1462
|
+
if (this.options.email) {
|
|
1463
|
+
this.guardRecipientCount(input, this.options.email.maxRecipients);
|
|
1464
|
+
}
|
|
1110
1465
|
const requestedLocale = input.locale ?? this.options.global.defaultLocale;
|
|
1111
1466
|
const locale = await this.resolveTemplateLocale(input.template, requestedLocale);
|
|
1112
1467
|
const rendered = await this.renderTemplate(
|
|
@@ -1138,6 +1493,18 @@ exports.EmailService = class EmailService {
|
|
|
1138
1493
|
}
|
|
1139
1494
|
return this.options.email;
|
|
1140
1495
|
}
|
|
1496
|
+
/**
|
|
1497
|
+
* Throws `EMAIL_INVALID_RECIPIENT` when to, cc and bcc together address more mailboxes than
|
|
1498
|
+
* the channel allows. The refusal names the limit and never an address.
|
|
1499
|
+
*/
|
|
1500
|
+
guardRecipientCount(input, limit) {
|
|
1501
|
+
if (countRecipients(input.to) + countRecipients(input.cc) + countRecipients(input.bcc) > limit) {
|
|
1502
|
+
throw new NotificationException("EMAIL_INVALID_RECIPIENT", {
|
|
1503
|
+
reason: "too_many_recipients",
|
|
1504
|
+
limit
|
|
1505
|
+
});
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1141
1508
|
/** Throws `EMAIL_ATTACHMENTS_TOO_LARGE` when the attachments exceed the byte budget. */
|
|
1142
1509
|
guardAttachmentSize(attachments, maxBytes) {
|
|
1143
1510
|
if (!attachments) {
|
|
@@ -1286,10 +1653,11 @@ exports.EmailService = class EmailService {
|
|
|
1286
1653
|
...status
|
|
1287
1654
|
})
|
|
1288
1655
|
);
|
|
1289
|
-
throw new NotificationException(
|
|
1290
|
-
|
|
1291
|
-
...status
|
|
1292
|
-
|
|
1656
|
+
throw new NotificationException(
|
|
1657
|
+
"EMAIL_SEND_FAILED",
|
|
1658
|
+
{ providerName: this.provider.name, ...status },
|
|
1659
|
+
unavailableStatus(error)
|
|
1660
|
+
);
|
|
1293
1661
|
}
|
|
1294
1662
|
/**
|
|
1295
1663
|
* Assembles every value to scrub from a provider failure: the caller's
|
|
@@ -1300,16 +1668,12 @@ exports.EmailService = class EmailService {
|
|
|
1300
1668
|
* that with nothing declared and nothing echoed the list is verifiably
|
|
1301
1669
|
* empty and the raw error passes through untouched.
|
|
1302
1670
|
*/
|
|
1303
|
-
gatherRedactionValues(
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
if (declared) {
|
|
1310
|
-
values.push(...declared);
|
|
1311
|
-
}
|
|
1312
|
-
return values;
|
|
1671
|
+
gatherRedactionValues(parts, declared, sendOptions) {
|
|
1672
|
+
return [
|
|
1673
|
+
...collectEchoedExcerpts(parts, sendOptions.html),
|
|
1674
|
+
...sendOptions.text !== void 0 ? collectEchoedExcerpts(parts, sendOptions.text) : [],
|
|
1675
|
+
...declared ?? []
|
|
1676
|
+
];
|
|
1313
1677
|
}
|
|
1314
1678
|
};
|
|
1315
1679
|
exports.EmailService = __decorateClass([
|
|
@@ -1317,7 +1681,7 @@ exports.EmailService = __decorateClass([
|
|
|
1317
1681
|
__decorateParam(0, common.Inject(BYMAX_NOTIFICATION_OPTIONS)),
|
|
1318
1682
|
__decorateParam(1, common.Inject(BYMAX_NOTIFICATION_EMAIL_PROVIDER)),
|
|
1319
1683
|
__decorateParam(2, common.Inject(BYMAX_NOTIFICATION_TEMPLATE_RENDERER)),
|
|
1320
|
-
__decorateParam(3, common.Inject(
|
|
1684
|
+
__decorateParam(3, common.Inject(BYMAX_NOTIFICATION_AUDIT_SINK))
|
|
1321
1685
|
], exports.EmailService);
|
|
1322
1686
|
var NUMERIC = "0123456789";
|
|
1323
1687
|
var ALPHA = "ABCDEFGHJKLMNPQRSTUVWXYZ";
|
|
@@ -1381,11 +1745,79 @@ function formatCooldown(remainingSeconds) {
|
|
|
1381
1745
|
}
|
|
1382
1746
|
return parts.join(" ");
|
|
1383
1747
|
}
|
|
1384
|
-
|
|
1385
|
-
|
|
1748
|
+
var PLAIN_DOMAIN = /^[\p{L}\p{N}\p{M}_.-]+$/u;
|
|
1749
|
+
var ASCII_LABEL = new RegExp("^\\p{ASCII}*$", "u");
|
|
1750
|
+
function isLabelWiseMapping(folded, mapped) {
|
|
1751
|
+
const expected = folded.split(".").map((label) => ASCII_LABEL.test(label) ? label.toLowerCase() : null);
|
|
1752
|
+
const output = mapped.split(".");
|
|
1753
|
+
return expected.length === output.length && output.every((label, index) => {
|
|
1754
|
+
const want = expected.at(index);
|
|
1755
|
+
return want === null ? label.startsWith("xn--") : label === want;
|
|
1756
|
+
});
|
|
1757
|
+
}
|
|
1758
|
+
function normalizeDomain(domain) {
|
|
1759
|
+
const folded = domain.normalize("NFKC");
|
|
1760
|
+
if (!PLAIN_DOMAIN.test(folded)) {
|
|
1761
|
+
return domain.toLowerCase();
|
|
1762
|
+
}
|
|
1763
|
+
const mapped = url.domainToASCII(domain);
|
|
1764
|
+
return isLabelWiseMapping(folded, mapped) ? mapped : domain.toLowerCase();
|
|
1765
|
+
}
|
|
1386
1766
|
function normalizeRecipient(recipient) {
|
|
1387
1767
|
const trimmed = recipient.trim();
|
|
1388
|
-
|
|
1768
|
+
const at = trimmed.lastIndexOf("@");
|
|
1769
|
+
if (at === -1) {
|
|
1770
|
+
return trimmed;
|
|
1771
|
+
}
|
|
1772
|
+
return `${trimmed.slice(0, at).toLowerCase()}@${normalizeDomain(trimmed.slice(at + 1))}`;
|
|
1773
|
+
}
|
|
1774
|
+
|
|
1775
|
+
// src/server/utils/storage-failures.ts
|
|
1776
|
+
var OPERATIONS = [
|
|
1777
|
+
"set",
|
|
1778
|
+
"get",
|
|
1779
|
+
"consumeAttempt",
|
|
1780
|
+
"update",
|
|
1781
|
+
"delete",
|
|
1782
|
+
"deleteIfCode",
|
|
1783
|
+
"tryAcquireCooldown",
|
|
1784
|
+
"getCooldown",
|
|
1785
|
+
"clearCooldown",
|
|
1786
|
+
"getFailures",
|
|
1787
|
+
"recordFailure",
|
|
1788
|
+
"clearFailures"
|
|
1789
|
+
];
|
|
1790
|
+
function translate(storage, error) {
|
|
1791
|
+
if (error instanceof NotificationException || !isUnavailableError(error)) {
|
|
1792
|
+
return error;
|
|
1793
|
+
}
|
|
1794
|
+
return new NotificationException(
|
|
1795
|
+
"OTP_STORAGE_UNAVAILABLE",
|
|
1796
|
+
{ providerName: storage.name },
|
|
1797
|
+
{ cause: error }
|
|
1798
|
+
);
|
|
1799
|
+
}
|
|
1800
|
+
function withStorageFailures(storage) {
|
|
1801
|
+
const wrapped = {
|
|
1802
|
+
name: storage.name,
|
|
1803
|
+
isConfigured: () => storage.isConfigured()
|
|
1804
|
+
};
|
|
1805
|
+
for (const operation of OPERATIONS) {
|
|
1806
|
+
if (typeof Reflect.get(storage, operation) !== "function") {
|
|
1807
|
+
continue;
|
|
1808
|
+
}
|
|
1809
|
+
Object.defineProperty(wrapped, operation, {
|
|
1810
|
+
enumerable: true,
|
|
1811
|
+
value: async (...args) => {
|
|
1812
|
+
try {
|
|
1813
|
+
return await Reflect.get(storage, operation).apply(storage, args);
|
|
1814
|
+
} catch (error) {
|
|
1815
|
+
throw translate(storage, error);
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
});
|
|
1819
|
+
}
|
|
1820
|
+
return wrapped;
|
|
1389
1821
|
}
|
|
1390
1822
|
function safeCompare(expected, actual) {
|
|
1391
1823
|
const expectedBytes = Buffer.from(expected, "utf8");
|
|
@@ -1411,9 +1843,8 @@ exports.OtpService = class OtpService {
|
|
|
1411
1843
|
* @param auditLog - The audit-log repository (no-op when none configured).
|
|
1412
1844
|
* @param emailService - The email service; present only when the email channel is configured.
|
|
1413
1845
|
*/
|
|
1414
|
-
constructor(options,
|
|
1846
|
+
constructor(options, store, auditLog, emailService) {
|
|
1415
1847
|
this.options = options;
|
|
1416
|
-
this.storage = storage;
|
|
1417
1848
|
this.auditLog = auditLog;
|
|
1418
1849
|
this.emailService = emailService;
|
|
1419
1850
|
this.logger = new common.Logger(exports.OtpService.name);
|
|
@@ -1422,6 +1853,12 @@ exports.OtpService = class OtpService {
|
|
|
1422
1853
|
this.warnedTemplate = false;
|
|
1423
1854
|
/** @internal */
|
|
1424
1855
|
this.auditWarning = new AuditWriteWarning(this.logger, "otp");
|
|
1856
|
+
if (options.otp?.consumeOnVerify && store.deleteIfCode === void 0) {
|
|
1857
|
+
throw new Error(
|
|
1858
|
+
`[BymaxNotificationModule] otp.consumeOnVerify requires an IOtpStorage that implements deleteIfCode (the ${store.name} storage does not); implement it, or set consumeOnVerify to false`
|
|
1859
|
+
);
|
|
1860
|
+
}
|
|
1861
|
+
this.storage = withStorageFailures(store);
|
|
1425
1862
|
}
|
|
1426
1863
|
/**
|
|
1427
1864
|
* Whether the OTP channel is configured and its storage is ready.
|
|
@@ -1445,6 +1882,7 @@ exports.OtpService = class OtpService {
|
|
|
1445
1882
|
this.assertScope(input);
|
|
1446
1883
|
const scope = this.keyed(input);
|
|
1447
1884
|
this.assertDeliverable(input, otp.digestCode);
|
|
1885
|
+
this.assertMailbox(input);
|
|
1448
1886
|
const cfg = otp.resolveForPurpose(input.purpose);
|
|
1449
1887
|
await this.acquireCooldownOrThrow(scope, cfg.resendCooldownSeconds);
|
|
1450
1888
|
const code = generateOtpCode(cfg.length, cfg.codeType);
|
|
@@ -1475,25 +1913,17 @@ exports.OtpService = class OtpService {
|
|
|
1475
1913
|
const cfg = otp.resolveForPurpose(scope.purpose);
|
|
1476
1914
|
const attempt = await this.countAttempt(scope, cfg.ttlSeconds);
|
|
1477
1915
|
if (attempt === null) {
|
|
1478
|
-
|
|
1479
|
-
return { valid: false, reason: "not_found" };
|
|
1916
|
+
return this.rejectNotFound(scope);
|
|
1480
1917
|
}
|
|
1481
1918
|
if (attempt !== void 0 && attempt > cfg.maxAttempts) {
|
|
1482
|
-
|
|
1483
|
-
this.otpAuditEntry("max_attempts_exceeded", scope, { reason: "max_attempts" })
|
|
1484
|
-
);
|
|
1485
|
-
return { valid: false, reason: "max_attempts" };
|
|
1919
|
+
return this.rejectMaxAttempts(scope);
|
|
1486
1920
|
}
|
|
1487
1921
|
const result = await this.storage.consumeAttempt(scope.tenantId, scope.recipient, scope.purpose);
|
|
1488
1922
|
if (result.status === "not_found") {
|
|
1489
|
-
|
|
1490
|
-
return { valid: false, reason: "not_found" };
|
|
1923
|
+
return this.rejectNotFound(scope);
|
|
1491
1924
|
}
|
|
1492
1925
|
if (result.status === "max_attempts") {
|
|
1493
|
-
|
|
1494
|
-
this.otpAuditEntry("max_attempts_exceeded", scope, { reason: "max_attempts" })
|
|
1495
|
-
);
|
|
1496
|
-
return { valid: false, reason: "max_attempts" };
|
|
1926
|
+
return this.rejectMaxAttempts(scope);
|
|
1497
1927
|
}
|
|
1498
1928
|
const { entry } = result;
|
|
1499
1929
|
if (!this.matchesStoredCode(entry.code, scope.code, otp.digestCode)) {
|
|
@@ -1506,6 +1936,9 @@ exports.OtpService = class OtpService {
|
|
|
1506
1936
|
remainingAttempts: attempt === void 0 ? ofCode : Math.min(ofCode, cfg.maxAttempts - attempt)
|
|
1507
1937
|
};
|
|
1508
1938
|
}
|
|
1939
|
+
if (await this.lostConsume(scope, entry.code, otp.consumeOnVerify)) {
|
|
1940
|
+
return this.rejectNotFound(scope);
|
|
1941
|
+
}
|
|
1509
1942
|
await this.storage.clearFailures?.(scope.tenantId, scope.recipient, scope.purpose);
|
|
1510
1943
|
await this.finalizeVerifySuccess(scope, entry, otp.consumeOnVerify);
|
|
1511
1944
|
return { valid: true };
|
|
@@ -1677,7 +2110,7 @@ exports.OtpService = class OtpService {
|
|
|
1677
2110
|
);
|
|
1678
2111
|
} catch (error) {
|
|
1679
2112
|
this.logger.warn(
|
|
1680
|
-
`[${TEMPLATE_WARNING_CODE}] Could not check whether the email template '${DEFAULT_OTP_TEMPLATE}' resolves (${describeError(error)}); if it does not, the first generate() that delivers by email fails with TEMPLATE_NOT_FOUND.`
|
|
2113
|
+
`[${TEMPLATE_WARNING_CODE}] Could not check whether the email template '${DEFAULT_OTP_TEMPLATE}' resolves (${escapeAuditString(describeError(error))}); if it does not, the first generate() that delivers by email fails with TEMPLATE_NOT_FOUND.`
|
|
1681
2114
|
);
|
|
1682
2115
|
}
|
|
1683
2116
|
}
|
|
@@ -1716,6 +2149,18 @@ exports.OtpService = class OtpService {
|
|
|
1716
2149
|
});
|
|
1717
2150
|
}
|
|
1718
2151
|
}
|
|
2152
|
+
/**
|
|
2153
|
+
* Refuses, before any state exists, an email delivery to a string that is not exactly one
|
|
2154
|
+
* mailbox: the code goes to every address the string names. A manual delivery is the
|
|
2155
|
+
* caller's own, so a phone number or a device id stays a valid recipient.
|
|
2156
|
+
*
|
|
2157
|
+
* @throws NotificationException `EMAIL_INVALID_RECIPIENT`.
|
|
2158
|
+
*/
|
|
2159
|
+
assertMailbox(input) {
|
|
2160
|
+
if (this.deliveryOf(input) === "email") {
|
|
2161
|
+
assertSingleMailbox(input.recipient);
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
1719
2164
|
/** Delivers the code by email when requested; throws on failure (release is handled by the caller). */
|
|
1720
2165
|
async deliverOtp(input, code, cfg) {
|
|
1721
2166
|
if (this.deliveryOf(input) !== "email") {
|
|
@@ -1749,10 +2194,41 @@ exports.OtpService = class OtpService {
|
|
|
1749
2194
|
...input.userId !== void 0 ? { userId: input.userId } : {}
|
|
1750
2195
|
};
|
|
1751
2196
|
}
|
|
2197
|
+
/** Audits and returns the `not_found` verdict: no live code, or it was consumed by another call. */
|
|
2198
|
+
async rejectNotFound(scope) {
|
|
2199
|
+
await this.audit(this.otpAuditEntry("failed", scope, { reason: "not_found" }));
|
|
2200
|
+
return { valid: false, reason: "not_found" };
|
|
2201
|
+
}
|
|
2202
|
+
/** Audits and returns the `max_attempts` verdict. */
|
|
2203
|
+
async rejectMaxAttempts(scope) {
|
|
2204
|
+
await this.audit(this.otpAuditEntry("max_attempts_exceeded", scope, { reason: "max_attempts" }));
|
|
2205
|
+
return { valid: false, reason: "max_attempts" };
|
|
2206
|
+
}
|
|
2207
|
+
/**
|
|
2208
|
+
* With `consumeOnVerify`, removes the entry atomically while it still stores the value this
|
|
2209
|
+
* verification read, and reports whether another verification got there first. The one-time
|
|
2210
|
+
* property is decided here, not by a delete that follows: of N concurrent verifications of the
|
|
2211
|
+
* right code exactly one removes the entry. `storedCode` is the STORED value (the digest when
|
|
2212
|
+
* keyed), never the guess.
|
|
2213
|
+
*
|
|
2214
|
+
* @returns `true` when a concurrent verification consumed the code or it was regenerated.
|
|
2215
|
+
*/
|
|
2216
|
+
async lostConsume(scope, storedCode, consumeOnVerify) {
|
|
2217
|
+
const deleteIfCode = consumeOnVerify ? this.storage.deleteIfCode : void 0;
|
|
2218
|
+
if (!deleteIfCode) {
|
|
2219
|
+
return false;
|
|
2220
|
+
}
|
|
2221
|
+
return !await deleteIfCode.call(
|
|
2222
|
+
this.storage,
|
|
2223
|
+
scope.tenantId,
|
|
2224
|
+
scope.recipient,
|
|
2225
|
+
scope.purpose,
|
|
2226
|
+
storedCode
|
|
2227
|
+
);
|
|
2228
|
+
}
|
|
1752
2229
|
/** Finalizes a correct verification: consume-and-clear, or mark `validated`. */
|
|
1753
2230
|
async finalizeVerifySuccess(input, entry, consumeOnVerify) {
|
|
1754
2231
|
if (consumeOnVerify) {
|
|
1755
|
-
await this.storage.delete(input.tenantId, input.recipient, input.purpose);
|
|
1756
2232
|
await this.storage.clearCooldown(input.tenantId, input.recipient, input.purpose);
|
|
1757
2233
|
} else {
|
|
1758
2234
|
await this.storage.update(input.tenantId, input.recipient, input.purpose, {
|
|
@@ -1769,11 +2245,12 @@ exports.OtpService = class OtpService {
|
|
|
1769
2245
|
* consumer-supplied {@link IOtpStorage} is not required to, and a blank scope would
|
|
1770
2246
|
* then be shared by every caller that sent one.
|
|
1771
2247
|
*
|
|
1772
|
-
* @throws NotificationException `INVALID_SCOPE_IDENTIFIER` when either is blank.
|
|
2248
|
+
* @throws NotificationException `INVALID_SCOPE_IDENTIFIER` when either is blank or the purpose is not a plain name.
|
|
1773
2249
|
*/
|
|
1774
2250
|
assertScope(ref) {
|
|
1775
2251
|
assertIdentifies("OtpService", "tenantId", ref.tenantId);
|
|
1776
2252
|
assertIdentifies("OtpService", "recipient", ref.recipient);
|
|
2253
|
+
assertPurpose("OtpService", ref.purpose);
|
|
1777
2254
|
}
|
|
1778
2255
|
/**
|
|
1779
2256
|
* Returns the input with its recipient replaced by the value the OTP state is keyed on.
|
|
@@ -1836,7 +2313,7 @@ exports.OtpService = __decorateClass([
|
|
|
1836
2313
|
common.Injectable(),
|
|
1837
2314
|
__decorateParam(0, common.Inject(BYMAX_NOTIFICATION_OPTIONS)),
|
|
1838
2315
|
__decorateParam(1, common.Inject(BYMAX_NOTIFICATION_OTP_STORAGE)),
|
|
1839
|
-
__decorateParam(2, common.Inject(
|
|
2316
|
+
__decorateParam(2, common.Inject(BYMAX_NOTIFICATION_AUDIT_SINK)),
|
|
1840
2317
|
__decorateParam(3, common.Optional()),
|
|
1841
2318
|
__decorateParam(3, common.Inject(exports.EmailService))
|
|
1842
2319
|
], exports.OtpService);
|
|
@@ -2095,6 +2572,7 @@ exports.BymaxNotificationModule = class BymaxNotificationModule {
|
|
|
2095
2572
|
exports: [
|
|
2096
2573
|
BYMAX_NOTIFICATION_OPTIONS,
|
|
2097
2574
|
BYMAX_NOTIFICATION_LOG_REPOSITORY,
|
|
2575
|
+
BYMAX_NOTIFICATION_AUDIT_SINK,
|
|
2098
2576
|
BYMAX_NOTIFICATION_EMAIL_PROVIDER,
|
|
2099
2577
|
BYMAX_NOTIFICATION_TEMPLATE_RENDERER,
|
|
2100
2578
|
BYMAX_NOTIFICATION_OTP_STORAGE,
|
|
@@ -2121,7 +2599,7 @@ exports.BymaxNotificationModule = class BymaxNotificationModule {
|
|
|
2121
2599
|
BYMAX_NOTIFICATION_OPTIONS,
|
|
2122
2600
|
BYMAX_NOTIFICATION_EMAIL_PROVIDER,
|
|
2123
2601
|
BYMAX_NOTIFICATION_TEMPLATE_RENDERER,
|
|
2124
|
-
|
|
2602
|
+
BYMAX_NOTIFICATION_AUDIT_SINK
|
|
2125
2603
|
]
|
|
2126
2604
|
},
|
|
2127
2605
|
{
|
|
@@ -2130,7 +2608,7 @@ exports.BymaxNotificationModule = class BymaxNotificationModule {
|
|
|
2130
2608
|
inject: [
|
|
2131
2609
|
BYMAX_NOTIFICATION_OPTIONS,
|
|
2132
2610
|
BYMAX_NOTIFICATION_OTP_STORAGE,
|
|
2133
|
-
|
|
2611
|
+
BYMAX_NOTIFICATION_AUDIT_SINK,
|
|
2134
2612
|
// 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.
|
|
2135
2613
|
{ token: exports.EmailService, optional: true }
|
|
2136
2614
|
]
|
|
@@ -2161,6 +2639,7 @@ exports.BymaxNotificationModule = class BymaxNotificationModule {
|
|
|
2161
2639
|
useFactory: (raw) => raw.audit ? instantiate(raw.audit.repository) : new exports.NoOpNotificationLogRepository(),
|
|
2162
2640
|
inject: [RAW_NOTIFICATION_OPTIONS]
|
|
2163
2641
|
},
|
|
2642
|
+
auditSinkProvider(),
|
|
2164
2643
|
{
|
|
2165
2644
|
provide: BYMAX_NOTIFICATION_EMAIL_PROVIDER,
|
|
2166
2645
|
useFactory: (raw) => raw.email ? instantiate(raw.email.provider) : null,
|
|
@@ -2182,7 +2661,8 @@ exports.BymaxNotificationModule = class BymaxNotificationModule {
|
|
|
2182
2661
|
static buildProviders(options, resolved) {
|
|
2183
2662
|
const providers = [
|
|
2184
2663
|
{ provide: BYMAX_NOTIFICATION_OPTIONS, useValue: resolved },
|
|
2185
|
-
options.audit?.repository ? resolveAsProvider(BYMAX_NOTIFICATION_LOG_REPOSITORY, options.audit.repository) : { provide: BYMAX_NOTIFICATION_LOG_REPOSITORY, useClass: exports.NoOpNotificationLogRepository }
|
|
2664
|
+
options.audit?.repository ? resolveAsProvider(BYMAX_NOTIFICATION_LOG_REPOSITORY, options.audit.repository) : { provide: BYMAX_NOTIFICATION_LOG_REPOSITORY, useClass: exports.NoOpNotificationLogRepository },
|
|
2665
|
+
auditSinkProvider()
|
|
2186
2666
|
];
|
|
2187
2667
|
if (resolved.email && options.email) {
|
|
2188
2668
|
providers.push(resolveAsProvider(BYMAX_NOTIFICATION_EMAIL_PROVIDER, options.email.provider));
|
|
@@ -2224,6 +2704,13 @@ function activeChannels(resolved) {
|
|
|
2224
2704
|
}
|
|
2225
2705
|
return channels;
|
|
2226
2706
|
}
|
|
2707
|
+
function auditSinkProvider() {
|
|
2708
|
+
return {
|
|
2709
|
+
provide: BYMAX_NOTIFICATION_AUDIT_SINK,
|
|
2710
|
+
useFactory: (repository) => new EscapingLogRepository(repository),
|
|
2711
|
+
inject: [BYMAX_NOTIFICATION_LOG_REPOSITORY]
|
|
2712
|
+
};
|
|
2713
|
+
}
|
|
2227
2714
|
function resolveRenderer(renderer) {
|
|
2228
2715
|
if (renderer === void 0) {
|
|
2229
2716
|
return {
|
|
@@ -2408,15 +2895,23 @@ exports.NotificationAuditInterceptor = class NotificationAuditInterceptor {
|
|
|
2408
2895
|
}
|
|
2409
2896
|
return input.payload.recipient;
|
|
2410
2897
|
}
|
|
2411
|
-
/**
|
|
2898
|
+
/**
|
|
2899
|
+
* Extracts the audit `purpose`: the OTP purpose, or the email template name. The interceptor sees
|
|
2900
|
+
* the payload before the service refuses it and audits a refused call too, so an OTP purpose that
|
|
2901
|
+
* is not a plain name is left out of the entry: a control character in it would forge a log
|
|
2902
|
+
* record and its length is unbounded.
|
|
2903
|
+
*/
|
|
2412
2904
|
extractPurpose(input) {
|
|
2413
|
-
|
|
2905
|
+
if (input.channel !== "otp") {
|
|
2906
|
+
return input.payload.template;
|
|
2907
|
+
}
|
|
2908
|
+
return purposeProblem(input.payload.purpose) === void 0 ? input.payload.purpose : void 0;
|
|
2414
2909
|
}
|
|
2415
2910
|
};
|
|
2416
2911
|
exports.NotificationAuditInterceptor = __decorateClass([
|
|
2417
2912
|
common.Injectable(),
|
|
2418
2913
|
__decorateParam(0, common.Inject(BYMAX_NOTIFICATION_OPTIONS)),
|
|
2419
|
-
__decorateParam(1, common.Inject(
|
|
2914
|
+
__decorateParam(1, common.Inject(BYMAX_NOTIFICATION_AUDIT_SINK))
|
|
2420
2915
|
], exports.NotificationAuditInterceptor);
|
|
2421
2916
|
|
|
2422
2917
|
// src/server/constants/notification-purposes.ts
|
|
@@ -2497,6 +2992,31 @@ function readSdkMessage(error) {
|
|
|
2497
2992
|
return REDACTED_VALUE;
|
|
2498
2993
|
}
|
|
2499
2994
|
}
|
|
2995
|
+
function settleOrAbort(call, signal) {
|
|
2996
|
+
return new Promise((resolve, reject) => {
|
|
2997
|
+
const onAbort = () => {
|
|
2998
|
+
reject(signal.reason);
|
|
2999
|
+
};
|
|
3000
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
3001
|
+
call.then(resolve, reject).finally(() => {
|
|
3002
|
+
signal.removeEventListener("abort", onAbort);
|
|
3003
|
+
});
|
|
3004
|
+
});
|
|
3005
|
+
}
|
|
3006
|
+
function withCode(error, code) {
|
|
3007
|
+
return code === void 0 ? error : Object.assign(error, { code });
|
|
3008
|
+
}
|
|
3009
|
+
function unavailableCodeOf(error) {
|
|
3010
|
+
try {
|
|
3011
|
+
const status = error.statusCode;
|
|
3012
|
+
const requestNotMade = error.name === "application_error" && status === null;
|
|
3013
|
+
return requestNotMade || typeof status === "number" && status >= 500 ? "EUNAVAILABLE" : void 0;
|
|
3014
|
+
} catch {
|
|
3015
|
+
return void 0;
|
|
3016
|
+
}
|
|
3017
|
+
}
|
|
3018
|
+
var DEFAULT_TIMEOUT_MS = 15e3;
|
|
3019
|
+
var MAX_TIMEOUT_MS = 2147483647;
|
|
2500
3020
|
var RESEND_MODULE = "resend";
|
|
2501
3021
|
var _clientPromise, _options;
|
|
2502
3022
|
exports.ResendEmailProvider = class ResendEmailProvider {
|
|
@@ -2524,6 +3044,12 @@ exports.ResendEmailProvider = class ResendEmailProvider {
|
|
|
2524
3044
|
* reporter capturing the scope of a throw — would emit the key in plaintext.
|
|
2525
3045
|
*/
|
|
2526
3046
|
__privateAdd(this, _options);
|
|
3047
|
+
const timeout = options.timeoutMs;
|
|
3048
|
+
if (timeout !== void 0 && !(Number.isInteger(timeout) && timeout >= 1 && timeout <= MAX_TIMEOUT_MS)) {
|
|
3049
|
+
throw new Error(
|
|
3050
|
+
`ResendEmailProvider: timeoutMs must be a positive integer of at most ${String(MAX_TIMEOUT_MS)}`
|
|
3051
|
+
);
|
|
3052
|
+
}
|
|
2527
3053
|
__privateSet(this, _options, options);
|
|
2528
3054
|
}
|
|
2529
3055
|
/**
|
|
@@ -2546,26 +3072,35 @@ exports.ResendEmailProvider = class ResendEmailProvider {
|
|
|
2546
3072
|
async send(options) {
|
|
2547
3073
|
const client = await this.getClient();
|
|
2548
3074
|
const from2 = this.formatFrom(options.from, options.fromName);
|
|
3075
|
+
const timeoutMs = __privateGet(this, _options).timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
3076
|
+
const signal = AbortSignal.timeout(timeoutMs);
|
|
2549
3077
|
let result;
|
|
2550
3078
|
try {
|
|
2551
|
-
result = await
|
|
2552
|
-
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
|
|
2556
|
-
|
|
2557
|
-
|
|
2558
|
-
|
|
2559
|
-
|
|
2560
|
-
|
|
2561
|
-
|
|
2562
|
-
|
|
2563
|
-
|
|
3079
|
+
result = await settleOrAbort(
|
|
3080
|
+
client.emails.send(
|
|
3081
|
+
{
|
|
3082
|
+
from: from2,
|
|
3083
|
+
to: options.to,
|
|
3084
|
+
subject: options.subject,
|
|
3085
|
+
html: options.html,
|
|
3086
|
+
text: options.text,
|
|
3087
|
+
replyTo: options.replyTo,
|
|
3088
|
+
cc: options.cc,
|
|
3089
|
+
bcc: options.bcc,
|
|
3090
|
+
tags: options.tags,
|
|
3091
|
+
headers: options.headers,
|
|
3092
|
+
attachments: options.attachments
|
|
3093
|
+
},
|
|
3094
|
+
{ signal }
|
|
3095
|
+
),
|
|
3096
|
+
signal
|
|
3097
|
+
);
|
|
2564
3098
|
} catch (error) {
|
|
2565
|
-
|
|
3099
|
+
const reason = signal.aborted ? `Resend request timed out after ${String(timeoutMs)} ms` : readRedactedMessage(error);
|
|
3100
|
+
throw this.sendFailure(reason, options, signal.aborted ? "ETIMEDOUT" : errorCodeOf(error));
|
|
2566
3101
|
}
|
|
2567
3102
|
if (result.error) {
|
|
2568
|
-
throw this.sendFailure(readSdkMessage(result.error), options);
|
|
3103
|
+
throw this.sendFailure(readSdkMessage(result.error), options, unavailableCodeOf(result.error));
|
|
2569
3104
|
}
|
|
2570
3105
|
if (!result.data?.id) {
|
|
2571
3106
|
throw new Error("Resend returned no message ID");
|
|
@@ -2581,14 +3116,14 @@ exports.ResendEmailProvider = class ResendEmailProvider {
|
|
|
2581
3116
|
* @param options - The send input whose body and declared values to scrub.
|
|
2582
3117
|
* @returns The `Error` for the caller to throw.
|
|
2583
3118
|
*/
|
|
2584
|
-
sendFailure(rawMessage, options) {
|
|
3119
|
+
sendFailure(rawMessage, options, code) {
|
|
2585
3120
|
if (options.publishProviderText === false) {
|
|
2586
3121
|
this.logger.warn("[RESEND_SEND_FAILED] (provider text withheld)");
|
|
2587
|
-
return new Error("Resend send failed");
|
|
3122
|
+
return withCode(new Error("Resend send failed"), code);
|
|
2588
3123
|
}
|
|
2589
3124
|
const reason = this.scrubSendError(rawMessage, options);
|
|
2590
|
-
this.logger.warn(`[RESEND_SEND_FAILED] ${reason}`);
|
|
2591
|
-
return new Error(`Resend send failed: ${reason}`);
|
|
3125
|
+
this.logger.warn(`[RESEND_SEND_FAILED] ${escapeAuditString(reason)}`);
|
|
3126
|
+
return withCode(new Error(`Resend send failed: ${reason}`), code);
|
|
2592
3127
|
}
|
|
2593
3128
|
/**
|
|
2594
3129
|
* Removes the API key, the caller's declared secrets, and any echoed body
|
|
@@ -2681,6 +3216,22 @@ var IMPLICIT_TLS_PORT = 465;
|
|
|
2681
3216
|
var DEFAULT_CONNECTION_TIMEOUT_MS = 1e4;
|
|
2682
3217
|
var DEFAULT_GREETING_TIMEOUT_MS = 1e4;
|
|
2683
3218
|
var DEFAULT_SOCKET_TIMEOUT_MS = 2e4;
|
|
3219
|
+
var DEFAULT_SEND_TIMEOUT_MS = 6e4;
|
|
3220
|
+
var MAX_SEND_TIMEOUT_MS = 2147483647;
|
|
3221
|
+
function settleOrTimeout(call, timeoutMs) {
|
|
3222
|
+
return new Promise((resolve, reject) => {
|
|
3223
|
+
const timer = setTimeout(() => {
|
|
3224
|
+
reject(
|
|
3225
|
+
Object.assign(new Error(`SMTP send timed out after ${String(timeoutMs)} ms`), {
|
|
3226
|
+
code: "ETIMEDOUT"
|
|
3227
|
+
})
|
|
3228
|
+
);
|
|
3229
|
+
}, timeoutMs);
|
|
3230
|
+
call.then(resolve, reject).finally(() => {
|
|
3231
|
+
clearTimeout(timer);
|
|
3232
|
+
});
|
|
3233
|
+
});
|
|
3234
|
+
}
|
|
2684
3235
|
var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
|
|
2685
3236
|
function areCredentialsComplete(credentials) {
|
|
2686
3237
|
return Boolean(credentials.user) && Boolean(credentials.pass);
|
|
@@ -2691,6 +3242,7 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
|
|
|
2691
3242
|
/**
|
|
2692
3243
|
* @param options - Adapter options; `host` is required to actually send, and
|
|
2693
3244
|
* `credentials` must be complete whenever supplied at all.
|
|
3245
|
+
* @throws Error When `sendTimeoutMs` is not an integer from `1` to `2147483647`.
|
|
2694
3246
|
*/
|
|
2695
3247
|
constructor(options = {}) {
|
|
2696
3248
|
this.name = "smtp";
|
|
@@ -2713,6 +3265,12 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
|
|
|
2713
3265
|
* would emit the password in plaintext.
|
|
2714
3266
|
*/
|
|
2715
3267
|
__privateAdd(this, _options2);
|
|
3268
|
+
const timeout = options.sendTimeoutMs;
|
|
3269
|
+
if (timeout !== void 0 && !(Number.isInteger(timeout) && timeout >= 1 && timeout <= MAX_SEND_TIMEOUT_MS)) {
|
|
3270
|
+
throw new Error(
|
|
3271
|
+
`SmtpEmailProvider: sendTimeoutMs must be a positive integer of at most ${String(MAX_SEND_TIMEOUT_MS)}`
|
|
3272
|
+
);
|
|
3273
|
+
}
|
|
2716
3274
|
__privateSet(this, _options2, options);
|
|
2717
3275
|
}
|
|
2718
3276
|
/**
|
|
@@ -2787,25 +3345,47 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
|
|
|
2787
3345
|
*/
|
|
2788
3346
|
async dispatch(transport, payload, redactValuesList, publishProviderText) {
|
|
2789
3347
|
try {
|
|
2790
|
-
return await
|
|
3348
|
+
return await settleOrTimeout(
|
|
3349
|
+
transport.sendMail(payload),
|
|
3350
|
+
__privateGet(this, _options2).sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS
|
|
3351
|
+
);
|
|
2791
3352
|
} catch (error) {
|
|
2792
|
-
|
|
2793
|
-
|
|
2794
|
-
|
|
2795
|
-
|
|
2796
|
-
|
|
2797
|
-
|
|
2798
|
-
|
|
2799
|
-
|
|
2800
|
-
|
|
2801
|
-
...status !== void 0 ? { deliveryStatus: status } : {},
|
|
2802
|
-
...enhanced !== void 0 ? { deliveryEnhancedStatus: enhanced } : {}
|
|
2803
|
-
});
|
|
2804
|
-
}
|
|
2805
|
-
const reason = this.scrubTransportError(raw, payload, redactValuesList);
|
|
2806
|
-
this.logger.warn(`[SMTP_SEND_FAILED] ${reason}`);
|
|
2807
|
-
throw new Error(`SMTP send failed: ${reason}`);
|
|
3353
|
+
throw this.failure(error, payload, redactValuesList, publishProviderText);
|
|
3354
|
+
}
|
|
3355
|
+
}
|
|
3356
|
+
/** Builds the error this adapter throws for a transport failure, logging the scrubbed reason. */
|
|
3357
|
+
failure(error, payload, redactValuesList, publishProviderText) {
|
|
3358
|
+
const raw = readRedactedMessage(error);
|
|
3359
|
+
const code = errorCodeOf(error);
|
|
3360
|
+
if (publishProviderText === false) {
|
|
3361
|
+
return this.withheldFailure(raw, code, redactValuesList);
|
|
2808
3362
|
}
|
|
3363
|
+
const reason = this.scrubTransportError(raw, payload, redactValuesList);
|
|
3364
|
+
this.logger.warn(`[SMTP_SEND_FAILED] ${escapeAuditString(reason)}`);
|
|
3365
|
+
return Object.assign(
|
|
3366
|
+
new Error(`SMTP send failed: ${reason}`),
|
|
3367
|
+
code === void 0 ? {} : { code }
|
|
3368
|
+
);
|
|
3369
|
+
}
|
|
3370
|
+
/**
|
|
3371
|
+
* The failure of a send whose body carries a credential: none of the relay's own words may reach a
|
|
3372
|
+
* log line or a thrown message — redaction removes the shapes it predicts and a re-encoded echo
|
|
3373
|
+
* defeats it. Only the reply codes a fixed grammar can express are published, and they are the
|
|
3374
|
+
* same whatever the body held.
|
|
3375
|
+
*
|
|
3376
|
+
* Filtered HERE, not only in EmailService: this adapter is public, and its own warn line would
|
|
3377
|
+
* otherwise write a code that contains the caller's declared secret — an OTP of `55` sits inside a
|
|
3378
|
+
* `550` reply.
|
|
3379
|
+
*/
|
|
3380
|
+
withheldFailure(raw, code, redactValuesList) {
|
|
3381
|
+
const { status, enhanced } = withoutDeclaredValues(extractDeliveryStatus(raw), redactValuesList);
|
|
3382
|
+
const codes = [status, enhanced].filter((reply) => reply !== void 0).join(" ");
|
|
3383
|
+
this.logger.warn(`[SMTP_SEND_FAILED] ${codes || "no reply code"}`);
|
|
3384
|
+
return Object.assign(new Error("SMTP send failed"), {
|
|
3385
|
+
...status !== void 0 ? { deliveryStatus: status } : {},
|
|
3386
|
+
...enhanced !== void 0 ? { deliveryEnhancedStatus: enhanced } : {},
|
|
3387
|
+
...code !== void 0 ? { code } : {}
|
|
3388
|
+
});
|
|
2809
3389
|
}
|
|
2810
3390
|
/**
|
|
2811
3391
|
* Removes the credentials, the caller's declared secrets and any echoed body
|
|
@@ -2834,12 +3414,23 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
|
|
|
2834
3414
|
values.push(...this.credentialValues());
|
|
2835
3415
|
return redactValues(message, values);
|
|
2836
3416
|
}
|
|
2837
|
-
/**
|
|
3417
|
+
/**
|
|
3418
|
+
* The configured credentials that qualify as secret material, if any, and the base64 forms the
|
|
3419
|
+
* AUTH exchange carries them in: the user and the password as AUTH LOGIN sends them, and the
|
|
3420
|
+
* AUTH PLAIN token, which has an empty authorization identity. A relay that quotes the exchange
|
|
3421
|
+
* shows those, and a literal match cannot see them. The token is its own value: base64 groups
|
|
3422
|
+
* three bytes, so the token's bytes usually sit at another alignment than the user's or the
|
|
3423
|
+
* password's, and then neither of their encodings appears inside it. It cannot be derived from
|
|
3424
|
+
* them.
|
|
3425
|
+
*/
|
|
2838
3426
|
credentialValues() {
|
|
2839
|
-
const
|
|
2840
|
-
|
|
2841
|
-
|
|
3427
|
+
const { user, pass } = __privateGet(this, _options2).credentials ?? {};
|
|
3428
|
+
const secrets = [user, pass].filter((secret) => Boolean(secret));
|
|
3429
|
+
const plainToken = `\0${secrets.join("\0")}`;
|
|
3430
|
+
const encoded = (secrets.length === 2 ? [...secrets, plainToken] : secrets).map(
|
|
3431
|
+
(value) => Buffer.from(value, "utf-8").toString("base64")
|
|
2842
3432
|
);
|
|
3433
|
+
return [...secrets, ...encoded];
|
|
2843
3434
|
}
|
|
2844
3435
|
/**
|
|
2845
3436
|
* Replaces every occurrence of either configured credential with a placeholder.
|
|
@@ -3236,6 +3827,25 @@ exports.InMemoryOtpStorage = class InMemoryOtpStorage {
|
|
|
3236
3827
|
async delete(tenantId, recipient, purpose) {
|
|
3237
3828
|
this.store.delete(this.key(tenantId, recipient, purpose));
|
|
3238
3829
|
}
|
|
3830
|
+
/**
|
|
3831
|
+
* Deletes the entry only when it still stores `expectedStored`. Synchronous inside the
|
|
3832
|
+
* method, so of N concurrent callers exactly one sees the value and removes it.
|
|
3833
|
+
*
|
|
3834
|
+
* @param tenantId - Tenant isolation scope.
|
|
3835
|
+
* @param recipient - Pre-normalized recipient identifier.
|
|
3836
|
+
* @param purpose - OTP purpose.
|
|
3837
|
+
* @param expectedStored - The stored code value the caller read.
|
|
3838
|
+
* @returns `true` when this call removed the entry.
|
|
3839
|
+
*/
|
|
3840
|
+
async deleteIfCode(tenantId, recipient, purpose, expectedStored) {
|
|
3841
|
+
const key = this.key(tenantId, recipient, purpose);
|
|
3842
|
+
const entry = this.store.get(key);
|
|
3843
|
+
if (!entry || entry.expiresAt < Date.now() || entry.code !== expectedStored) {
|
|
3844
|
+
return false;
|
|
3845
|
+
}
|
|
3846
|
+
this.store.delete(key);
|
|
3847
|
+
return true;
|
|
3848
|
+
}
|
|
3239
3849
|
/**
|
|
3240
3850
|
* Acquires the cooldown lock only when one is not already active.
|
|
3241
3851
|
*
|
|
@@ -3286,7 +3896,7 @@ exports.InMemoryOtpStorage = class InMemoryOtpStorage {
|
|
|
3286
3896
|
this.cooldowns.delete(this.key(tenantId, recipient, purpose));
|
|
3287
3897
|
}
|
|
3288
3898
|
/**
|
|
3289
|
-
* Test helper — wipes all entries and
|
|
3899
|
+
* Test helper — wipes all entries, cooldowns and failure counters. Not part of `IOtpStorage`.
|
|
3290
3900
|
*/
|
|
3291
3901
|
clear() {
|
|
3292
3902
|
this.store.clear();
|
|
@@ -3294,12 +3904,17 @@ exports.InMemoryOtpStorage = class InMemoryOtpStorage {
|
|
|
3294
3904
|
this.failures.clear();
|
|
3295
3905
|
}
|
|
3296
3906
|
/**
|
|
3297
|
-
* Test helper — current map sizes. Not part of `IOtpStorage`.
|
|
3907
|
+
* Test helper — current map sizes. Not part of `IOtpStorage`. Like the cooldowns, a failure
|
|
3908
|
+
* counter that has lapsed stays counted until it is read or cleared.
|
|
3298
3909
|
*
|
|
3299
|
-
* @returns The number of stored OTP entries and
|
|
3910
|
+
* @returns The number of stored OTP entries, cooldowns and failure counters.
|
|
3300
3911
|
*/
|
|
3301
3912
|
size() {
|
|
3302
|
-
return {
|
|
3913
|
+
return {
|
|
3914
|
+
otps: this.store.size,
|
|
3915
|
+
cooldowns: this.cooldowns.size,
|
|
3916
|
+
failures: this.failures.size
|
|
3917
|
+
};
|
|
3303
3918
|
}
|
|
3304
3919
|
/** The unexpired failure count for a key, dropping a lapsed counter. Synchronous. */
|
|
3305
3920
|
liveFailures(key) {
|
|
@@ -3323,6 +3938,7 @@ exports.InMemoryOtpStorage = class InMemoryOtpStorage {
|
|
|
3323
3938
|
* stays unambiguous too.
|
|
3324
3939
|
*/
|
|
3325
3940
|
key(tenantId, recipient, purpose) {
|
|
3941
|
+
assertPurpose("InMemoryOtpStorage", purpose);
|
|
3326
3942
|
return `${hashTenantRecipient(tenantId, recipient)}::${purpose}`;
|
|
3327
3943
|
}
|
|
3328
3944
|
};
|
|
@@ -3437,6 +4053,24 @@ exports.RedisOtpStorage = class RedisOtpStorage {
|
|
|
3437
4053
|
async delete(tenantId, recipient, purpose) {
|
|
3438
4054
|
await __privateGet(this, _redis).del(this.otpKey(tenantId, recipient, purpose));
|
|
3439
4055
|
}
|
|
4056
|
+
/**
|
|
4057
|
+
* Deletes the entry only when it still stores `expectedStored`, in one script.
|
|
4058
|
+
*
|
|
4059
|
+
* @param tenantId - Tenant isolation scope.
|
|
4060
|
+
* @param recipient - Pre-normalized recipient identifier.
|
|
4061
|
+
* @param purpose - OTP purpose.
|
|
4062
|
+
* @param expectedStored - The stored code value the caller read (the digest, when keyed).
|
|
4063
|
+
* @returns `true` when this call removed the entry.
|
|
4064
|
+
*/
|
|
4065
|
+
async deleteIfCode(tenantId, recipient, purpose, expectedStored) {
|
|
4066
|
+
const removed = await __privateGet(this, _redis).eval(
|
|
4067
|
+
exports.RedisOtpStorage.DELETE_IF_CODE_LUA,
|
|
4068
|
+
1,
|
|
4069
|
+
this.otpKey(tenantId, recipient, purpose),
|
|
4070
|
+
expectedStored
|
|
4071
|
+
);
|
|
4072
|
+
return Number(removed) === 1;
|
|
4073
|
+
}
|
|
3440
4074
|
/**
|
|
3441
4075
|
* Atomic cooldown acquire with `SET … NX EX` — only the first concurrent caller wins.
|
|
3442
4076
|
*
|
|
@@ -3524,14 +4158,17 @@ exports.RedisOtpStorage = class RedisOtpStorage {
|
|
|
3524
4158
|
}
|
|
3525
4159
|
/** Builds the OTP entry key: `{namespace}:otp:{purpose}:{hashTenantRecipient(...)}`. */
|
|
3526
4160
|
otpKey(tenantId, recipient, purpose) {
|
|
4161
|
+
assertPurpose("RedisOtpStorage", purpose);
|
|
3527
4162
|
return `${this.namespace}:otp:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
|
|
3528
4163
|
}
|
|
3529
4164
|
/** Builds the failure-counter key: `{namespace}:otp_fail:{purpose}:{hashTenantRecipient(...)}`. */
|
|
3530
4165
|
failureKey(tenantId, recipient, purpose) {
|
|
4166
|
+
assertPurpose("RedisOtpStorage", purpose);
|
|
3531
4167
|
return `${this.namespace}:otp_fail:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
|
|
3532
4168
|
}
|
|
3533
4169
|
/** Builds the cooldown key: `{namespace}:otp_cd:{purpose}:{hashTenantRecipient(...)}`. */
|
|
3534
4170
|
cooldownKey(tenantId, recipient, purpose) {
|
|
4171
|
+
assertPurpose("RedisOtpStorage", purpose);
|
|
3535
4172
|
return `${this.namespace}:otp_cd:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
|
|
3536
4173
|
}
|
|
3537
4174
|
};
|
|
@@ -3563,6 +4200,18 @@ exports.RedisOtpStorage.CONSUME_ATTEMPT_LUA = `
|
|
|
3563
4200
|
end
|
|
3564
4201
|
return cjson.encode({ status = 'ok', entry = entry })
|
|
3565
4202
|
`;
|
|
4203
|
+
/**
|
|
4204
|
+
* Atomic compare-and-delete: reads the entry, and deletes it only when its stored `code` equals
|
|
4205
|
+
* the value the caller read, so of N concurrent verifications exactly one removes it.
|
|
4206
|
+
*/
|
|
4207
|
+
exports.RedisOtpStorage.DELETE_IF_CODE_LUA = `
|
|
4208
|
+
local raw = redis.call('GET', KEYS[1])
|
|
4209
|
+
if not raw then return 0 end
|
|
4210
|
+
local entry = cjson.decode(raw)
|
|
4211
|
+
if entry.code ~= ARGV[1] then return 0 end
|
|
4212
|
+
redis.call('DEL', KEYS[1])
|
|
4213
|
+
return 1
|
|
4214
|
+
`;
|
|
3566
4215
|
/**
|
|
3567
4216
|
* Atomic failure-counter primitive: one `INCR` and the lifetime refresh in a single script, so
|
|
3568
4217
|
* concurrent failures each receive a distinct count and the counter never outlives its window
|