@web-ts-toolkit/email-service 0.0.0-stage → 0.72.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +446 -2
- package/index.d.mts +206 -0
- package/index.d.ts +206 -0
- package/index.js +4289 -0
- package/index.mjs +4244 -0
- package/mongoose.d.mts +24 -0
- package/mongoose.d.ts +24 -0
- package/mongoose.js +3045 -0
- package/mongoose.mjs +3020 -0
- package/package.json +89 -4
- package/provider-HisBc6hk.d.mts +183 -0
- package/provider-HisBc6hk.d.ts +183 -0
- package/sendgrid.d.mts +18 -0
- package/sendgrid.d.ts +18 -0
- package/sendgrid.js +1437 -0
- package/sendgrid.mjs +1410 -0
- package/smtp.d.mts +28 -0
- package/smtp.d.ts +28 -0
- package/smtp.js +1449 -0
- package/smtp.mjs +1412 -0
- package/store-D4YAI6Rk.d.mts +346 -0
- package/store-Vb63Gocz.d.ts +346 -0
package/smtp.js
ADDED
|
@@ -0,0 +1,1449 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/smtp.ts
|
|
31
|
+
var smtp_exports = {};
|
|
32
|
+
__export(smtp_exports, {
|
|
33
|
+
createSmtpProvider: () => createSmtpProvider
|
|
34
|
+
});
|
|
35
|
+
module.exports = __toCommonJS(smtp_exports);
|
|
36
|
+
|
|
37
|
+
// src/constants.ts
|
|
38
|
+
var KiB = 1024;
|
|
39
|
+
var MiB = 1024 * KiB;
|
|
40
|
+
var DAY_MS = 864e5;
|
|
41
|
+
function bounded(defaultValue, min, max) {
|
|
42
|
+
return Object.freeze({ default: defaultValue, min, max });
|
|
43
|
+
}
|
|
44
|
+
var EMAIL_FORMAT_VERSION = 1;
|
|
45
|
+
var MAX_UNIX_MS = 253402300799999;
|
|
46
|
+
var CLOCK_MARGIN_MS = 1e3;
|
|
47
|
+
var MAX_EXPIRY_MS = 30 * DAY_MS;
|
|
48
|
+
var MESSAGE_LIMITS = Object.freeze({
|
|
49
|
+
scopeBytes: 64,
|
|
50
|
+
identifierBytes: 128,
|
|
51
|
+
jsonDepth: 12,
|
|
52
|
+
jsonValues: 2048,
|
|
53
|
+
jsonKeyBytes: 128,
|
|
54
|
+
intentBytes: 16 * KiB,
|
|
55
|
+
dataBytes: 64 * KiB,
|
|
56
|
+
snapshotBytes: MiB,
|
|
57
|
+
recipients: 50,
|
|
58
|
+
addressBytes: 254,
|
|
59
|
+
localPartBytes: 64,
|
|
60
|
+
displayNameBytes: 128,
|
|
61
|
+
subjectBytes: 512,
|
|
62
|
+
templateSourceBytes: 256 * KiB,
|
|
63
|
+
htmlBytes: 512 * KiB,
|
|
64
|
+
textBytes: 256 * KiB,
|
|
65
|
+
correlationEntries: 8,
|
|
66
|
+
correlationKeyBytes: 32,
|
|
67
|
+
correlationValueBytes: 96,
|
|
68
|
+
attachments: 5,
|
|
69
|
+
filenameBytes: 128,
|
|
70
|
+
contentTypeBytes: 127,
|
|
71
|
+
attachmentBytes: 2 * MiB,
|
|
72
|
+
totalAttachmentBytes: 5 * MiB
|
|
73
|
+
});
|
|
74
|
+
var PRIORITY = bounded(0, 0, 9);
|
|
75
|
+
var TEMPLATE_CACHE_ENTRIES = bounded(32, 0, 128);
|
|
76
|
+
var TEMPLATE_MAX_PENDING = bounded(8, 1, 32);
|
|
77
|
+
var CALL_BUDGETS = Object.freeze({
|
|
78
|
+
prepare: bounded(5e3, 50, 3e4),
|
|
79
|
+
admissionOrAdmin: bounded(1e4, 50, 6e4),
|
|
80
|
+
batchOrRun: bounded(3e4, 50, 12e4),
|
|
81
|
+
shutdown: bounded(15e3, 50, 6e4)
|
|
82
|
+
});
|
|
83
|
+
var DEFAULT_RETRY_POLICY = Object.freeze({
|
|
84
|
+
maxAttempts: 3,
|
|
85
|
+
baseDelayMs: 1e3,
|
|
86
|
+
maxDelayMs: 6e4
|
|
87
|
+
});
|
|
88
|
+
var RETRY_POLICY_BOUNDS = Object.freeze({
|
|
89
|
+
maxAttempts: bounded(DEFAULT_RETRY_POLICY.maxAttempts, 1, 10),
|
|
90
|
+
baseDelayMs: bounded(DEFAULT_RETRY_POLICY.baseDelayMs, 100, 6e4),
|
|
91
|
+
// Also require maxDelayMs >= the configured baseDelayMs.
|
|
92
|
+
maxDelayMs: bounded(DEFAULT_RETRY_POLICY.maxDelayMs, 100, 36e5)
|
|
93
|
+
});
|
|
94
|
+
var MAX_MANUAL_ATTEMPTS = 1;
|
|
95
|
+
var MAX_ATTEMPT_LEDGER = RETRY_POLICY_BOUNDS.maxAttempts.max + MAX_MANUAL_ATTEMPTS;
|
|
96
|
+
var MAX_RATE_DEFERRAL_MS = 30 * DAY_MS;
|
|
97
|
+
var DEFAULT_RETENTION_POLICY = Object.freeze({
|
|
98
|
+
payloadMs: 7 * DAY_MS,
|
|
99
|
+
historyMs: 30 * DAY_MS,
|
|
100
|
+
idempotencyMs: 30 * DAY_MS
|
|
101
|
+
});
|
|
102
|
+
var RETENTION_POLICY_BOUNDS = Object.freeze({
|
|
103
|
+
payloadMs: bounded(DEFAULT_RETENTION_POLICY.payloadMs, 0, 30 * DAY_MS),
|
|
104
|
+
historyMs: bounded(DEFAULT_RETENTION_POLICY.historyMs, DAY_MS, 90 * DAY_MS),
|
|
105
|
+
idempotencyMs: bounded(DEFAULT_RETENTION_POLICY.idempotencyMs, DAY_MS, 90 * DAY_MS)
|
|
106
|
+
});
|
|
107
|
+
var DEFAULT_WORKER_LIMITS = Object.freeze({
|
|
108
|
+
maxConcurrency: 4,
|
|
109
|
+
storeTimeoutMs: 5e3,
|
|
110
|
+
leaseMs: 6e4,
|
|
111
|
+
preHandoffTimeoutMs: 8e3,
|
|
112
|
+
attachmentTimeoutMs: 5e3,
|
|
113
|
+
rateTimeoutMs: 500,
|
|
114
|
+
providerTimeoutMs: 15e3,
|
|
115
|
+
finalizeGraceMs: 1e4
|
|
116
|
+
});
|
|
117
|
+
var WORKER_LIMIT_BOUNDS = Object.freeze({
|
|
118
|
+
maxConcurrency: bounded(DEFAULT_WORKER_LIMITS.maxConcurrency, 1, 16),
|
|
119
|
+
storeTimeoutMs: bounded(DEFAULT_WORKER_LIMITS.storeTimeoutMs, 50, 3e4),
|
|
120
|
+
leaseMs: bounded(DEFAULT_WORKER_LIMITS.leaseMs, 5e3, 3e5),
|
|
121
|
+
preHandoffTimeoutMs: bounded(DEFAULT_WORKER_LIMITS.preHandoffTimeoutMs, 50, 6e4),
|
|
122
|
+
attachmentTimeoutMs: bounded(DEFAULT_WORKER_LIMITS.attachmentTimeoutMs, 50, 3e4),
|
|
123
|
+
rateTimeoutMs: bounded(DEFAULT_WORKER_LIMITS.rateTimeoutMs, 10, 5e3),
|
|
124
|
+
providerTimeoutMs: bounded(DEFAULT_WORKER_LIMITS.providerTimeoutMs, 50, 6e4),
|
|
125
|
+
finalizeGraceMs: bounded(DEFAULT_WORKER_LIMITS.finalizeGraceMs, 100, 3e4)
|
|
126
|
+
});
|
|
127
|
+
var RUN_CLAIM_LIMIT = bounded(20, 1, 100);
|
|
128
|
+
var RUN_MAINTENANCE_LIMIT = bounded(10, 0, 100);
|
|
129
|
+
var ACTIVITY_PAGE_LIMIT = bounded(25, 1, 100);
|
|
130
|
+
var ADMIN_MAINTENANCE_LIMIT = bounded(20, 1, 100);
|
|
131
|
+
var PROJECTION_DRAIN_MS = WORKER_LIMIT_BOUNDS.storeTimeoutMs.max + CLOCK_MARGIN_MS;
|
|
132
|
+
var MEMORY_MAX_JOBS = bounded(256, 1, 4096);
|
|
133
|
+
var MONGOOSE_DEFAULT_NAMES = Object.freeze({
|
|
134
|
+
jobsCollection: "email_jobs",
|
|
135
|
+
activitiesCollection: "email_activities",
|
|
136
|
+
jobsModelName: "EmailJobV1",
|
|
137
|
+
activitiesModelName: "EmailActivityV1"
|
|
138
|
+
});
|
|
139
|
+
var SMTP_DEFAULT_PORTS = Object.freeze({ implicit: 465, starttls: 587 });
|
|
140
|
+
var SMTP_MIN_TLS_VERSION = "TLSv1.2";
|
|
141
|
+
var SENDGRID_REQUEST_MAX_BYTES = 8 * MiB;
|
|
142
|
+
var SENDGRID_RESPONSE_MAX_BYTES = 64 * KiB;
|
|
143
|
+
|
|
144
|
+
// src/internal/canonical-json.ts
|
|
145
|
+
var import_node_crypto = require("crypto");
|
|
146
|
+
|
|
147
|
+
// src/internal/validation.ts
|
|
148
|
+
var import_node_buffer = require("buffer");
|
|
149
|
+
var import_node_util = require("util");
|
|
150
|
+
|
|
151
|
+
// src/errors.ts
|
|
152
|
+
var messages = Object.freeze({
|
|
153
|
+
invalid_config: "Invalid email service configuration.",
|
|
154
|
+
invalid_command: "Invalid email command.",
|
|
155
|
+
invalid_input: "Invalid template input.",
|
|
156
|
+
invalid_data: "Invalid prepared template data.",
|
|
157
|
+
invalid_snapshot: "Invalid prepared email snapshot.",
|
|
158
|
+
preparation_failed: "Email preparation failed.",
|
|
159
|
+
template_not_found: "Email template not found.",
|
|
160
|
+
template_source: "Email template source could not be loaded.",
|
|
161
|
+
template_render: "Email template could not be rendered.",
|
|
162
|
+
provider_mismatch: "Email provider does not match the template or snapshot.",
|
|
163
|
+
expired: "Email has expired.",
|
|
164
|
+
idempotency_conflict: "Email admission key was used with different intent.",
|
|
165
|
+
not_found: "Email job not found.",
|
|
166
|
+
resolution_conflict: "Unknown attempt cannot be resolved with this action.",
|
|
167
|
+
store_capacity: "Email store is at capacity.",
|
|
168
|
+
store_unavailable: "Email store is unavailable.",
|
|
169
|
+
store_incompatible: "Email store does not meet the required guarantees.",
|
|
170
|
+
write_unconfirmed: "Email store write not confirmed; it may have committed.",
|
|
171
|
+
invalid_cursor: "Invalid email activity cursor.",
|
|
172
|
+
aborted: "Email operation was aborted.",
|
|
173
|
+
deadline: "Email operation deadline elapsed.",
|
|
174
|
+
busy: "Email service has no available capacity for this operation.",
|
|
175
|
+
closed: "Email service is closed."
|
|
176
|
+
});
|
|
177
|
+
var EmailError = class extends Error {
|
|
178
|
+
/** `write_unconfirmed` does not mean that a dispatched mutation failed to commit. */
|
|
179
|
+
code;
|
|
180
|
+
constructor(code) {
|
|
181
|
+
const safeCode = typeof code === "string" && Object.hasOwn(messages, code) ? code : "invalid_config";
|
|
182
|
+
super(messages[safeCode]);
|
|
183
|
+
this.name = "EmailError";
|
|
184
|
+
this.code = safeCode;
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
// src/internal/validation.ts
|
|
189
|
+
function invalid(code) {
|
|
190
|
+
throw new EmailError(code);
|
|
191
|
+
}
|
|
192
|
+
function dataObject(value, code) {
|
|
193
|
+
if (typeof value !== "object" || value === null || import_node_util.types.isProxy(value)) invalid(code);
|
|
194
|
+
return value;
|
|
195
|
+
}
|
|
196
|
+
function isArray(value, code) {
|
|
197
|
+
return Array.isArray(dataObject(value, code));
|
|
198
|
+
}
|
|
199
|
+
function plainKeys(value, maxKeys, code) {
|
|
200
|
+
const object = dataObject(value, code);
|
|
201
|
+
const proto = Object.getPrototypeOf(object);
|
|
202
|
+
if (Array.isArray(object) || proto !== null && proto !== Object.prototype) invalid(code);
|
|
203
|
+
const keys = Reflect.ownKeys(object);
|
|
204
|
+
if (keys.length > maxKeys || keys.some((key) => typeof key !== "string")) invalid(code);
|
|
205
|
+
return keys;
|
|
206
|
+
}
|
|
207
|
+
function ownData(value, key, code) {
|
|
208
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
209
|
+
if (!descriptor?.enumerable || !Object.hasOwn(descriptor, "value")) invalid(code);
|
|
210
|
+
return descriptor.value;
|
|
211
|
+
}
|
|
212
|
+
function readRecord(value, required, optional, code) {
|
|
213
|
+
const keys = plainKeys(value, required.length + optional.length, code);
|
|
214
|
+
const copy = /* @__PURE__ */ Object.create(null);
|
|
215
|
+
for (const key of keys) {
|
|
216
|
+
if (!required.includes(key) && !optional.includes(key)) invalid(code);
|
|
217
|
+
copy[key] = ownData(value, key, code);
|
|
218
|
+
}
|
|
219
|
+
for (const key of required) {
|
|
220
|
+
if (!Object.hasOwn(copy, key)) invalid(code);
|
|
221
|
+
}
|
|
222
|
+
return copy;
|
|
223
|
+
}
|
|
224
|
+
function denseArrayLength(value, maxLength, code) {
|
|
225
|
+
const object = dataObject(value, code);
|
|
226
|
+
if (!Array.isArray(object) || Object.getPrototypeOf(object) !== Array.prototype) invalid(code);
|
|
227
|
+
const { length } = object;
|
|
228
|
+
if (length > maxLength || Reflect.ownKeys(object).length !== length + 1) invalid(code);
|
|
229
|
+
return length;
|
|
230
|
+
}
|
|
231
|
+
function readArray(value, maxLength, code, read) {
|
|
232
|
+
const length = denseArrayLength(value, maxLength, code);
|
|
233
|
+
const copy = [];
|
|
234
|
+
for (let i = 0; i < length; i++) copy.push(read(ownData(value, String(i), code)));
|
|
235
|
+
return Object.freeze(copy);
|
|
236
|
+
}
|
|
237
|
+
function integer(value, min, max, code) {
|
|
238
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max) invalid(code);
|
|
239
|
+
return value === 0 ? 0 : value;
|
|
240
|
+
}
|
|
241
|
+
function boundedOption(value, bounds, code = "invalid_config") {
|
|
242
|
+
return value === void 0 ? bounds.default : integer(value, bounds.min, bounds.max, code);
|
|
243
|
+
}
|
|
244
|
+
function unixMs(value, code) {
|
|
245
|
+
return integer(value, 0, MAX_UNIX_MS, code);
|
|
246
|
+
}
|
|
247
|
+
function utf8Length(value, maxBytes, code) {
|
|
248
|
+
if (value.length > maxBytes || /[\uD800-\uDFFF]/u.test(value)) invalid(code);
|
|
249
|
+
const bytes = import_node_buffer.Buffer.byteLength(value, "utf8");
|
|
250
|
+
if (bytes > maxBytes) invalid(code);
|
|
251
|
+
return bytes;
|
|
252
|
+
}
|
|
253
|
+
function utf8String(value, maxBytes, code) {
|
|
254
|
+
if (typeof value !== "string") invalid(code);
|
|
255
|
+
utf8Length(value, maxBytes, code);
|
|
256
|
+
return value;
|
|
257
|
+
}
|
|
258
|
+
function headerString(value, maxBytes, code) {
|
|
259
|
+
const text = utf8String(value, maxBytes, code);
|
|
260
|
+
for (let i = 0; i < text.length; i++) {
|
|
261
|
+
const ch = text.charCodeAt(i);
|
|
262
|
+
if (ch < 32 || ch === 127) invalid(code);
|
|
263
|
+
}
|
|
264
|
+
return text;
|
|
265
|
+
}
|
|
266
|
+
function opaqueToken(value, maxBytes, code) {
|
|
267
|
+
if (typeof value !== "string" || value.length > maxBytes || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(value)) {
|
|
268
|
+
invalid(code);
|
|
269
|
+
}
|
|
270
|
+
return value;
|
|
271
|
+
}
|
|
272
|
+
function identifier(value, code) {
|
|
273
|
+
return opaqueToken(value, MESSAGE_LIMITS.identifierBytes, code);
|
|
274
|
+
}
|
|
275
|
+
function hashToken(value, code) {
|
|
276
|
+
if (typeof value !== "string" || value.length !== 64 || !/^[0-9a-f]{64}$/.test(value)) invalid(code);
|
|
277
|
+
return value;
|
|
278
|
+
}
|
|
279
|
+
function jsonKey(key, code) {
|
|
280
|
+
utf8Length(key, MESSAGE_LIMITS.jsonKeyBytes, code);
|
|
281
|
+
if (key === "__proto__" || key === "prototype" || key === "constructor" || key.includes(".") || key.includes("$") || key.includes("\0")) {
|
|
282
|
+
invalid(code);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// src/internal/canonical-json.ts
|
|
287
|
+
var treeLimits = { depth: MESSAGE_LIMITS.jsonDepth, values: MESSAGE_LIMITS.jsonValues };
|
|
288
|
+
function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = treeLimits) {
|
|
289
|
+
let bytesLeft = maxBytes;
|
|
290
|
+
let valuesLeft = limits.values;
|
|
291
|
+
const chunks = [];
|
|
292
|
+
const ancestors = /* @__PURE__ */ new Set();
|
|
293
|
+
function append(text, bytes = text.length) {
|
|
294
|
+
if (bytes > bytesLeft) invalid(code);
|
|
295
|
+
bytesLeft -= bytes;
|
|
296
|
+
chunks.push(text);
|
|
297
|
+
}
|
|
298
|
+
function appendString(text) {
|
|
299
|
+
let bytes = 2 + utf8Length(text, bytesLeft - 2, code);
|
|
300
|
+
for (let i = 0; i < text.length; i++) {
|
|
301
|
+
const ch = text.charCodeAt(i);
|
|
302
|
+
if (ch === 34 || ch === 92 || ch === 8 || ch === 9 || ch === 10 || ch === 12 || ch === 13) bytes++;
|
|
303
|
+
else if (ch < 32) bytes += 5;
|
|
304
|
+
if (bytes > bytesLeft) invalid(code);
|
|
305
|
+
}
|
|
306
|
+
append(JSON.stringify(text), bytes);
|
|
307
|
+
}
|
|
308
|
+
function visit(value2, depth) {
|
|
309
|
+
if (depth > limits.depth || --valuesLeft < 0 || bytesLeft < 1) invalid(code);
|
|
310
|
+
switch (typeof value2) {
|
|
311
|
+
case "string":
|
|
312
|
+
appendString(value2);
|
|
313
|
+
return value2;
|
|
314
|
+
case "number":
|
|
315
|
+
if (!Number.isFinite(value2) || Number.isInteger(value2) && !Number.isSafeInteger(value2)) invalid(code);
|
|
316
|
+
append(JSON.stringify(value2));
|
|
317
|
+
return value2 === 0 ? 0 : value2;
|
|
318
|
+
case "boolean":
|
|
319
|
+
append(value2 ? "true" : "false");
|
|
320
|
+
return value2;
|
|
321
|
+
case "object":
|
|
322
|
+
if (value2 === null) {
|
|
323
|
+
append("null");
|
|
324
|
+
return null;
|
|
325
|
+
}
|
|
326
|
+
break;
|
|
327
|
+
default:
|
|
328
|
+
invalid(code);
|
|
329
|
+
}
|
|
330
|
+
if (ancestors.has(value2)) invalid(code);
|
|
331
|
+
ancestors.add(value2);
|
|
332
|
+
try {
|
|
333
|
+
const maxChildren = depth === limits.depth ? 0 : valuesLeft;
|
|
334
|
+
if (isArray(value2, code)) {
|
|
335
|
+
const length = denseArrayLength(value2, maxChildren, code);
|
|
336
|
+
if (length && 2 * length + 1 > bytesLeft) invalid(code);
|
|
337
|
+
const copy2 = [];
|
|
338
|
+
append("[");
|
|
339
|
+
for (let i = 0; i < length; i++) {
|
|
340
|
+
if (i) append(",");
|
|
341
|
+
copy2.push(visit(ownData(value2, String(i), code), depth + 1));
|
|
342
|
+
}
|
|
343
|
+
append("]");
|
|
344
|
+
return Object.freeze(copy2);
|
|
345
|
+
}
|
|
346
|
+
const keys = plainKeys(value2, maxChildren, code);
|
|
347
|
+
if (keys.length && 5 * keys.length + 1 > bytesLeft) invalid(code);
|
|
348
|
+
for (const key of keys) jsonKey(key, code);
|
|
349
|
+
const copy = /* @__PURE__ */ Object.create(null);
|
|
350
|
+
append("{");
|
|
351
|
+
for (const [index, key] of keys.sort().entries()) {
|
|
352
|
+
if (index) append(",");
|
|
353
|
+
appendString(key);
|
|
354
|
+
append(":");
|
|
355
|
+
copy[key] = visit(ownData(value2, key, code), depth + 1);
|
|
356
|
+
}
|
|
357
|
+
append("}");
|
|
358
|
+
return Object.freeze(copy);
|
|
359
|
+
} finally {
|
|
360
|
+
ancestors.delete(value2);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
const value = visit(input, 0);
|
|
364
|
+
return { value, encoded: chunks.join("") };
|
|
365
|
+
}
|
|
366
|
+
function copyJsonObject(input, maxBytes, code) {
|
|
367
|
+
if (typeof input !== "object" || input === null || isArray(input, code)) invalid(code);
|
|
368
|
+
return canonicalJson(input, maxBytes, code).value;
|
|
369
|
+
}
|
|
370
|
+
function sha256(input) {
|
|
371
|
+
return (0, import_node_crypto.createHash)("sha256").update(input).digest("hex");
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// src/internal/attempt-codecs.ts
|
|
375
|
+
var smtpStages = ["connect", "tls", "auth", "envelope", "data"];
|
|
376
|
+
var providerStages = [...smtpStages, "http"];
|
|
377
|
+
var evidence = Object.freeze({
|
|
378
|
+
smtp_accepted: ["accepted", "never", ["data"], "smtp"],
|
|
379
|
+
smtp_partial: ["partially_accepted", "never", ["data"], "smtp"],
|
|
380
|
+
smtp_transient_reply: ["rejected", "safe_transient", smtpStages, "smtp"],
|
|
381
|
+
smtp_permanent_reply: ["rejected", "never", smtpStages, "smtp"],
|
|
382
|
+
sendgrid_accepted: ["accepted", "never", ["http"], "sendgrid"],
|
|
383
|
+
sendgrid_validated: ["validated", "never", ["http"], "sendgrid"],
|
|
384
|
+
sendgrid_throttled: ["rejected", "safe_transient", ["http"], "sendgrid"],
|
|
385
|
+
sendgrid_rejected: ["rejected", "never", ["http"], "sendgrid"],
|
|
386
|
+
not_transmitted: ["unsubmitted", "safe_transient", providerStages, "provider"],
|
|
387
|
+
provider_configuration: ["unsubmitted", "never", providerStages, "provider"],
|
|
388
|
+
transport_uncertain: ["unknown", "never", providerStages, "provider"],
|
|
389
|
+
provider_timeout: ["unknown", "never", providerStages, "provider"],
|
|
390
|
+
provider_aborted: ["unknown", "never", providerStages, "provider"],
|
|
391
|
+
attachment_unavailable: ["unsubmitted", "safe_transient", ["attachment"], "pre"],
|
|
392
|
+
attachment_timeout: ["unsubmitted", "safe_transient", ["attachment"], "pre"],
|
|
393
|
+
attachment_invalid: ["unsubmitted", "never", ["attachment"], "pre"],
|
|
394
|
+
attachment_resolver_error: ["unsubmitted", "never", ["attachment"], "pre"],
|
|
395
|
+
rate_deferred: ["unsubmitted", "safe_transient", ["rate_limit"], "pre"],
|
|
396
|
+
rate_timeout: ["unsubmitted", "safe_transient", ["rate_limit"], "pre"],
|
|
397
|
+
rate_error: ["unsubmitted", "never", ["rate_limit"], "pre"],
|
|
398
|
+
profile_unavailable: ["unsubmitted", "never", ["pre_handoff"], "pre"],
|
|
399
|
+
provider_preflight_error: ["unsubmitted", "never", ["pre_handoff"], "pre"],
|
|
400
|
+
pre_handoff_timeout: ["unsubmitted", "safe_transient", ["pre_handoff"], "pre"],
|
|
401
|
+
worker_stopped: ["unsubmitted", "safe_transient", ["pre_handoff"], "pre"],
|
|
402
|
+
pre_handoff_lease_expired: ["unsubmitted", "safe_transient", ["pre_handoff"], "recovery"],
|
|
403
|
+
launch_window_closed: ["unsubmitted", "safe_transient", ["pre_handoff"], "launch"],
|
|
404
|
+
post_handoff_lease_expired: ["unknown", "never", ["pre_handoff"], "recovery"],
|
|
405
|
+
expired: ["unsubmitted", "never", ["pre_handoff"], "pre"],
|
|
406
|
+
cancelled: ["unsubmitted", "never", ["pre_handoff"], "cancel"]
|
|
407
|
+
});
|
|
408
|
+
function readAttemptReason(value, code) {
|
|
409
|
+
if (typeof value !== "string" || !Object.hasOwn(evidence, value)) invalid(code);
|
|
410
|
+
return value;
|
|
411
|
+
}
|
|
412
|
+
var recipientGroups = ["to", "cc", "bcc"];
|
|
413
|
+
function recipientCounts(envelope) {
|
|
414
|
+
return Object.freeze({ to: envelope.to.length, cc: envelope.cc.length, bcc: envelope.bcc.length });
|
|
415
|
+
}
|
|
416
|
+
function smtpMessageId(attemptId) {
|
|
417
|
+
return `<${attemptId}@email.invalid>`;
|
|
418
|
+
}
|
|
419
|
+
function readHint(input, reason, code) {
|
|
420
|
+
if (reason !== "rate_deferred" && reason !== "sendgrid_throttled") invalid(code);
|
|
421
|
+
const raw = readRecord(input, [], ["delayMs", "notBefore"], code);
|
|
422
|
+
const hasDelay = Object.hasOwn(raw, "delayMs");
|
|
423
|
+
const hasFloor = Object.hasOwn(raw, "notBefore");
|
|
424
|
+
if (!hasDelay && (!hasFloor || reason === "rate_deferred")) invalid(code);
|
|
425
|
+
return Object.freeze({
|
|
426
|
+
...hasDelay ? {
|
|
427
|
+
delayMs: reason === "rate_deferred" ? integer(raw.delayMs, 1, MAX_RATE_DEFERRAL_MS, code) : integer(raw.delayMs, 0, Number.MAX_SAFE_INTEGER, code)
|
|
428
|
+
} : {},
|
|
429
|
+
...hasFloor ? { notBefore: unixMs(raw.notBefore, code) } : {}
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
function readAttemptResult(input, code = "invalid_command", projected = false) {
|
|
433
|
+
const raw = readRecord(
|
|
434
|
+
input,
|
|
435
|
+
["outcome", "retry", "stage", "reason"],
|
|
436
|
+
["retryHint", "recipients", "messageId", "providerMessageId"],
|
|
437
|
+
code
|
|
438
|
+
);
|
|
439
|
+
const reason = readAttemptReason(raw.reason, code);
|
|
440
|
+
const [outcome, retry, stages, origin] = evidence[reason];
|
|
441
|
+
const stage = stages.find((value) => value === raw.stage);
|
|
442
|
+
if (raw.outcome !== outcome || raw.retry !== retry || !stage) invalid(code);
|
|
443
|
+
const hasHint = Object.hasOwn(raw, "retryHint");
|
|
444
|
+
if (projected && hasHint || !projected && reason === "rate_deferred" && !hasHint) invalid(code);
|
|
445
|
+
const smtpSuccess = reason === "smtp_accepted" || reason === "smtp_partial";
|
|
446
|
+
const hasRecipients = Object.hasOwn(raw, "recipients");
|
|
447
|
+
if (smtpSuccess && !hasRecipients) invalid(code);
|
|
448
|
+
let recipients;
|
|
449
|
+
if (hasRecipients) {
|
|
450
|
+
if (origin !== "smtp" && origin !== "provider" || stage !== "envelope" && stage !== "data") invalid(code);
|
|
451
|
+
const seen = /* @__PURE__ */ new Set();
|
|
452
|
+
recipients = readArray(raw.recipients, MESSAGE_LIMITS.recipients, code, (value) => {
|
|
453
|
+
const { group, index: rawIndex, status } = readRecord(value, ["group", "index", "status"], [], code);
|
|
454
|
+
if (group !== "to" && group !== "cc" && group !== "bcc") invalid(code);
|
|
455
|
+
if (status !== "rejected" && (status !== "accepted" || !smtpSuccess)) invalid(code);
|
|
456
|
+
const index = integer(rawIndex, 0, MESSAGE_LIMITS.recipients - 1, code);
|
|
457
|
+
const key = `${group}:${index}`;
|
|
458
|
+
if (seen.has(key)) invalid(code);
|
|
459
|
+
seen.add(key);
|
|
460
|
+
return Object.freeze({ group, index, status });
|
|
461
|
+
});
|
|
462
|
+
const accepted = recipients.filter(({ status }) => status === "accepted").length;
|
|
463
|
+
if (reason === "smtp_accepted" && (!accepted || accepted !== recipients.length) || reason === "smtp_partial" && (!accepted || accepted === recipients.length)) {
|
|
464
|
+
invalid(code);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
const hasMessageId = Object.hasOwn(raw, "messageId");
|
|
468
|
+
const { messageId, providerMessageId } = raw;
|
|
469
|
+
if (hasMessageId && (!smtpSuccess || typeof messageId !== "string" || messageId.length !== 52)) invalid(code);
|
|
470
|
+
const hasProviderId = Object.hasOwn(raw, "providerMessageId");
|
|
471
|
+
if (hasProviderId && (reason !== "sendgrid_accepted" || typeof providerMessageId !== "string" || providerMessageId.length > 128 || !/^[A-Za-z0-9][A-Za-z0-9._=-]{0,127}$/.test(providerMessageId))) {
|
|
472
|
+
invalid(code);
|
|
473
|
+
}
|
|
474
|
+
return Object.freeze({
|
|
475
|
+
outcome,
|
|
476
|
+
retry,
|
|
477
|
+
stage,
|
|
478
|
+
reason,
|
|
479
|
+
...hasHint ? { retryHint: readHint(raw.retryHint, reason, code) } : {},
|
|
480
|
+
...recipients === void 0 ? {} : { recipients },
|
|
481
|
+
...typeof messageId === "string" ? { messageId } : {},
|
|
482
|
+
...typeof providerMessageId === "string" ? { providerMessageId } : {}
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
function assertEvidenceContext(result, provider, attemptId, counts, code) {
|
|
486
|
+
const { reason, stage, recipients, messageId } = result;
|
|
487
|
+
const origin = evidence[reason][3];
|
|
488
|
+
if (origin === "smtp" && provider.kind !== "smtp" || origin === "sendgrid" && provider.kind !== "sendgrid" || origin === "provider" && (provider.kind === "smtp" ? stage === "http" : stage !== "http" && stage !== "connect" && stage !== "tls") || reason === "sendgrid_accepted" && provider.mode !== "live" || reason === "sendgrid_validated" && provider.mode !== "sandbox" || messageId !== void 0 && messageId !== smtpMessageId(attemptId)) {
|
|
489
|
+
invalid(code);
|
|
490
|
+
}
|
|
491
|
+
if (recipients) {
|
|
492
|
+
if (provider.kind !== "smtp") invalid(code);
|
|
493
|
+
if (counts) {
|
|
494
|
+
if (recipients.some(({ group, index }) => index >= counts[group])) invalid(code);
|
|
495
|
+
const needsPartition = reason === "smtp_accepted" || reason === "smtp_partial" || stage === "envelope" && (reason === "smtp_transient_reply" || reason === "smtp_permanent_reply");
|
|
496
|
+
if (needsPartition && recipients.length !== counts.to + counts.cc + counts.bcc) invalid(code);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
function readProviderResult(input, provider, attemptId, envelope) {
|
|
501
|
+
const code = "invalid_command";
|
|
502
|
+
const result = readAttemptResult(input, code);
|
|
503
|
+
const origin = evidence[result.reason][3];
|
|
504
|
+
if (origin !== "smtp" && origin !== "sendgrid" && origin !== "provider") invalid(code);
|
|
505
|
+
assertEvidenceContext(result, provider, attemptId, recipientCounts(envelope), code);
|
|
506
|
+
return result;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
// src/internal/budget.ts
|
|
510
|
+
var import_node_events = require("events");
|
|
511
|
+
var import_node_perf_hooks = require("perf_hooks");
|
|
512
|
+
var import_promises = require("timers/promises");
|
|
513
|
+
var import_node_util2 = require("util");
|
|
514
|
+
var systemEmailClock = Object.freeze({
|
|
515
|
+
now: Date.now,
|
|
516
|
+
monotonicNow: () => import_node_perf_hooks.performance.now(),
|
|
517
|
+
sleep: (ms, signal) => (0, import_promises.setTimeout)(ms, void 0, { signal })
|
|
518
|
+
});
|
|
519
|
+
function readCallOptions(input, bounds) {
|
|
520
|
+
const code = "invalid_config";
|
|
521
|
+
const { signal, timeoutMs } = readRecord(input, [], ["signal", "timeoutMs"], code);
|
|
522
|
+
const timeout = boundedOption(timeoutMs, bounds, code);
|
|
523
|
+
if (signal === void 0) return { timeoutMs: timeout };
|
|
524
|
+
try {
|
|
525
|
+
if (!import_node_util2.types.isProxy(signal) && signal instanceof AbortSignal && typeof Reflect.get(AbortSignal.prototype, "aborted", signal) === "boolean") {
|
|
526
|
+
return { signal, timeoutMs: timeout };
|
|
527
|
+
}
|
|
528
|
+
} catch {
|
|
529
|
+
invalid(code);
|
|
530
|
+
}
|
|
531
|
+
return invalid(code);
|
|
532
|
+
}
|
|
533
|
+
function monotonicNow(clock) {
|
|
534
|
+
try {
|
|
535
|
+
const now = clock.monotonicNow();
|
|
536
|
+
if (Number.isFinite(now)) return now;
|
|
537
|
+
} catch {
|
|
538
|
+
invalid("invalid_config");
|
|
539
|
+
}
|
|
540
|
+
return invalid("invalid_config");
|
|
541
|
+
}
|
|
542
|
+
function createBudget(clock, timeoutMs, external) {
|
|
543
|
+
return createBudgetUntil(clock, monotonicNow(clock) + timeoutMs, external);
|
|
544
|
+
}
|
|
545
|
+
function createBudgetUntil(clock, end, external) {
|
|
546
|
+
const operation = new AbortController();
|
|
547
|
+
const timer = new AbortController();
|
|
548
|
+
let externalListener;
|
|
549
|
+
let closed = false;
|
|
550
|
+
let reason;
|
|
551
|
+
function close() {
|
|
552
|
+
if (closed) return;
|
|
553
|
+
closed = true;
|
|
554
|
+
externalListener?.[Symbol.dispose]();
|
|
555
|
+
timer.abort();
|
|
556
|
+
}
|
|
557
|
+
function stop(code) {
|
|
558
|
+
if (closed) return;
|
|
559
|
+
reason = code;
|
|
560
|
+
close();
|
|
561
|
+
operation.abort(new EmailError(code));
|
|
562
|
+
}
|
|
563
|
+
function remainingMs() {
|
|
564
|
+
if (closed) return 0;
|
|
565
|
+
if (external?.aborted) {
|
|
566
|
+
stop("aborted");
|
|
567
|
+
} else {
|
|
568
|
+
try {
|
|
569
|
+
const remaining = end - monotonicNow(clock);
|
|
570
|
+
if (remaining > 0) return remaining;
|
|
571
|
+
stop("deadline");
|
|
572
|
+
} catch {
|
|
573
|
+
stop("invalid_config");
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
return 0;
|
|
577
|
+
}
|
|
578
|
+
function arm(remaining) {
|
|
579
|
+
void Promise.resolve(clock.sleep(Math.ceil(remaining), timer.signal)).then(
|
|
580
|
+
() => {
|
|
581
|
+
try {
|
|
582
|
+
const left = remainingMs();
|
|
583
|
+
if (left <= 0) return;
|
|
584
|
+
if (left >= remaining) stop("invalid_config");
|
|
585
|
+
else arm(left);
|
|
586
|
+
} catch {
|
|
587
|
+
stop("invalid_config");
|
|
588
|
+
}
|
|
589
|
+
},
|
|
590
|
+
() => stop("invalid_config")
|
|
591
|
+
);
|
|
592
|
+
}
|
|
593
|
+
try {
|
|
594
|
+
if (external && !external.aborted) externalListener = (0, import_node_events.addAbortListener)(external, () => stop("aborted"));
|
|
595
|
+
const remaining = remainingMs();
|
|
596
|
+
if (remaining > 0) arm(remaining);
|
|
597
|
+
} catch {
|
|
598
|
+
stop("invalid_config");
|
|
599
|
+
}
|
|
600
|
+
return {
|
|
601
|
+
signal: operation.signal,
|
|
602
|
+
deadline: end,
|
|
603
|
+
remainingMs,
|
|
604
|
+
check() {
|
|
605
|
+
remainingMs();
|
|
606
|
+
if (reason) invalid(reason);
|
|
607
|
+
if (closed) invalid("aborted");
|
|
608
|
+
},
|
|
609
|
+
close
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
// src/internal/message-codecs.ts
|
|
614
|
+
var import_node_net = require("net");
|
|
615
|
+
var import_node_util3 = require("util");
|
|
616
|
+
var L = MESSAGE_LIMITS;
|
|
617
|
+
var SNAPSHOT = "invalid_snapshot";
|
|
618
|
+
var DOT_ATOM = /^[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*$/;
|
|
619
|
+
var DNS_LABEL = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/;
|
|
620
|
+
var MIME_TYPE = /^[-a-z0-9!#$%&'*+.^_`{|}~]+\/[-a-z0-9!#$%&'*+.^_`{|}~]+$/;
|
|
621
|
+
function validateProviderRef(input, code = SNAPSHOT) {
|
|
622
|
+
const { kind, key, mode } = readRecord(input, ["kind", "key", "mode"], [], code);
|
|
623
|
+
const profile = identifier(key, code);
|
|
624
|
+
if (kind === "smtp" && mode === "live") return Object.freeze({ kind, key: profile, mode });
|
|
625
|
+
if (kind === "sendgrid" && (mode === "live" || mode === "sandbox")) {
|
|
626
|
+
return Object.freeze({ kind, key: profile, mode });
|
|
627
|
+
}
|
|
628
|
+
return invalid(code);
|
|
629
|
+
}
|
|
630
|
+
function validateTemplateIdentity(input, code = SNAPSHOT) {
|
|
631
|
+
const { key, revision } = readRecord(input, ["key", "revision"], [], code);
|
|
632
|
+
return Object.freeze({ key: identifier(key, code), revision: identifier(revision, code) });
|
|
633
|
+
}
|
|
634
|
+
function sendGridTemplateId(input, code = SNAPSHOT) {
|
|
635
|
+
if (typeof input !== "string" || input.length !== 34 || !/^d-[0-9a-fA-F]{32}$/.test(input)) invalid(code);
|
|
636
|
+
return input;
|
|
637
|
+
}
|
|
638
|
+
function validateMailbox(input, code = SNAPSHOT) {
|
|
639
|
+
const mailbox = readRecord(input, ["address"], ["name"], code);
|
|
640
|
+
const address = headerString(mailbox.address, L.addressBytes, code);
|
|
641
|
+
const at = address.indexOf("@");
|
|
642
|
+
const local = address.slice(0, at);
|
|
643
|
+
const domain = address.slice(at + 1);
|
|
644
|
+
if (at < 1 || at > L.localPartBytes || !DOT_ATOM.test(local) || !domain.split(".").every((label) => DNS_LABEL.test(label)) || (0, import_node_net.isIP)(domain) !== 0) {
|
|
645
|
+
invalid(code);
|
|
646
|
+
}
|
|
647
|
+
return Object.freeze({
|
|
648
|
+
address,
|
|
649
|
+
...Object.hasOwn(mailbox, "name") ? { name: headerString(mailbox.name, L.displayNameBytes, code) } : {}
|
|
650
|
+
});
|
|
651
|
+
}
|
|
652
|
+
function validateEnvelope(input, kind, code = SNAPSHOT) {
|
|
653
|
+
const envelope = readRecord(input, ["from", "to", "cc", "bcc"], ["replyTo"], code);
|
|
654
|
+
const seen = /* @__PURE__ */ new Set();
|
|
655
|
+
const recipient = (raw) => {
|
|
656
|
+
const mailbox = validateMailbox(raw, code);
|
|
657
|
+
const address = mailbox.address.toLowerCase();
|
|
658
|
+
if (seen.has(address)) invalid(code);
|
|
659
|
+
seen.add(address);
|
|
660
|
+
return mailbox;
|
|
661
|
+
};
|
|
662
|
+
const from = validateMailbox(envelope.from, code);
|
|
663
|
+
const to = readArray(envelope.to, L.recipients, code, recipient);
|
|
664
|
+
const cc = readArray(envelope.cc, L.recipients - to.length, code, recipient);
|
|
665
|
+
const bcc = readArray(envelope.bcc, L.recipients - to.length - cc.length, code, recipient);
|
|
666
|
+
if (seen.size === 0 || kind === "sendgrid" && to.length === 0) invalid(code);
|
|
667
|
+
return Object.freeze({
|
|
668
|
+
from,
|
|
669
|
+
to,
|
|
670
|
+
cc,
|
|
671
|
+
bcc,
|
|
672
|
+
...Object.hasOwn(envelope, "replyTo") ? { replyTo: validateMailbox(envelope.replyTo, code) } : {}
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
function validateCorrelation(input, code = SNAPSHOT) {
|
|
676
|
+
const keys = plainKeys(input, L.correlationEntries, code);
|
|
677
|
+
const copy = /* @__PURE__ */ Object.create(null);
|
|
678
|
+
for (const key of keys) {
|
|
679
|
+
jsonKey(key, code);
|
|
680
|
+
opaqueToken(key, L.correlationKeyBytes, code);
|
|
681
|
+
copy[key] = opaqueToken(ownData(input, key, code), L.correlationValueBytes, code);
|
|
682
|
+
}
|
|
683
|
+
return Object.freeze(copy);
|
|
684
|
+
}
|
|
685
|
+
function validateAttachmentRef(input, code = SNAPSHOT) {
|
|
686
|
+
const ref = readRecord(
|
|
687
|
+
input,
|
|
688
|
+
["resolverKey", "id", "version", "filename", "contentType", "byteLength", "sha256"],
|
|
689
|
+
[],
|
|
690
|
+
code
|
|
691
|
+
);
|
|
692
|
+
const filename = headerString(ref.filename, L.filenameBytes, code);
|
|
693
|
+
if (!filename || filename === "." || filename === ".." || /[/\\:]/.test(filename)) invalid(code);
|
|
694
|
+
const contentType = headerString(ref.contentType, L.contentTypeBytes, code);
|
|
695
|
+
if (!MIME_TYPE.test(contentType)) invalid(code);
|
|
696
|
+
return Object.freeze({
|
|
697
|
+
resolverKey: identifier(ref.resolverKey, code),
|
|
698
|
+
id: identifier(ref.id, code),
|
|
699
|
+
version: identifier(ref.version, code),
|
|
700
|
+
filename,
|
|
701
|
+
contentType,
|
|
702
|
+
byteLength: integer(ref.byteLength, 1, L.attachmentBytes, code),
|
|
703
|
+
sha256: hashToken(ref.sha256, code)
|
|
704
|
+
});
|
|
705
|
+
}
|
|
706
|
+
function validateAttachmentRefs(input, code = SNAPSHOT) {
|
|
707
|
+
let total = 0;
|
|
708
|
+
return readArray(input, L.attachments, code, (raw) => {
|
|
709
|
+
const ref = validateAttachmentRef(raw, code);
|
|
710
|
+
total += ref.byteLength;
|
|
711
|
+
if (total > L.totalAttachmentBytes) invalid(code);
|
|
712
|
+
return ref;
|
|
713
|
+
});
|
|
714
|
+
}
|
|
715
|
+
function copyAttachmentBytes(ref, input, code = SNAPSHOT) {
|
|
716
|
+
if (!import_node_util3.types.isUint8Array(input)) invalid(code);
|
|
717
|
+
const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
|
|
718
|
+
const buffer = Reflect.get(typedArrayPrototype, "buffer", input);
|
|
719
|
+
const offset = Reflect.get(typedArrayPrototype, "byteOffset", input);
|
|
720
|
+
const length = Reflect.get(typedArrayPrototype, "byteLength", input);
|
|
721
|
+
if (import_node_util3.types.isSharedArrayBuffer(buffer) || length !== ref.byteLength || length < 1 || length > L.attachmentBytes) {
|
|
722
|
+
invalid(code);
|
|
723
|
+
}
|
|
724
|
+
const bytes = new Uint8Array(new Uint8Array(buffer, offset, length));
|
|
725
|
+
if (sha256(bytes) !== ref.sha256) invalid(code);
|
|
726
|
+
return bytes;
|
|
727
|
+
}
|
|
728
|
+
function validateSubject(input, code = SNAPSHOT) {
|
|
729
|
+
const subject = headerString(input, L.subjectBytes, code);
|
|
730
|
+
if (!subject.trim()) invalid(code);
|
|
731
|
+
return subject;
|
|
732
|
+
}
|
|
733
|
+
function smtpParts(subject, html, text, code) {
|
|
734
|
+
if (!html && !text) invalid(code);
|
|
735
|
+
return Object.freeze({ subject, ...html === void 0 ? {} : { html }, ...text === void 0 ? {} : { text } });
|
|
736
|
+
}
|
|
737
|
+
function validateSmtpContent(input, code = SNAPSHOT) {
|
|
738
|
+
const content = readRecord(input, ["subject"], ["html", "text"], code);
|
|
739
|
+
return smtpParts(
|
|
740
|
+
validateSubject(content.subject, code),
|
|
741
|
+
Object.hasOwn(content, "html") ? utf8String(content.html, L.htmlBytes, code) : void 0,
|
|
742
|
+
Object.hasOwn(content, "text") ? utf8String(content.text, L.textBytes, code) : void 0,
|
|
743
|
+
code
|
|
744
|
+
);
|
|
745
|
+
}
|
|
746
|
+
function validateExpiry(input, preparedAt, scheduleAt, code = SNAPSHOT) {
|
|
747
|
+
const expiresAt = unixMs(input, code);
|
|
748
|
+
if (expiresAt <= preparedAt || expiresAt - preparedAt > MAX_EXPIRY_MS || scheduleAt !== null && scheduleAt >= expiresAt) {
|
|
749
|
+
invalid(code);
|
|
750
|
+
}
|
|
751
|
+
return expiresAt;
|
|
752
|
+
}
|
|
753
|
+
function hashSnapshot(snapshot) {
|
|
754
|
+
return sha256(
|
|
755
|
+
canonicalJson(snapshot, L.snapshotBytes, SNAPSHOT, { depth: L.jsonDepth + 1, values: L.jsonValues + 256 }).encoded
|
|
756
|
+
);
|
|
757
|
+
}
|
|
758
|
+
function readSnapshot(input) {
|
|
759
|
+
const dto = readRecord(
|
|
760
|
+
input,
|
|
761
|
+
[
|
|
762
|
+
"version",
|
|
763
|
+
"kind",
|
|
764
|
+
"provider",
|
|
765
|
+
"template",
|
|
766
|
+
"envelope",
|
|
767
|
+
"preparedAt",
|
|
768
|
+
"expiresAt",
|
|
769
|
+
"priority",
|
|
770
|
+
"attachments",
|
|
771
|
+
"correlation"
|
|
772
|
+
],
|
|
773
|
+
["subject", "html", "text", "templateId", "data"],
|
|
774
|
+
SNAPSHOT
|
|
775
|
+
);
|
|
776
|
+
if (dto.version !== EMAIL_FORMAT_VERSION || dto.kind !== "smtp" && dto.kind !== "sendgrid") invalid(SNAPSHOT);
|
|
777
|
+
const provider = validateProviderRef(dto.provider);
|
|
778
|
+
if (provider.kind !== dto.kind) invalid("provider_mismatch");
|
|
779
|
+
const preparedAt = unixMs(dto.preparedAt, SNAPSHOT);
|
|
780
|
+
const common = {
|
|
781
|
+
version: EMAIL_FORMAT_VERSION,
|
|
782
|
+
template: validateTemplateIdentity(dto.template),
|
|
783
|
+
envelope: validateEnvelope(dto.envelope, provider.kind),
|
|
784
|
+
preparedAt,
|
|
785
|
+
expiresAt: validateExpiry(dto.expiresAt, preparedAt, null),
|
|
786
|
+
priority: integer(dto.priority, PRIORITY.min, PRIORITY.max, SNAPSHOT),
|
|
787
|
+
attachments: validateAttachmentRefs(dto.attachments),
|
|
788
|
+
correlation: validateCorrelation(dto.correlation)
|
|
789
|
+
};
|
|
790
|
+
if (provider.kind === "smtp") {
|
|
791
|
+
if (Object.hasOwn(dto, "templateId") || Object.hasOwn(dto, "data")) invalid(SNAPSHOT);
|
|
792
|
+
const content = validateSmtpContent({
|
|
793
|
+
subject: dto.subject,
|
|
794
|
+
...Object.hasOwn(dto, "html") ? { html: dto.html } : {},
|
|
795
|
+
...Object.hasOwn(dto, "text") ? { text: dto.text } : {}
|
|
796
|
+
});
|
|
797
|
+
return Object.freeze({ ...common, kind: provider.kind, provider, ...content });
|
|
798
|
+
}
|
|
799
|
+
if (Object.hasOwn(dto, "subject") || Object.hasOwn(dto, "html") || Object.hasOwn(dto, "text")) invalid(SNAPSHOT);
|
|
800
|
+
return Object.freeze({
|
|
801
|
+
...common,
|
|
802
|
+
kind: provider.kind,
|
|
803
|
+
provider,
|
|
804
|
+
templateId: sendGridTemplateId(dto.templateId),
|
|
805
|
+
data: copyJsonObject(dto.data, L.dataBytes, SNAPSHOT)
|
|
806
|
+
});
|
|
807
|
+
}
|
|
808
|
+
function validateSnapshot(input) {
|
|
809
|
+
const snapshot = readSnapshot(input);
|
|
810
|
+
return { snapshot, snapshotHash: hashSnapshot(snapshot) };
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
// src/internal/store-codecs.ts
|
|
814
|
+
var REQUEST = "invalid_command";
|
|
815
|
+
var LEASE = WORKER_LIMIT_BOUNDS.leaseMs;
|
|
816
|
+
function readStoreId(value, code = REQUEST) {
|
|
817
|
+
if (typeof value !== "string" || value.length !== 36 || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value)) {
|
|
818
|
+
invalid(code);
|
|
819
|
+
}
|
|
820
|
+
return value;
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
// src/internal/provider-preparation.ts
|
|
824
|
+
function sameRef(a, b) {
|
|
825
|
+
return a.resolverKey === b.resolverKey && a.id === b.id && a.version === b.version && a.filename === b.filename && a.contentType === b.contentType && a.byteLength === b.byteLength && a.sha256 === b.sha256;
|
|
826
|
+
}
|
|
827
|
+
function readProviderSubmission(input, ref) {
|
|
828
|
+
const code = "invalid_snapshot";
|
|
829
|
+
const raw = readRecord(input, ["jobId", "attemptId", "snapshot", "attachments"], [], code);
|
|
830
|
+
const jobId = readStoreId(raw.jobId, code);
|
|
831
|
+
const attemptId = readStoreId(raw.attemptId, code);
|
|
832
|
+
const { snapshot } = validateSnapshot(raw.snapshot);
|
|
833
|
+
if (ref.kind !== snapshot.kind || ref.key !== snapshot.provider.key || ref.mode !== snapshot.provider.mode) {
|
|
834
|
+
invalid("provider_mismatch");
|
|
835
|
+
}
|
|
836
|
+
const length = denseArrayLength(raw.attachments, MESSAGE_LIMITS.attachments, code);
|
|
837
|
+
if (length !== snapshot.attachments.length) invalid(code);
|
|
838
|
+
const attachments = snapshot.attachments.map((expected, index) => {
|
|
839
|
+
const resolved = readRecord(ownData(raw.attachments, String(index), code), ["ref", "bytes"], [], code);
|
|
840
|
+
if (!sameRef(expected, validateAttachmentRef(resolved.ref, code))) invalid(code);
|
|
841
|
+
return Object.freeze({ ref: expected, bytes: copyAttachmentBytes(expected, resolved.bytes, code) });
|
|
842
|
+
});
|
|
843
|
+
return Object.freeze({
|
|
844
|
+
jobId,
|
|
845
|
+
attemptId,
|
|
846
|
+
snapshot,
|
|
847
|
+
attachments: Object.freeze(attachments)
|
|
848
|
+
});
|
|
849
|
+
}
|
|
850
|
+
function readProviderCall(input) {
|
|
851
|
+
const code = "invalid_config";
|
|
852
|
+
const raw = readRecord(input, ["signal", "timeoutMs"], [], code);
|
|
853
|
+
const bounds = { ...WORKER_LIMIT_BOUNDS.providerTimeoutMs, min: 1 };
|
|
854
|
+
const timeoutMs = integer(raw.timeoutMs, bounds.min, bounds.max, code);
|
|
855
|
+
const { signal } = readCallOptions(raw, bounds);
|
|
856
|
+
if (!signal) invalid(code);
|
|
857
|
+
return { timeoutMs, signal };
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
// src/providers/smtp/mime.ts
|
|
861
|
+
var import_mail_composer = __toESM(require("nodemailer/lib/mail-composer"));
|
|
862
|
+
var import_mime_funcs = require("nodemailer/lib/mime-funcs");
|
|
863
|
+
function body(content) {
|
|
864
|
+
if (content !== void 0) return { content: Buffer.from(content, "utf8"), contentTransferEncoding: "base64" };
|
|
865
|
+
}
|
|
866
|
+
function addressHeader({ address, name }) {
|
|
867
|
+
return name ? `${(0, import_mime_funcs.encodeWord)(name, "B", 64)} <${address}>` : address;
|
|
868
|
+
}
|
|
869
|
+
function prepareSmtpMessage({
|
|
870
|
+
snapshot,
|
|
871
|
+
attemptId,
|
|
872
|
+
attachments
|
|
873
|
+
}) {
|
|
874
|
+
const { from, to, cc, replyTo } = snapshot.envelope;
|
|
875
|
+
const destinations = recipientGroups.flatMap(
|
|
876
|
+
(group) => snapshot.envelope[group].map(({ address }, index) => Object.freeze({ address, group, index }))
|
|
877
|
+
);
|
|
878
|
+
const messageId = smtpMessageId(attemptId);
|
|
879
|
+
try {
|
|
880
|
+
const mime = new import_mail_composer.default({
|
|
881
|
+
// Give the composer its own mutable address objects. It never sees Bcc or chooses the wire envelope.
|
|
882
|
+
from: { ...from },
|
|
883
|
+
...to.length ? { to: to.map((mailbox) => ({ ...mailbox })) } : {},
|
|
884
|
+
...cc.length ? { cc: cc.map((mailbox) => ({ ...mailbox })) } : {},
|
|
885
|
+
replyTo: replyTo && { ...replyTo },
|
|
886
|
+
subject: (0, import_mime_funcs.encodeWord)(snapshot.subject, "B", 64),
|
|
887
|
+
text: body(snapshot.text),
|
|
888
|
+
html: body(snapshot.html),
|
|
889
|
+
date: new Date(snapshot.preparedAt),
|
|
890
|
+
messageId,
|
|
891
|
+
attachments: attachments.map(({ ref, bytes }) => {
|
|
892
|
+
if (/^(?:multipart|message)\//.test(ref.contentType)) invalid("invalid_snapshot");
|
|
893
|
+
return {
|
|
894
|
+
filename: ref.filename,
|
|
895
|
+
contentType: ref.contentType,
|
|
896
|
+
content: Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength),
|
|
897
|
+
contentDisposition: "attachment",
|
|
898
|
+
contentTransferEncoding: "base64"
|
|
899
|
+
};
|
|
900
|
+
}),
|
|
901
|
+
disableFileAccess: true,
|
|
902
|
+
disableUrlAccess: true,
|
|
903
|
+
newline: "win"
|
|
904
|
+
}).compile();
|
|
905
|
+
const addresses = new Map([
|
|
906
|
+
["From", addressHeader(from)],
|
|
907
|
+
["To", to.map(addressHeader).join(", ")],
|
|
908
|
+
["Cc", cc.map(addressHeader).join(", ")],
|
|
909
|
+
...replyTo ? [["Reply-To", addressHeader(replyTo)]] : []
|
|
910
|
+
]);
|
|
911
|
+
const encode = mime.encodeHeaderValue.bind(mime);
|
|
912
|
+
mime.encodeHeaderValue = (key, value) => addresses.get(key) ?? encode(key, value);
|
|
913
|
+
return Object.freeze({
|
|
914
|
+
from: from.address,
|
|
915
|
+
destinations: Object.freeze(destinations),
|
|
916
|
+
messageId,
|
|
917
|
+
openMimeStream: () => mime.createReadStream()
|
|
918
|
+
});
|
|
919
|
+
} catch {
|
|
920
|
+
return invalid("invalid_snapshot");
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
// src/providers/smtp/options.ts
|
|
925
|
+
var import_node_crypto2 = require("crypto");
|
|
926
|
+
var import_node_net2 = require("net");
|
|
927
|
+
var import_node_tls = require("tls");
|
|
928
|
+
var CONFIG = "invalid_config";
|
|
929
|
+
var DNS_LABEL2 = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/;
|
|
930
|
+
var MAX_CERTIFICATES = 16;
|
|
931
|
+
var MAX_PEM_BYTES = 16 * 1024;
|
|
932
|
+
var MAX_CREDENTIAL_BYTES = 1024;
|
|
933
|
+
function dnsName(value) {
|
|
934
|
+
return value.split(".").every((part) => DNS_LABEL2.test(part));
|
|
935
|
+
}
|
|
936
|
+
function caCertificate(input) {
|
|
937
|
+
const pem = utf8String(input, MAX_PEM_BYTES, CONFIG);
|
|
938
|
+
const match = /^-----BEGIN CERTIFICATE-----\r?\n([A-Za-z0-9+/=]+(?:\r?\n[A-Za-z0-9+/=]+)*)\r?\n-----END CERTIFICATE-----(?:\r?\n)?(?![\s\S])/.exec(
|
|
939
|
+
pem
|
|
940
|
+
);
|
|
941
|
+
if (!match?.[1]) invalid(CONFIG);
|
|
942
|
+
const base64 = match[1].replace(/\r?\n/g, "");
|
|
943
|
+
const der = Buffer.from(base64, "base64");
|
|
944
|
+
if (!der.length || der.toString("base64") !== base64) invalid(CONFIG);
|
|
945
|
+
try {
|
|
946
|
+
const cert = new import_node_crypto2.X509Certificate(der);
|
|
947
|
+
if (cert.ca && cert.raw.equals(der)) return cert.toString();
|
|
948
|
+
} catch {
|
|
949
|
+
}
|
|
950
|
+
return invalid(CONFIG);
|
|
951
|
+
}
|
|
952
|
+
function readAuth(input) {
|
|
953
|
+
const fields = readRecord(input, ["user", "pass"], [], CONFIG);
|
|
954
|
+
const user = headerString(fields.user, MAX_CREDENTIAL_BYTES, CONFIG);
|
|
955
|
+
const pass = headerString(fields.pass, MAX_CREDENTIAL_BYTES, CONFIG);
|
|
956
|
+
if (!user.trim() || !pass) invalid(CONFIG);
|
|
957
|
+
return Object.freeze({ user, pass });
|
|
958
|
+
}
|
|
959
|
+
function readSmtpConfig(input) {
|
|
960
|
+
const raw = readRecord(input, ["key", "host", "tls"], ["port", "servername", "ca", "auth"], CONFIG);
|
|
961
|
+
const ref = Object.freeze({ kind: "smtp", key: identifier(raw.key, CONFIG), mode: "live" });
|
|
962
|
+
const { tls } = raw;
|
|
963
|
+
if (tls !== "implicit" && tls !== "starttls") invalid(CONFIG);
|
|
964
|
+
const host = headerString(raw.host, 253, CONFIG);
|
|
965
|
+
const ip = (0, import_node_net2.isIP)(host);
|
|
966
|
+
if (host.includes("%") || !ip && !dnsName(host)) invalid(CONFIG);
|
|
967
|
+
const port = Object.hasOwn(raw, "port") ? integer(raw.port, 1, 65535, CONFIG) : SMTP_DEFAULT_PORTS[tls];
|
|
968
|
+
const servername = Object.hasOwn(raw, "servername") ? headerString(raw.servername, 253, CONFIG) : ip ? void 0 : host;
|
|
969
|
+
if (servername !== void 0 && ((0, import_node_net2.isIP)(servername) || !dnsName(servername))) invalid(CONFIG);
|
|
970
|
+
const auth = Object.hasOwn(raw, "auth") ? readAuth(raw.auth) : void 0;
|
|
971
|
+
const ca = Object.hasOwn(raw, "ca") ? readArray(raw.ca, MAX_CERTIFICATES, CONFIG, caCertificate) : void 0;
|
|
972
|
+
if (ca?.length === 0) invalid(CONFIG);
|
|
973
|
+
try {
|
|
974
|
+
const secureContext = (0, import_node_tls.createSecureContext)({ minVersion: SMTP_MIN_TLS_VERSION, ...ca ? { ca: [...ca] } : {} });
|
|
975
|
+
return Object.freeze({ ref, host, port, tls, identity: servername ?? host, servername, secureContext, auth });
|
|
976
|
+
} catch {
|
|
977
|
+
return invalid(CONFIG);
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
// src/providers/smtp/connection.ts
|
|
982
|
+
var import_node_dns = require("dns");
|
|
983
|
+
var import_node_events2 = require("events");
|
|
984
|
+
var import_node_net3 = require("net");
|
|
985
|
+
var import_node_tls2 = require("tls");
|
|
986
|
+
|
|
987
|
+
// src/providers/smtp/reply.ts
|
|
988
|
+
var MAX_LINE = 512;
|
|
989
|
+
var MAX_REPLY = 16 * 1024;
|
|
990
|
+
var REPLY_LINE = /^([2-5][0-5]\d)(?:([- ])([\t\x20-\x7e\x80-\xff]*))?(?![\s\S])/;
|
|
991
|
+
var SmtpReplyReader = class {
|
|
992
|
+
#pending = "";
|
|
993
|
+
#size = 0;
|
|
994
|
+
#code;
|
|
995
|
+
#lines = [];
|
|
996
|
+
push(chunk) {
|
|
997
|
+
this.#size += chunk.length;
|
|
998
|
+
if (this.#size > MAX_REPLY) throw new Error("Invalid SMTP reply");
|
|
999
|
+
const data = this.#pending + chunk.toString("latin1");
|
|
1000
|
+
let start = 0;
|
|
1001
|
+
for (let end = data.indexOf("\n"); end !== -1; end = data.indexOf("\n", start)) {
|
|
1002
|
+
if (end - start + 1 > MAX_LINE || data[end - 1] !== "\r") throw new Error("Invalid SMTP reply");
|
|
1003
|
+
const match = REPLY_LINE.exec(data.slice(start, end - 1));
|
|
1004
|
+
const code = Number(match?.[1]);
|
|
1005
|
+
if (!match || this.#code !== void 0 && this.#code !== code) throw new Error("Invalid SMTP reply");
|
|
1006
|
+
this.#code = code;
|
|
1007
|
+
this.#lines.push(match[3] ?? "");
|
|
1008
|
+
start = end + 1;
|
|
1009
|
+
if (match[2] !== "-") {
|
|
1010
|
+
if (start !== data.length) throw new Error("Unexpected SMTP bytes");
|
|
1011
|
+
return { code, lines: this.#lines };
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
this.#pending = data.slice(start);
|
|
1015
|
+
if (this.#pending.length >= MAX_LINE) throw new Error("Invalid SMTP reply");
|
|
1016
|
+
}
|
|
1017
|
+
};
|
|
1018
|
+
|
|
1019
|
+
// src/providers/smtp/connection.ts
|
|
1020
|
+
var SmtpFailure = class extends Error {
|
|
1021
|
+
constructor(reason) {
|
|
1022
|
+
super("SMTP submission stopped.");
|
|
1023
|
+
this.reason = reason;
|
|
1024
|
+
}
|
|
1025
|
+
reason;
|
|
1026
|
+
};
|
|
1027
|
+
var systemResolver = (timeout) => new import_node_dns.Resolver({ timeout, tries: 1 });
|
|
1028
|
+
var transientNetwork = /* @__PURE__ */ new Set([
|
|
1029
|
+
"EAI_AGAIN",
|
|
1030
|
+
"ECONNABORTED",
|
|
1031
|
+
"ECONNREFUSED",
|
|
1032
|
+
"ECONNRESET",
|
|
1033
|
+
"EHOSTUNREACH",
|
|
1034
|
+
"ENETDOWN",
|
|
1035
|
+
"ENETUNREACH",
|
|
1036
|
+
"EPIPE",
|
|
1037
|
+
"ESERVFAIL",
|
|
1038
|
+
"ETIMEOUT",
|
|
1039
|
+
"ETIMEDOUT"
|
|
1040
|
+
]);
|
|
1041
|
+
var invalidCertificate = /* @__PURE__ */ new Set([
|
|
1042
|
+
"CERT_HAS_EXPIRED",
|
|
1043
|
+
"CERT_NOT_YET_VALID",
|
|
1044
|
+
"DEPTH_ZERO_SELF_SIGNED_CERT",
|
|
1045
|
+
"ERR_TLS_CERT_ALTNAME_INVALID",
|
|
1046
|
+
"SELF_SIGNED_CERT_IN_CHAIN",
|
|
1047
|
+
"UNABLE_TO_GET_ISSUER_CERT",
|
|
1048
|
+
"UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
|
|
1049
|
+
"UNABLE_TO_VERIFY_LEAF_SIGNATURE",
|
|
1050
|
+
"ERR_SSL_UNSUPPORTED_PROTOCOL",
|
|
1051
|
+
"ERR_SSL_TLSV1_ALERT_PROTOCOL_VERSION"
|
|
1052
|
+
]);
|
|
1053
|
+
function errorCode(error) {
|
|
1054
|
+
return error?.code ?? "";
|
|
1055
|
+
}
|
|
1056
|
+
function dotStuff(bytes, atLineStart) {
|
|
1057
|
+
const parts = [];
|
|
1058
|
+
let start = 0;
|
|
1059
|
+
for (let i = bytes.indexOf(46); i !== -1; i = bytes.indexOf(46, i + 1)) {
|
|
1060
|
+
if (i === 0 ? atLineStart : bytes[i - 1] === 10) {
|
|
1061
|
+
parts.push(bytes.subarray(start, i + 1), bytes.subarray(i, i + 1));
|
|
1062
|
+
start = i + 1;
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
return start === 0 ? bytes : Buffer.concat([...parts, bytes.subarray(start)]);
|
|
1066
|
+
}
|
|
1067
|
+
var SmtpConnection = class {
|
|
1068
|
+
constructor(config, call, resolverFactory = systemResolver) {
|
|
1069
|
+
this.config = config;
|
|
1070
|
+
this.resolverFactory = resolverFactory;
|
|
1071
|
+
this.#budget = createBudget(systemEmailClock, call.timeoutMs, call.signal);
|
|
1072
|
+
if (this.#budget.signal.aborted) this.#onStop();
|
|
1073
|
+
else this.#abortListener = (0, import_node_events2.addAbortListener)(this.#budget.signal, this.#onStop);
|
|
1074
|
+
}
|
|
1075
|
+
config;
|
|
1076
|
+
resolverFactory;
|
|
1077
|
+
stage = "connect";
|
|
1078
|
+
permanentRcptRefusal = false;
|
|
1079
|
+
#budget;
|
|
1080
|
+
#abortListener;
|
|
1081
|
+
#failure;
|
|
1082
|
+
#resolver;
|
|
1083
|
+
#plain;
|
|
1084
|
+
#tls;
|
|
1085
|
+
#wire;
|
|
1086
|
+
#readerSocket;
|
|
1087
|
+
#readReply;
|
|
1088
|
+
#rejectPending;
|
|
1089
|
+
#stream;
|
|
1090
|
+
#bodyStarted = false;
|
|
1091
|
+
#partialReply = false;
|
|
1092
|
+
#onStop = () => {
|
|
1093
|
+
const reason = this.#budget.signal.reason;
|
|
1094
|
+
const code = reason?.code;
|
|
1095
|
+
this.#fail(
|
|
1096
|
+
code === "deadline" ? "provider_timeout" : code === "aborted" ? "provider_aborted" : "transport_uncertain"
|
|
1097
|
+
);
|
|
1098
|
+
};
|
|
1099
|
+
#fail(reason) {
|
|
1100
|
+
if (this.#failure) return;
|
|
1101
|
+
this.#failure = new SmtpFailure(reason);
|
|
1102
|
+
this.#abortListener?.[Symbol.dispose]();
|
|
1103
|
+
this.#budget.close();
|
|
1104
|
+
this.#readReply = void 0;
|
|
1105
|
+
this.#readerSocket?.off("data", this.#onData);
|
|
1106
|
+
const resolver = this.#resolver;
|
|
1107
|
+
this.#resolver = void 0;
|
|
1108
|
+
resolver?.cancel();
|
|
1109
|
+
this.#stream?.destroy();
|
|
1110
|
+
this.#stream = void 0;
|
|
1111
|
+
this.#tls?.destroy();
|
|
1112
|
+
this.#plain?.destroy();
|
|
1113
|
+
this.#rejectPending?.(this.#failure);
|
|
1114
|
+
this.#rejectPending = void 0;
|
|
1115
|
+
}
|
|
1116
|
+
close() {
|
|
1117
|
+
this.#fail("transport_uncertain");
|
|
1118
|
+
}
|
|
1119
|
+
#check() {
|
|
1120
|
+
if (this.#failure) throw this.#failure;
|
|
1121
|
+
try {
|
|
1122
|
+
this.#budget.check();
|
|
1123
|
+
} catch {
|
|
1124
|
+
this.#onStop();
|
|
1125
|
+
throw this.#failure ?? new SmtpFailure("transport_uncertain");
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
#live() {
|
|
1129
|
+
try {
|
|
1130
|
+
this.#check();
|
|
1131
|
+
return true;
|
|
1132
|
+
} catch {
|
|
1133
|
+
return false;
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
#wait(start) {
|
|
1137
|
+
this.#check();
|
|
1138
|
+
return new Promise((resolve, reject) => {
|
|
1139
|
+
this.#rejectPending = reject;
|
|
1140
|
+
try {
|
|
1141
|
+
start((value) => {
|
|
1142
|
+
if (this.#rejectPending !== reject || !this.#live()) return;
|
|
1143
|
+
this.#rejectPending = void 0;
|
|
1144
|
+
resolve(value);
|
|
1145
|
+
});
|
|
1146
|
+
} catch {
|
|
1147
|
+
this.#fail("transport_uncertain");
|
|
1148
|
+
}
|
|
1149
|
+
});
|
|
1150
|
+
}
|
|
1151
|
+
#resolve() {
|
|
1152
|
+
if ((0, import_node_net3.isIP)(this.config.host)) return Promise.resolve(this.config.host);
|
|
1153
|
+
return this.#wait((done) => {
|
|
1154
|
+
const resolver = this.resolverFactory(Math.ceil(this.#budget.remainingMs()));
|
|
1155
|
+
this.#resolver = resolver;
|
|
1156
|
+
let pending = 2;
|
|
1157
|
+
const errors = [];
|
|
1158
|
+
const onResolved = (error, addresses) => {
|
|
1159
|
+
if (this.#resolver !== resolver || !this.#live()) return;
|
|
1160
|
+
const address = !error && addresses?.find((value) => (0, import_node_net3.isIP)(value) !== 0);
|
|
1161
|
+
if (address) {
|
|
1162
|
+
this.#resolver = void 0;
|
|
1163
|
+
resolver.cancel();
|
|
1164
|
+
done(address);
|
|
1165
|
+
} else {
|
|
1166
|
+
errors.push(errorCode(error));
|
|
1167
|
+
if (--pending !== 0) return;
|
|
1168
|
+
if (errors.some((code) => transientNetwork.has(code))) this.#fail("not_transmitted");
|
|
1169
|
+
else if (errors.every((code) => !code || code === "ENODATA" || code === "ENOTFOUND")) {
|
|
1170
|
+
this.#fail("provider_configuration");
|
|
1171
|
+
} else this.#fail("transport_uncertain");
|
|
1172
|
+
}
|
|
1173
|
+
};
|
|
1174
|
+
resolver.resolve4(this.config.host, onResolved);
|
|
1175
|
+
if (this.#resolver === resolver) resolver.resolve6(this.config.host, onResolved);
|
|
1176
|
+
});
|
|
1177
|
+
}
|
|
1178
|
+
#networkFailure(socket, code) {
|
|
1179
|
+
if (this.#wire !== socket || !this.#live()) return;
|
|
1180
|
+
if (this.stage === "tls" && socket === this.#tls && invalidCertificate.has(code)) {
|
|
1181
|
+
this.#fail("provider_configuration");
|
|
1182
|
+
} else if (!this.#bodyStarted && !this.#partialReply && !this.permanentRcptRefusal && (!code || transientNetwork.has(code))) {
|
|
1183
|
+
this.#fail("not_transmitted");
|
|
1184
|
+
} else this.#fail("transport_uncertain");
|
|
1185
|
+
}
|
|
1186
|
+
#watch(socket) {
|
|
1187
|
+
socket.on("error", (error) => this.#networkFailure(socket, errorCode(error) || "OTHER"));
|
|
1188
|
+
socket.once("end", () => this.#networkFailure(socket, ""));
|
|
1189
|
+
socket.once("close", () => this.#networkFailure(socket, ""));
|
|
1190
|
+
}
|
|
1191
|
+
async connect() {
|
|
1192
|
+
const host = await this.#resolve();
|
|
1193
|
+
await this.#wait((done) => {
|
|
1194
|
+
const socket = (0, import_node_net3.connect)({ host, port: this.config.port, family: (0, import_node_net3.isIP)(host), autoSelectFamily: false });
|
|
1195
|
+
this.#plain = this.#wire = socket;
|
|
1196
|
+
this.#watch(socket);
|
|
1197
|
+
socket.setNoDelay(true);
|
|
1198
|
+
socket.once("connect", () => done());
|
|
1199
|
+
});
|
|
1200
|
+
}
|
|
1201
|
+
async startTls() {
|
|
1202
|
+
this.stage = "tls";
|
|
1203
|
+
await this.#wait((done) => {
|
|
1204
|
+
const socket = this.#plain;
|
|
1205
|
+
socket.off("data", this.#onData);
|
|
1206
|
+
const secured = (0, import_node_tls2.connect)({
|
|
1207
|
+
socket,
|
|
1208
|
+
secureContext: this.config.secureContext,
|
|
1209
|
+
...this.config.servername ? { servername: this.config.servername } : {},
|
|
1210
|
+
rejectUnauthorized: true,
|
|
1211
|
+
// Verify the configured identity, not a resolved address or a name proposed by the relay.
|
|
1212
|
+
checkServerIdentity: (_servername, cert) => (0, import_node_tls2.checkServerIdentity)(this.config.identity, cert)
|
|
1213
|
+
});
|
|
1214
|
+
this.#tls = this.#wire = secured;
|
|
1215
|
+
this.#watch(secured);
|
|
1216
|
+
secured.once("secureConnect", () => {
|
|
1217
|
+
if (!this.#live()) return;
|
|
1218
|
+
if (!secured.authorized) return this.#fail("provider_configuration");
|
|
1219
|
+
done();
|
|
1220
|
+
});
|
|
1221
|
+
});
|
|
1222
|
+
}
|
|
1223
|
+
#onData = (chunk) => {
|
|
1224
|
+
if (!this.#live()) return;
|
|
1225
|
+
if (!this.#readReply) this.#fail("transport_uncertain");
|
|
1226
|
+
else this.#readReply(chunk);
|
|
1227
|
+
};
|
|
1228
|
+
#reply(command) {
|
|
1229
|
+
const reader = new SmtpReplyReader();
|
|
1230
|
+
return this.#wait((done) => {
|
|
1231
|
+
this.#readReply = (chunk) => {
|
|
1232
|
+
try {
|
|
1233
|
+
const reply = reader.push(chunk);
|
|
1234
|
+
this.#partialReply = !reply;
|
|
1235
|
+
if (reply) {
|
|
1236
|
+
this.#readReply = void 0;
|
|
1237
|
+
done(reply);
|
|
1238
|
+
}
|
|
1239
|
+
} catch {
|
|
1240
|
+
this.#fail("transport_uncertain");
|
|
1241
|
+
}
|
|
1242
|
+
};
|
|
1243
|
+
const socket = this.#wire;
|
|
1244
|
+
if (socket !== this.#readerSocket) {
|
|
1245
|
+
this.#readerSocket = socket;
|
|
1246
|
+
socket.on("data", this.#onData);
|
|
1247
|
+
}
|
|
1248
|
+
if (command !== void 0) this.#write(`${command}\r
|
|
1249
|
+
`);
|
|
1250
|
+
});
|
|
1251
|
+
}
|
|
1252
|
+
greeting() {
|
|
1253
|
+
return this.#reply();
|
|
1254
|
+
}
|
|
1255
|
+
#write(value, done) {
|
|
1256
|
+
this.#check();
|
|
1257
|
+
const socket = this.#wire;
|
|
1258
|
+
socket.write(value, (error) => {
|
|
1259
|
+
if (error) this.#networkFailure(socket, errorCode(error) || "OTHER");
|
|
1260
|
+
else done?.();
|
|
1261
|
+
});
|
|
1262
|
+
}
|
|
1263
|
+
command(command) {
|
|
1264
|
+
return this.#reply(command);
|
|
1265
|
+
}
|
|
1266
|
+
/** Never listen for a final acceptance until the complete MIME stream can be terminated. */
|
|
1267
|
+
async data(openMimeStream) {
|
|
1268
|
+
this.#check();
|
|
1269
|
+
this.#bodyStarted = true;
|
|
1270
|
+
this.#stream = openMimeStream();
|
|
1271
|
+
let tail = 10;
|
|
1272
|
+
for await (const value of this.#stream) {
|
|
1273
|
+
for (let offset = 0; offset < value.length; offset += 16384) {
|
|
1274
|
+
this.#check();
|
|
1275
|
+
const bytes = value.subarray(offset, offset + 16384);
|
|
1276
|
+
const stuffed = dotStuff(bytes, (tail & 255) === 10);
|
|
1277
|
+
const last = bytes[bytes.length - 1];
|
|
1278
|
+
const before = bytes.length === 1 ? tail & 255 : bytes[bytes.length - 2];
|
|
1279
|
+
tail = before << 8 | last;
|
|
1280
|
+
await this.#wait((done) => this.#write(stuffed, done));
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
this.#stream = void 0;
|
|
1284
|
+
if (tail !== 3338) throw new SmtpFailure("transport_uncertain");
|
|
1285
|
+
return this.#reply(".");
|
|
1286
|
+
}
|
|
1287
|
+
get failure() {
|
|
1288
|
+
return this.#failure;
|
|
1289
|
+
}
|
|
1290
|
+
};
|
|
1291
|
+
|
|
1292
|
+
// src/providers/smtp/submit.ts
|
|
1293
|
+
function failed(stage, reason) {
|
|
1294
|
+
if (reason === "not_transmitted") return { outcome: "unsubmitted", retry: "safe_transient", stage, reason };
|
|
1295
|
+
if (reason === "provider_configuration") return { outcome: "unsubmitted", retry: "never", stage, reason };
|
|
1296
|
+
return { outcome: "unknown", retry: "never", stage, reason };
|
|
1297
|
+
}
|
|
1298
|
+
function negative(stage, code, permanentRcptRefusal = false, recipients = []) {
|
|
1299
|
+
if (code < 400 || code > 599) throw new SmtpFailure("transport_uncertain");
|
|
1300
|
+
const permanent = code >= 500 || permanentRcptRefusal;
|
|
1301
|
+
return {
|
|
1302
|
+
outcome: "rejected",
|
|
1303
|
+
retry: permanent ? "never" : "safe_transient",
|
|
1304
|
+
stage,
|
|
1305
|
+
reason: permanent ? "smtp_permanent_reply" : "smtp_transient_reply",
|
|
1306
|
+
...recipients.length ? { recipients } : {}
|
|
1307
|
+
};
|
|
1308
|
+
}
|
|
1309
|
+
function extensions({ lines }) {
|
|
1310
|
+
let starttls = false;
|
|
1311
|
+
const mechanisms = /* @__PURE__ */ new Set();
|
|
1312
|
+
for (const line of lines.slice(1)) {
|
|
1313
|
+
const [keyword, ...args] = line.trimEnd().toUpperCase().split(/[ \t=]+/);
|
|
1314
|
+
if (keyword === "STARTTLS" && args.length === 0) starttls = true;
|
|
1315
|
+
if (keyword === "AUTH") for (const mechanism of args) mechanisms.add(mechanism);
|
|
1316
|
+
}
|
|
1317
|
+
return { starttls, mechanisms };
|
|
1318
|
+
}
|
|
1319
|
+
async function authenticate(connection, { user, pass }, mechanisms) {
|
|
1320
|
+
connection.stage = "auth";
|
|
1321
|
+
let response;
|
|
1322
|
+
if (mechanisms.has("PLAIN")) {
|
|
1323
|
+
const encoded = Buffer.from(`\0${user}\0${pass}`, "utf8").toString("base64");
|
|
1324
|
+
const command = `AUTH PLAIN ${encoded}`;
|
|
1325
|
+
if (command.length <= 510) response = await connection.command(command);
|
|
1326
|
+
else {
|
|
1327
|
+
response = await connection.command("AUTH PLAIN");
|
|
1328
|
+
if (response.code !== 334) return negative("auth", response.code);
|
|
1329
|
+
response = await connection.command(encoded);
|
|
1330
|
+
}
|
|
1331
|
+
} else if (mechanisms.has("LOGIN")) {
|
|
1332
|
+
response = await connection.command("AUTH LOGIN");
|
|
1333
|
+
if (response.code !== 334) return negative("auth", response.code);
|
|
1334
|
+
response = await connection.command(Buffer.from(user, "utf8").toString("base64"));
|
|
1335
|
+
if (response.code !== 334) return negative("auth", response.code);
|
|
1336
|
+
response = await connection.command(Buffer.from(pass, "utf8").toString("base64"));
|
|
1337
|
+
} else return failed("auth", "provider_configuration");
|
|
1338
|
+
if (response.code !== 235) return negative("auth", response.code);
|
|
1339
|
+
}
|
|
1340
|
+
async function exchange(connection, config, message) {
|
|
1341
|
+
await connection.connect();
|
|
1342
|
+
if (config.tls === "implicit") await connection.startTls();
|
|
1343
|
+
connection.stage = "connect";
|
|
1344
|
+
const greeting = await connection.greeting();
|
|
1345
|
+
if (greeting.code !== 220) return negative("connect", greeting.code);
|
|
1346
|
+
let ehlo = await connection.command("EHLO email.invalid");
|
|
1347
|
+
if (ehlo.code !== 250) return negative("connect", ehlo.code);
|
|
1348
|
+
if (config.tls === "starttls") {
|
|
1349
|
+
connection.stage = "tls";
|
|
1350
|
+
if (!extensions(ehlo).starttls) return failed("tls", "provider_configuration");
|
|
1351
|
+
const upgrade = await connection.command("STARTTLS");
|
|
1352
|
+
if (upgrade.code !== 220) return negative("tls", upgrade.code);
|
|
1353
|
+
await connection.startTls();
|
|
1354
|
+
ehlo = await connection.command("EHLO email.invalid");
|
|
1355
|
+
if (ehlo.code !== 250) return negative("tls", ehlo.code);
|
|
1356
|
+
}
|
|
1357
|
+
if (config.auth) {
|
|
1358
|
+
const failure = await authenticate(connection, config.auth, extensions(ehlo).mechanisms);
|
|
1359
|
+
if (failure) return failure;
|
|
1360
|
+
}
|
|
1361
|
+
connection.stage = "envelope";
|
|
1362
|
+
let { code } = await connection.command(`MAIL FROM:<${message.from}>`);
|
|
1363
|
+
if (code !== 250) return negative("envelope", code);
|
|
1364
|
+
const recipients = [];
|
|
1365
|
+
let accepted = 0;
|
|
1366
|
+
for (const { address, group, index } of message.destinations) {
|
|
1367
|
+
({ code } = await connection.command(`RCPT TO:<${address}>`));
|
|
1368
|
+
if (code === 250 || code === 251) {
|
|
1369
|
+
accepted++;
|
|
1370
|
+
recipients.push({ group, index, status: "accepted" });
|
|
1371
|
+
} else if (code >= 400 && code <= 599) {
|
|
1372
|
+
connection.permanentRcptRefusal ||= code >= 500;
|
|
1373
|
+
recipients.push({ group, index, status: "rejected" });
|
|
1374
|
+
if (code === 421) break;
|
|
1375
|
+
} else throw new SmtpFailure("transport_uncertain");
|
|
1376
|
+
}
|
|
1377
|
+
const rejected = recipients.filter(({ status }) => status === "rejected");
|
|
1378
|
+
if (accepted === 0 && recipients.length === message.destinations.length) {
|
|
1379
|
+
return negative("envelope", code, connection.permanentRcptRefusal, rejected);
|
|
1380
|
+
}
|
|
1381
|
+
if (code === 421) {
|
|
1382
|
+
return failed("envelope", connection.permanentRcptRefusal ? "transport_uncertain" : "not_transmitted");
|
|
1383
|
+
}
|
|
1384
|
+
connection.stage = "data";
|
|
1385
|
+
({ code } = await connection.command("DATA"));
|
|
1386
|
+
if (code !== 354) return negative("data", code, connection.permanentRcptRefusal, rejected);
|
|
1387
|
+
({ code } = await connection.data(message.openMimeStream));
|
|
1388
|
+
if (code !== 250) return negative("data", code, connection.permanentRcptRefusal, rejected);
|
|
1389
|
+
return {
|
|
1390
|
+
outcome: rejected.length ? "partially_accepted" : "accepted",
|
|
1391
|
+
retry: "never",
|
|
1392
|
+
stage: "data",
|
|
1393
|
+
reason: rejected.length ? "smtp_partial" : "smtp_accepted",
|
|
1394
|
+
messageId: message.messageId,
|
|
1395
|
+
recipients
|
|
1396
|
+
};
|
|
1397
|
+
}
|
|
1398
|
+
async function submitSmtp(config, message, call, resolverFactory) {
|
|
1399
|
+
const connection = new SmtpConnection(config, call, resolverFactory);
|
|
1400
|
+
try {
|
|
1401
|
+
return await exchange(connection, config, message);
|
|
1402
|
+
} catch (error) {
|
|
1403
|
+
const failure = connection.failure ?? (error instanceof SmtpFailure ? error : void 0);
|
|
1404
|
+
return failed(connection.stage, failure?.reason ?? "transport_uncertain");
|
|
1405
|
+
} finally {
|
|
1406
|
+
connection.close();
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
|
|
1410
|
+
// src/smtp.ts
|
|
1411
|
+
function createSmtpProvider(options) {
|
|
1412
|
+
const config = readSmtpConfig(options);
|
|
1413
|
+
const { ref } = config;
|
|
1414
|
+
const provider = {
|
|
1415
|
+
ref,
|
|
1416
|
+
prepare(input) {
|
|
1417
|
+
const prepared = readProviderSubmission(input, ref);
|
|
1418
|
+
const {
|
|
1419
|
+
attemptId,
|
|
1420
|
+
snapshot: { envelope }
|
|
1421
|
+
} = prepared;
|
|
1422
|
+
let message = prepareSmtpMessage(prepared);
|
|
1423
|
+
return Object.freeze({
|
|
1424
|
+
async submit(context) {
|
|
1425
|
+
if (!message) invalid("closed");
|
|
1426
|
+
const call = readProviderCall(context);
|
|
1427
|
+
const send = message;
|
|
1428
|
+
message = void 0;
|
|
1429
|
+
const result = await submitSmtp(config, send, call);
|
|
1430
|
+
try {
|
|
1431
|
+
return readProviderResult(result, ref, attemptId, envelope);
|
|
1432
|
+
} catch {
|
|
1433
|
+
return readProviderResult(
|
|
1434
|
+
{ outcome: "unknown", retry: "never", stage: result.stage, reason: "transport_uncertain" },
|
|
1435
|
+
ref,
|
|
1436
|
+
attemptId,
|
|
1437
|
+
envelope
|
|
1438
|
+
);
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
});
|
|
1442
|
+
}
|
|
1443
|
+
};
|
|
1444
|
+
return Object.freeze(provider);
|
|
1445
|
+
}
|
|
1446
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
1447
|
+
0 && (module.exports = {
|
|
1448
|
+
createSmtpProvider
|
|
1449
|
+
});
|