@mailpier/inbox 0.0.0-stage → 0.1.1
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 +24 -0
- package/LICENSE +21 -0
- package/README.md +159 -2
- package/dist/chunk-2NMZ2IWD.js +524 -0
- package/dist/cli.cjs +751 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +244 -0
- package/dist/client-DD8Tr4-3.d.cts +415 -0
- package/dist/client-DD8Tr4-3.d.ts +415 -0
- package/dist/cypress/commands.cjs +94 -0
- package/dist/cypress/commands.d.cts +58 -0
- package/dist/cypress/commands.d.ts +58 -0
- package/dist/cypress/commands.js +68 -0
- package/dist/cypress/index.cjs +575 -0
- package/dist/cypress/index.d.cts +47 -0
- package/dist/cypress/index.d.ts +47 -0
- package/dist/cypress/index.js +40 -0
- package/dist/index.cjs +557 -0
- package/dist/index.d.cts +26 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +22 -0
- package/dist/playwright.cjs +639 -0
- package/dist/playwright.d.cts +65 -0
- package/dist/playwright.d.ts +65 -0
- package/dist/playwright.js +104 -0
- package/dist/testing/index.cjs +683 -0
- package/dist/testing/index.d.cts +106 -0
- package/dist/testing/index.d.ts +106 -0
- package/dist/testing/index.js +654 -0
- package/package.json +112 -4
|
@@ -0,0 +1,683 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/testing/index.ts
|
|
21
|
+
var testing_exports = {};
|
|
22
|
+
__export(testing_exports, {
|
|
23
|
+
findCodes: () => findCodes,
|
|
24
|
+
findLinks: () => findLinks,
|
|
25
|
+
startFakeMailPier: () => startFakeMailPier
|
|
26
|
+
});
|
|
27
|
+
module.exports = __toCommonJS(testing_exports);
|
|
28
|
+
|
|
29
|
+
// src/testing/fakeServer.ts
|
|
30
|
+
var import_node_http = require("http");
|
|
31
|
+
var import_node_crypto = require("crypto");
|
|
32
|
+
var MAX_TAKE = 100;
|
|
33
|
+
var GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
34
|
+
var HOOK_LIMITS = { requestsPerMonth: 1e5, maxBodyBytes: 1048576, responseRules: 50, maxDelayMs: 3e4, requestsPerSecond: 25, forward: true };
|
|
35
|
+
var HOOK_CONTENT_TYPES = ["application/json", "text/plain", "application/xml"];
|
|
36
|
+
var HOP_BY_HOP = /* @__PURE__ */ new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-connection", "te", "trailer", "transfer-encoding", "upgrade", "host"]);
|
|
37
|
+
var SECRET_HEADERS = /* @__PURE__ */ new Set([
|
|
38
|
+
"authorization",
|
|
39
|
+
"proxy-authorization",
|
|
40
|
+
"cookie",
|
|
41
|
+
"x-api-key",
|
|
42
|
+
"api-key",
|
|
43
|
+
"x-auth-token",
|
|
44
|
+
"x-access-token",
|
|
45
|
+
"x-amz-security-token"
|
|
46
|
+
]);
|
|
47
|
+
async function startFakeMailPier(options = {}) {
|
|
48
|
+
const apiKey = options.apiKey ?? "mpi_test_key";
|
|
49
|
+
const account = options.account ?? "demo";
|
|
50
|
+
const environment = options.environment ?? "qa";
|
|
51
|
+
const domains = (options.domains ?? ["mailpier.io"]).map((d) => d.toLowerCase());
|
|
52
|
+
const zoneFor = (d) => `${environment}.${account}.${d}`;
|
|
53
|
+
const zones = domains.map(zoneFor);
|
|
54
|
+
const zone = zones[0];
|
|
55
|
+
let seq = 0;
|
|
56
|
+
let store = [];
|
|
57
|
+
let failures = [];
|
|
58
|
+
const waiters = /* @__PURE__ */ new Set();
|
|
59
|
+
const requests = [];
|
|
60
|
+
const inEnv = (address) => {
|
|
61
|
+
const a = address.trim().toLowerCase();
|
|
62
|
+
return zones.some((z) => a.endsWith(`@${z}`) || a.endsWith(`.${z}`));
|
|
63
|
+
};
|
|
64
|
+
function deliver(mail) {
|
|
65
|
+
const recipients = (Array.isArray(mail.to) ? mail.to : [mail.to]).map((t) => t.trim()).filter(Boolean);
|
|
66
|
+
if (recipients.length === 0) throw new Error("deliver needs at least one recipient.");
|
|
67
|
+
const id = (0, import_node_crypto.randomUUID)();
|
|
68
|
+
const attachments = (mail.attachments ?? []).map((a) => ({
|
|
69
|
+
fileName: a.fileName,
|
|
70
|
+
contentType: a.contentType ?? "application/octet-stream",
|
|
71
|
+
bytes: typeof a.content === "string" ? Buffer.from(a.content, "utf8") : Buffer.from(a.content)
|
|
72
|
+
}));
|
|
73
|
+
const raw = buildEml(id, mail, recipients, attachments);
|
|
74
|
+
store.push({
|
|
75
|
+
seq: ++seq,
|
|
76
|
+
id,
|
|
77
|
+
received: (mail.receivedUtc ?? /* @__PURE__ */ new Date()).getTime(),
|
|
78
|
+
mail,
|
|
79
|
+
to: recipients,
|
|
80
|
+
links: mail.links ?? findLinks(mail.html, mail.text),
|
|
81
|
+
codes: mail.codes ?? findCodes(mail.subject, mail.text),
|
|
82
|
+
attachments,
|
|
83
|
+
raw
|
|
84
|
+
});
|
|
85
|
+
for (const w of [...waiters]) w();
|
|
86
|
+
return id;
|
|
87
|
+
}
|
|
88
|
+
const webhooksOn = options.webhooks ?? true;
|
|
89
|
+
const token = randomLocal(20);
|
|
90
|
+
let baseUrl = "";
|
|
91
|
+
const hookUrl = () => `${baseUrl}/_fake/hook/${token}`;
|
|
92
|
+
let hookSeq = 0;
|
|
93
|
+
let ruleSeq = 0;
|
|
94
|
+
let hookCounter = 0;
|
|
95
|
+
let hooks = [];
|
|
96
|
+
let rules = [];
|
|
97
|
+
let forwardUrl = null;
|
|
98
|
+
const replays = [];
|
|
99
|
+
function matchRule(method, path) {
|
|
100
|
+
return rules.filter((r) => (r.method === null || r.method === method) && path.startsWith(r.path)).sort((a, b) => b.path.length - a.path.length || Number(b.method !== null) - Number(a.method !== null) || b.id - a.id)[0];
|
|
101
|
+
}
|
|
102
|
+
function storeHook(h) {
|
|
103
|
+
const rule = matchRule(h.method, h.path);
|
|
104
|
+
const status = rule?.status ?? (h.method === "OPTIONS" ? 204 : 200);
|
|
105
|
+
const stored = { ...h, id: ++hookSeq, status, ruleId: rule?.id ?? null };
|
|
106
|
+
hookCounter++;
|
|
107
|
+
hooks.push(stored);
|
|
108
|
+
for (const w of [...waiters]) w();
|
|
109
|
+
return { stored, rule };
|
|
110
|
+
}
|
|
111
|
+
function catchWebhook(r = {}) {
|
|
112
|
+
const method = (r.method ?? "POST").trim().toUpperCase() || "POST";
|
|
113
|
+
const path = r.path?.trim() ? r.path.startsWith("/") ? r.path : `/${r.path}` : "/";
|
|
114
|
+
const isObject = r.body !== void 0 && !(r.body instanceof Uint8Array) && typeof r.body === "object";
|
|
115
|
+
const body = r.body === void 0 ? Buffer.alloc(0) : typeof r.body === "string" ? Buffer.from(r.body, "utf8") : r.body instanceof Uint8Array ? Buffer.from(r.body) : Buffer.from(JSON.stringify(r.body), "utf8");
|
|
116
|
+
const pairs = Array.isArray(r.headers) ? r.headers.map(([n, v]) => [n, v]) : Object.entries(r.headers ?? {});
|
|
117
|
+
const contentType = r.contentType ?? pairs.find(([n]) => n.toLowerCase() === "content-type")?.[1] ?? (isObject ? "application/json" : typeof r.body === "string" ? "text/plain; charset=utf-8" : r.body ? "application/octet-stream" : void 0);
|
|
118
|
+
if (contentType && !pairs.some(([n]) => n.toLowerCase() === "content-type")) pairs.push(["Content-Type", contentType]);
|
|
119
|
+
return storeHook({
|
|
120
|
+
received: (r.receivedUtc ?? /* @__PURE__ */ new Date()).getTime(),
|
|
121
|
+
method,
|
|
122
|
+
path,
|
|
123
|
+
query: (r.query ?? "").replace(/^\?/, ""),
|
|
124
|
+
headers: maskHeaders(pairs.filter(([n]) => !HOP_BY_HOP.has(n.toLowerCase()))),
|
|
125
|
+
body,
|
|
126
|
+
contentType: contentType ?? null,
|
|
127
|
+
sourceIp: r.sourceIp ?? "203.0.113.10"
|
|
128
|
+
}).stored.id;
|
|
129
|
+
}
|
|
130
|
+
const summary = (s) => clean({
|
|
131
|
+
id: s.id,
|
|
132
|
+
receivedUtc: new Date(s.received).toISOString(),
|
|
133
|
+
from: s.mail.from ?? "sender@example.com",
|
|
134
|
+
to: s.to.filter(inEnv),
|
|
135
|
+
subject: s.mail.subject,
|
|
136
|
+
sizeBytes: s.raw.length,
|
|
137
|
+
hasAttachments: s.attachments.length > 0
|
|
138
|
+
});
|
|
139
|
+
const detail = (s) => clean({
|
|
140
|
+
...summary(s),
|
|
141
|
+
text: s.mail.text,
|
|
142
|
+
html: s.mail.html,
|
|
143
|
+
headers: clean({
|
|
144
|
+
from: clean({ name: s.mail.fromName, address: s.mail.from ?? "sender@example.com" }),
|
|
145
|
+
to: s.to.map((a) => ({ address: a })),
|
|
146
|
+
cc: [],
|
|
147
|
+
subject: s.mail.subject,
|
|
148
|
+
date: new Date(s.received).toISOString(),
|
|
149
|
+
messageId: `<${s.id}@fake.mailpier.test>`
|
|
150
|
+
}),
|
|
151
|
+
links: s.links.map((l) => clean({ href: l.href, text: l.text })),
|
|
152
|
+
codes: s.codes,
|
|
153
|
+
attachments: s.attachments.map((a, index) => ({ index, fileName: a.fileName, contentType: a.contentType, size: a.bytes.length })),
|
|
154
|
+
auth: { spf: "pass", dkim: "pass", dmarc: "pass" },
|
|
155
|
+
spam: { score: 0.1, verdict: "ham" }
|
|
156
|
+
});
|
|
157
|
+
const hookSummary = (h) => ({
|
|
158
|
+
id: h.id,
|
|
159
|
+
receivedUtc: new Date(h.received).toISOString(),
|
|
160
|
+
method: h.method,
|
|
161
|
+
path: h.path,
|
|
162
|
+
query: h.query,
|
|
163
|
+
contentType: h.contentType,
|
|
164
|
+
size: h.body.length,
|
|
165
|
+
environment,
|
|
166
|
+
status: h.status
|
|
167
|
+
});
|
|
168
|
+
const hookDetail = (h) => {
|
|
169
|
+
const text = utf8(h.body);
|
|
170
|
+
const type = (h.contentType ?? "").split(";")[0].trim().toLowerCase();
|
|
171
|
+
let json = null;
|
|
172
|
+
if (text !== void 0 && (type === "application/json" || type.endsWith("+json"))) {
|
|
173
|
+
try {
|
|
174
|
+
json = JSON.parse(text);
|
|
175
|
+
} catch {
|
|
176
|
+
json = null;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
const form = text !== void 0 && type === "application/x-www-form-urlencoded" ? Object.fromEntries(new URLSearchParams(text)) : null;
|
|
180
|
+
return {
|
|
181
|
+
...hookSummary(h),
|
|
182
|
+
url: `${hookUrl()}${h.path}${h.query ? `?${h.query}` : ""}`,
|
|
183
|
+
headers: h.headers.map(([name, value]) => ({ name, value })),
|
|
184
|
+
body: text ?? null,
|
|
185
|
+
bodyBase64: text === void 0 ? h.body.toString("base64") : null,
|
|
186
|
+
json,
|
|
187
|
+
form,
|
|
188
|
+
sourceIp: h.sourceIp,
|
|
189
|
+
headersTruncated: false,
|
|
190
|
+
ruleId: h.ruleId,
|
|
191
|
+
forwardStatus: null
|
|
192
|
+
};
|
|
193
|
+
};
|
|
194
|
+
const endpointJson = () => ({
|
|
195
|
+
url: hookUrl(),
|
|
196
|
+
paused: false,
|
|
197
|
+
hideSecrets: true,
|
|
198
|
+
forwardUrl,
|
|
199
|
+
limits: { ...HOOK_LIMITS, usedThisMonth: hookCounter }
|
|
200
|
+
});
|
|
201
|
+
const ruleJson = (r) => ({
|
|
202
|
+
id: r.id,
|
|
203
|
+
method: r.method,
|
|
204
|
+
path: r.path,
|
|
205
|
+
status: r.status,
|
|
206
|
+
contentType: r.contentType,
|
|
207
|
+
body: r.body,
|
|
208
|
+
delayMs: r.delayMs,
|
|
209
|
+
createdUtc: new Date(r.created).toISOString(),
|
|
210
|
+
inForce: true
|
|
211
|
+
});
|
|
212
|
+
function matches(f) {
|
|
213
|
+
let afterSeq = 0;
|
|
214
|
+
if (f.since !== void 0 && f.afterId) afterSeq = store.find((s) => s.id === f.afterId)?.seq ?? 0;
|
|
215
|
+
return store.filter((s) => s.to.some(inEnv) && (!f.to || s.to.some((t) => t.toLowerCase() === f.to.toLowerCase())) && (!f.subject || (s.mail.subject ?? "").toLowerCase().includes(f.subject.toLowerCase())) && (f.since === void 0 || s.received >= f.since) && s.seq > afterSeq);
|
|
216
|
+
}
|
|
217
|
+
const server = (0, import_node_http.createServer)((req, res) => {
|
|
218
|
+
handle(req, res).catch((err) => {
|
|
219
|
+
if (!res.headersSent) send(res, 500, { error: `Fake server error: ${String(err)}` });
|
|
220
|
+
else res.end();
|
|
221
|
+
});
|
|
222
|
+
});
|
|
223
|
+
async function handle(req, res) {
|
|
224
|
+
const u = new URL(req.url ?? "/", "http://fake");
|
|
225
|
+
const method = req.method ?? "GET";
|
|
226
|
+
requests.push({ method, url: u.pathname + u.search, authorization: req.headers.authorization });
|
|
227
|
+
res.setHeader("Cache-Control", "no-store");
|
|
228
|
+
if (u.pathname === "/_fake/deliver" && method === "POST") {
|
|
229
|
+
const body = await readJson(req);
|
|
230
|
+
if (!body || typeof body !== "object") return send(res, 400, { error: "JSON body required." });
|
|
231
|
+
return send(res, 201, { id: deliver(body) });
|
|
232
|
+
}
|
|
233
|
+
if (u.pathname.startsWith("/_fake/hook/")) return handleCatch(req, res, u, method);
|
|
234
|
+
if (!u.pathname.startsWith("/v1/")) return send(res, 404, { error: "Not found." });
|
|
235
|
+
const isHooks = u.pathname === "/v1/hooks" || u.pathname.startsWith("/v1/hooks/");
|
|
236
|
+
if (isHooks && !webhooksOn) return send(res, 404, { error: "Not found." });
|
|
237
|
+
if ((req.headers.authorization ?? "") !== `Bearer ${apiKey}`) {
|
|
238
|
+
res.setHeader("WWW-Authenticate", "Bearer");
|
|
239
|
+
return send(res, 401, { error: "Missing, unknown or revoked API key. Send Authorization: Bearer mpi_..." });
|
|
240
|
+
}
|
|
241
|
+
const f = failures[0];
|
|
242
|
+
if (f) {
|
|
243
|
+
if ((f.times ?? 1) <= 1) failures.shift();
|
|
244
|
+
else f.times = (f.times ?? 1) - 1;
|
|
245
|
+
if (f.retryAfter !== void 0) res.setHeader("Retry-After", String(f.retryAfter));
|
|
246
|
+
return send(res, f.status, { error: f.error ?? (f.status === 429 ? "Too many requests. Slow down and retry after the Retry-After seconds." : "The service is not available right now. Retry in a moment.") });
|
|
247
|
+
}
|
|
248
|
+
const q = u.searchParams;
|
|
249
|
+
const to = q.get("to")?.trim() || void 0;
|
|
250
|
+
if (to && !inEnv(to) && u.pathname.startsWith("/v1/messages")) {
|
|
251
|
+
return send(res, 400, { error: `${to} is not an address of environment ${environment} (${zones.map((z) => `*@${z}`).join(", ")}).` });
|
|
252
|
+
}
|
|
253
|
+
const sinceText = q.get("since");
|
|
254
|
+
let since;
|
|
255
|
+
if (sinceText) {
|
|
256
|
+
since = Date.parse(sinceText);
|
|
257
|
+
if (Number.isNaN(since)) return send(res, 400, { error: "since must be an ISO 8601 date/time." });
|
|
258
|
+
}
|
|
259
|
+
if (isHooks) return handleHooks(req, res, u, method, since);
|
|
260
|
+
const filter = { to, subject: q.get("subject") ?? void 0, since, afterId: q.get("afterId") ?? void 0 };
|
|
261
|
+
const parts = u.pathname.split("/").filter(Boolean);
|
|
262
|
+
if (u.pathname === "/v1/me" && method === "GET") {
|
|
263
|
+
return send(res, 200, {
|
|
264
|
+
account: { slug: account, name: "Demo", plan: "Team", status: "Active", monthlyQuota: 1e4, apiRequestsPerMinute: 600 },
|
|
265
|
+
environment: { name: environment, displayName: environment.toUpperCase(), retentionMinutes: 720, retentionHours: 12, isMain: environment === "main" },
|
|
266
|
+
domains,
|
|
267
|
+
addressPattern: `anything@${zone}`,
|
|
268
|
+
fullOriginalPattern: `jane.doe@example.com.${zone}`,
|
|
269
|
+
usage: { month: (/* @__PURE__ */ new Date()).toISOString().slice(0, 7), messages: store.length, quota: 1e4 },
|
|
270
|
+
key: { name: "test", prefix: apiKey.slice(0, 12) }
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
if (u.pathname === "/v1/addresses" && method === "POST") {
|
|
274
|
+
const body = await readJson(req, true);
|
|
275
|
+
if (body === "invalid") return send(res, 400, { error: "The body must be a JSON object, or empty." });
|
|
276
|
+
const prefix = body?.prefix?.trim();
|
|
277
|
+
if (prefix && !/^[a-z0-9-]{1,30}$/.test(prefix)) {
|
|
278
|
+
return send(res, 400, { error: "prefix may only hold a-z, 0-9 and '-' (at most 30 characters)." });
|
|
279
|
+
}
|
|
280
|
+
const domain = body?.domain?.trim().toLowerCase() || domains[0];
|
|
281
|
+
if (!domains.includes(domain)) return send(res, 400, { error: `domain must be one of: ${domains.join(", ")}.` });
|
|
282
|
+
const local = (prefix ? `${prefix}-` : "") + randomLocal();
|
|
283
|
+
return send(res, 201, { address: `${local}@${zoneFor(domain)}`, domain, account, environment, workspace: environment });
|
|
284
|
+
}
|
|
285
|
+
if (u.pathname === "/v1/messages" && method === "GET") {
|
|
286
|
+
const take = clamp(int(q.get("take"), 50), 1, MAX_TAKE);
|
|
287
|
+
const skip = clamp(int(q.get("skip"), 0), 0, 1e4);
|
|
288
|
+
const items = matches(filter).sort((a, b) => b.received - a.received || b.seq - a.seq).slice(skip, skip + take).map(summary);
|
|
289
|
+
return send(res, 200, { items, skip, take });
|
|
290
|
+
}
|
|
291
|
+
if (u.pathname === "/v1/messages/wait" && method === "GET") {
|
|
292
|
+
const seconds = clamp(int(q.get("timeoutSeconds"), 30), 1, 120);
|
|
293
|
+
const found = await longPoll(res, seconds, () => matches(filter).sort((a, b) => a.received - b.received || a.seq - b.seq)[0]);
|
|
294
|
+
if (!found) {
|
|
295
|
+
res.statusCode = 204;
|
|
296
|
+
return res.end();
|
|
297
|
+
}
|
|
298
|
+
return send(res, 200, detail(found));
|
|
299
|
+
}
|
|
300
|
+
if (u.pathname === "/v1/messages" && method === "DELETE") {
|
|
301
|
+
if (!to) return send(res, 400, { error: "to (one of this environment's addresses) is required." });
|
|
302
|
+
const gone = matches({ to });
|
|
303
|
+
store = store.filter((s) => !gone.includes(s));
|
|
304
|
+
return send(res, 200, { deleted: gone.length, skippedShared: 0 });
|
|
305
|
+
}
|
|
306
|
+
if (parts[0] === "v1" && parts[1] === "messages" && parts[2] && GUID.test(parts[2])) {
|
|
307
|
+
const s = store.find((m) => m.id.toLowerCase() === parts[2].toLowerCase() && m.to.some(inEnv));
|
|
308
|
+
const notFound = () => send(res, 404, { error: "No such message in this environment." });
|
|
309
|
+
if (parts.length === 3 && method === "GET") return s ? send(res, 200, detail(s)) : notFound();
|
|
310
|
+
if (parts.length === 3 && method === "DELETE") {
|
|
311
|
+
if (!s) return notFound();
|
|
312
|
+
store = store.filter((m) => m !== s);
|
|
313
|
+
res.statusCode = 204;
|
|
314
|
+
return res.end();
|
|
315
|
+
}
|
|
316
|
+
if (parts.length === 4 && parts[3] === "raw" && method === "GET") {
|
|
317
|
+
if (!s) return notFound();
|
|
318
|
+
res.writeHead(200, { "Content-Type": "message/rfc822", "Content-Disposition": `attachment; filename="${s.id}.eml"` });
|
|
319
|
+
return res.end(s.raw);
|
|
320
|
+
}
|
|
321
|
+
if (parts.length === 5 && parts[3] === "attachments" && /^\d+$/.test(parts[4]) && method === "GET") {
|
|
322
|
+
const a = s?.attachments[Number(parts[4])];
|
|
323
|
+
if (!a) return notFound();
|
|
324
|
+
res.writeHead(200, { "Content-Type": a.contentType, "Content-Disposition": `attachment; filename="${a.fileName}"` });
|
|
325
|
+
return res.end(a.bytes);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
return send(res, 404, { error: "Not found." });
|
|
329
|
+
}
|
|
330
|
+
function longPoll(res, seconds, first) {
|
|
331
|
+
const now = first();
|
|
332
|
+
if (now !== void 0) return Promise.resolve(now);
|
|
333
|
+
return new Promise((resolve) => {
|
|
334
|
+
const done = (s) => {
|
|
335
|
+
clearTimeout(timer);
|
|
336
|
+
waiters.delete(check);
|
|
337
|
+
res.off("close", gone);
|
|
338
|
+
resolve(s);
|
|
339
|
+
};
|
|
340
|
+
const check = () => {
|
|
341
|
+
const s = first();
|
|
342
|
+
if (s !== void 0) done(s);
|
|
343
|
+
};
|
|
344
|
+
const gone = () => done(void 0);
|
|
345
|
+
const timer = setTimeout(() => done(void 0), seconds * 1e3);
|
|
346
|
+
waiters.add(check);
|
|
347
|
+
res.on("close", gone);
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
async function handleCatch(req, res, u, method) {
|
|
351
|
+
const rest = u.pathname.slice("/_fake/hook/".length);
|
|
352
|
+
const slash = rest.indexOf("/");
|
|
353
|
+
const t = slash < 0 ? rest : rest.slice(0, slash);
|
|
354
|
+
const path = slash < 0 ? "/" : rest.slice(slash);
|
|
355
|
+
const plain = (status, text, extra = {}) => {
|
|
356
|
+
res.writeHead(status, { ...CATCH_HEADERS, "Content-Type": "text/plain; charset=utf-8", ...extra });
|
|
357
|
+
res.end(method === "HEAD" ? void 0 : text);
|
|
358
|
+
};
|
|
359
|
+
if (!webhooksOn || t !== token) return plain(404, "MailPier Inbox webhook catcher (fake): no such URL.");
|
|
360
|
+
if (path.length > 2048) return plain(414, "The path is too long.");
|
|
361
|
+
const chunks = [];
|
|
362
|
+
let size = 0;
|
|
363
|
+
for await (const c of req) {
|
|
364
|
+
size += c.length;
|
|
365
|
+
if (size <= HOOK_LIMITS.maxBodyBytes) chunks.push(c);
|
|
366
|
+
}
|
|
367
|
+
if (size > HOOK_LIMITS.maxBodyBytes) return plain(413, "The request body is too large.");
|
|
368
|
+
const pairs = [];
|
|
369
|
+
for (let i = 0; i + 1 < req.rawHeaders.length; i += 2) {
|
|
370
|
+
if (!HOP_BY_HOP.has(req.rawHeaders[i].toLowerCase())) pairs.push([req.rawHeaders[i], req.rawHeaders[i + 1]]);
|
|
371
|
+
}
|
|
372
|
+
const { stored, rule } = storeHook({
|
|
373
|
+
received: Date.now(),
|
|
374
|
+
method,
|
|
375
|
+
path,
|
|
376
|
+
query: u.search.replace(/^\?/, ""),
|
|
377
|
+
headers: maskHeaders(pairs),
|
|
378
|
+
body: Buffer.concat(chunks),
|
|
379
|
+
contentType: req.headers["content-type"] ?? null,
|
|
380
|
+
sourceIp: req.socket.remoteAddress ?? "127.0.0.1"
|
|
381
|
+
});
|
|
382
|
+
if (rule) {
|
|
383
|
+
if (rule.delayMs > 0) await new Promise((r) => setTimeout(r, rule.delayMs));
|
|
384
|
+
res.writeHead(rule.status, { ...CATCH_HEADERS, "Content-Type": `${rule.contentType}; charset=utf-8` });
|
|
385
|
+
return res.end(method === "HEAD" ? void 0 : rule.body);
|
|
386
|
+
}
|
|
387
|
+
if (method === "OPTIONS") {
|
|
388
|
+
res.writeHead(204, { ...CATCH_HEADERS, "Access-Control-Allow-Methods": "*", "Access-Control-Allow-Headers": "*", "Access-Control-Max-Age": "600" });
|
|
389
|
+
return res.end();
|
|
390
|
+
}
|
|
391
|
+
return plain(200, "OK");
|
|
392
|
+
}
|
|
393
|
+
async function handleHooks(req, res, u, method, since) {
|
|
394
|
+
const q = u.searchParams;
|
|
395
|
+
const parts = u.pathname.split("/").filter(Boolean);
|
|
396
|
+
const path = q.get("path") || void 0;
|
|
397
|
+
if (path && (!path.startsWith("/") || path.length > 2048)) return send(res, 400, { error: "path must start with /." });
|
|
398
|
+
const hookMethod = methodName(q.get("method"));
|
|
399
|
+
if (hookMethod === "") return send(res, 400, { error: "method must be an HTTP method name (letters only, at most 20)." });
|
|
400
|
+
let afterId;
|
|
401
|
+
if (q.get("afterId")) {
|
|
402
|
+
afterId = Number(q.get("afterId"));
|
|
403
|
+
if (!Number.isInteger(afterId)) return send(res, 400, { error: "afterId must be a request id (a whole number)." });
|
|
404
|
+
}
|
|
405
|
+
const filter = (h) => (!path || h.path.startsWith(path)) && (!hookMethod || h.method === hookMethod) && (afterId === void 0 || h.id > afterId) && (since === void 0 || h.received >= since);
|
|
406
|
+
const bad = (error) => send(res, 400, { error });
|
|
407
|
+
const notFound = () => send(res, 404, { error: "No such request in this environment." });
|
|
408
|
+
if (parts.length === 2 && method === "GET") return send(res, 200, endpointJson());
|
|
409
|
+
if (parts[2] === "urls" && parts.length === 3 && method === "POST") {
|
|
410
|
+
const p = `/t-${randomLocal(6)}`;
|
|
411
|
+
return send(res, 201, { url: `${hookUrl()}${p}`, path: p });
|
|
412
|
+
}
|
|
413
|
+
if (parts[2] === "requests") {
|
|
414
|
+
if (parts.length === 3 && method === "GET") {
|
|
415
|
+
const take = clamp(int(q.get("take"), 50), 1, MAX_TAKE);
|
|
416
|
+
const skip = clamp(int(q.get("skip"), 0), 0, 1e4);
|
|
417
|
+
const items = hooks.filter(filter).sort((a, b) => b.id - a.id).slice(skip, skip + take).map(hookSummary);
|
|
418
|
+
return send(res, 200, { items, skip, take });
|
|
419
|
+
}
|
|
420
|
+
if (parts.length === 3 && method === "DELETE") {
|
|
421
|
+
const gone = hooks.filter((h) => !path || h.path.startsWith(path));
|
|
422
|
+
hooks = hooks.filter((h) => !gone.includes(h));
|
|
423
|
+
return send(res, 200, { deleted: gone.length });
|
|
424
|
+
}
|
|
425
|
+
if (parts.length === 4 && parts[3] === "wait" && method === "GET") {
|
|
426
|
+
const seconds = clamp(int(q.get("timeoutSeconds"), 30), 1, 120);
|
|
427
|
+
const found = await longPoll(res, seconds, () => hooks.filter(filter).sort((a, b) => a.id - b.id)[0]);
|
|
428
|
+
if (!found) {
|
|
429
|
+
res.statusCode = 204;
|
|
430
|
+
return res.end();
|
|
431
|
+
}
|
|
432
|
+
return send(res, 200, hookDetail(found));
|
|
433
|
+
}
|
|
434
|
+
if (parts.length >= 4 && /^\d+$/.test(parts[3])) {
|
|
435
|
+
const h = hooks.find((x) => x.id === Number(parts[3]));
|
|
436
|
+
if (parts.length === 4 && method === "GET") return h ? send(res, 200, hookDetail(h)) : notFound();
|
|
437
|
+
if (parts.length === 4 && method === "DELETE") {
|
|
438
|
+
if (!h) return notFound();
|
|
439
|
+
hooks = hooks.filter((x) => x !== h);
|
|
440
|
+
res.statusCode = 204;
|
|
441
|
+
return res.end();
|
|
442
|
+
}
|
|
443
|
+
if (parts.length === 5 && parts[4] === "body" && method === "GET") {
|
|
444
|
+
if (!h) return notFound();
|
|
445
|
+
res.writeHead(200, { "Content-Type": "application/octet-stream", "Content-Disposition": `attachment; filename="webhook-${h.id}.bin"` });
|
|
446
|
+
return res.end(h.body);
|
|
447
|
+
}
|
|
448
|
+
if (parts.length === 5 && parts[4] === "replay" && method === "POST") {
|
|
449
|
+
if (!h) return notFound();
|
|
450
|
+
const body = await readJson(req);
|
|
451
|
+
const refused = publicUrlProblem(body?.url);
|
|
452
|
+
if (refused) return bad(refused);
|
|
453
|
+
replays.push({ id: h.id, url: String(body.url).trim() });
|
|
454
|
+
return send(res, 200, { status: 200, durationMs: 1 });
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
if (parts[2] === "responses") {
|
|
459
|
+
if (parts.length === 3 && method === "GET") return send(res, 200, { items: rules.map(ruleJson) });
|
|
460
|
+
if (parts.length === 3 && method === "POST") {
|
|
461
|
+
const b = await readJson(req);
|
|
462
|
+
if (!b) return bad("The body must be a JSON object.");
|
|
463
|
+
const rulePath = b.path;
|
|
464
|
+
if (typeof rulePath !== "string" || !rulePath.startsWith("/") || rulePath.length > 2048) return bad("path must start with / (at most 2,048 characters).");
|
|
465
|
+
const ruleMethod = b.method === null || b.method === void 0 ? null : typeof b.method === "string" ? methodName(b.method) ?? null : "";
|
|
466
|
+
if (ruleMethod === "") return bad("method must be an HTTP method name (letters only, at most 20) or null for any method.");
|
|
467
|
+
const status = typeof b.status === "number" ? b.status : Number.NaN;
|
|
468
|
+
if (!Number.isInteger(status) || !(status >= 200 && status <= 299 || status >= 400 && status <= 599)) {
|
|
469
|
+
return bad("status must be 200-299 or 400-599 (no 1xx or 3xx).");
|
|
470
|
+
}
|
|
471
|
+
const contentType = typeof b.contentType === "string" && b.contentType.trim() ? b.contentType.trim().toLowerCase() : b.contentType === void 0 || b.contentType === null || b.contentType === "" ? "text/plain" : "";
|
|
472
|
+
if (!HOOK_CONTENT_TYPES.includes(contentType)) return bad(`contentType must be one of: ${HOOK_CONTENT_TYPES.join(", ")}.`);
|
|
473
|
+
const ruleBody = b.body ?? "";
|
|
474
|
+
if (typeof ruleBody !== "string" || Buffer.byteLength(ruleBody) > 8192) return bad("body must be text of at most 8 KB.");
|
|
475
|
+
const delayMs = b.delayMs ?? 0;
|
|
476
|
+
if (typeof delayMs !== "number" || !Number.isInteger(delayMs) || delayMs < 0 || delayMs > HOOK_LIMITS.maxDelayMs) {
|
|
477
|
+
return bad(`delayMs must be 0-${HOOK_LIMITS.maxDelayMs} (the plan's longest delay).`);
|
|
478
|
+
}
|
|
479
|
+
if (rules.length >= HOOK_LIMITS.responseRules) return bad(`Your plan allows ${HOOK_LIMITS.responseRules} custom responses per environment.`);
|
|
480
|
+
const rule = { id: ++ruleSeq, method: ruleMethod, path: rulePath, status, contentType, body: ruleBody, delayMs, created: Date.now() };
|
|
481
|
+
rules.push(rule);
|
|
482
|
+
return send(res, 201, ruleJson(rule));
|
|
483
|
+
}
|
|
484
|
+
if (parts.length === 4 && /^\d+$/.test(parts[3]) && method === "DELETE") {
|
|
485
|
+
const r = rules.find((x) => x.id === Number(parts[3]));
|
|
486
|
+
if (!r) return send(res, 404, { error: "No such custom response in this environment." });
|
|
487
|
+
rules = rules.filter((x) => x !== r);
|
|
488
|
+
res.statusCode = 204;
|
|
489
|
+
return res.end();
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
if (parts[2] === "forward" && parts.length === 3 && method === "PUT") {
|
|
493
|
+
const b = await readJson(req);
|
|
494
|
+
if (!b) return bad("The body must be a JSON object.");
|
|
495
|
+
if (b.url === null || b.url === void 0 || b.url === "") {
|
|
496
|
+
forwardUrl = null;
|
|
497
|
+
} else {
|
|
498
|
+
const refused = publicUrlProblem(b.url);
|
|
499
|
+
if (refused) return bad(refused);
|
|
500
|
+
forwardUrl = String(b.url).trim();
|
|
501
|
+
}
|
|
502
|
+
return send(res, 200, endpointJson());
|
|
503
|
+
}
|
|
504
|
+
return send(res, 404, { error: "Not found." });
|
|
505
|
+
}
|
|
506
|
+
await new Promise((resolve, reject) => {
|
|
507
|
+
server.once("error", reject);
|
|
508
|
+
server.listen(options.port ?? 0, "127.0.0.1", () => resolve());
|
|
509
|
+
});
|
|
510
|
+
const port = server.address().port;
|
|
511
|
+
baseUrl = `http://127.0.0.1:${port}`;
|
|
512
|
+
return {
|
|
513
|
+
url: baseUrl,
|
|
514
|
+
apiKey,
|
|
515
|
+
zone,
|
|
516
|
+
requests,
|
|
517
|
+
deliver,
|
|
518
|
+
failNext: (f) => {
|
|
519
|
+
failures.push({ ...f });
|
|
520
|
+
},
|
|
521
|
+
count: () => store.length,
|
|
522
|
+
webhookUrl: hookUrl(),
|
|
523
|
+
catchWebhook,
|
|
524
|
+
webhookCount: () => hooks.length,
|
|
525
|
+
replays,
|
|
526
|
+
reset: () => {
|
|
527
|
+
store = [];
|
|
528
|
+
failures = [];
|
|
529
|
+
requests.length = 0;
|
|
530
|
+
hooks = [];
|
|
531
|
+
rules = [];
|
|
532
|
+
forwardUrl = null;
|
|
533
|
+
hookCounter = 0;
|
|
534
|
+
replays.length = 0;
|
|
535
|
+
},
|
|
536
|
+
close: () => new Promise((resolve) => {
|
|
537
|
+
for (const w of [...waiters]) w();
|
|
538
|
+
server.closeAllConnections?.();
|
|
539
|
+
server.close(() => resolve());
|
|
540
|
+
})
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
function send(res, status, body) {
|
|
544
|
+
const text = JSON.stringify(body);
|
|
545
|
+
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Content-Length": Buffer.byteLength(text) });
|
|
546
|
+
res.end(text);
|
|
547
|
+
}
|
|
548
|
+
async function readJson(req, optional = false) {
|
|
549
|
+
const chunks = [];
|
|
550
|
+
for await (const c of req) chunks.push(c);
|
|
551
|
+
const text = Buffer.concat(chunks).toString("utf8");
|
|
552
|
+
if (!text.trim()) return void 0;
|
|
553
|
+
try {
|
|
554
|
+
const v = JSON.parse(text);
|
|
555
|
+
return v && typeof v === "object" && !Array.isArray(v) ? v : optional ? "invalid" : void 0;
|
|
556
|
+
} catch {
|
|
557
|
+
return optional ? "invalid" : void 0;
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
function clean(o) {
|
|
561
|
+
for (const k of Object.keys(o)) if (o[k] === void 0 || o[k] === null) delete o[k];
|
|
562
|
+
return o;
|
|
563
|
+
}
|
|
564
|
+
var int = (v, d) => {
|
|
565
|
+
const n = Number.parseInt(v ?? "", 10);
|
|
566
|
+
return Number.isFinite(n) ? n : d;
|
|
567
|
+
};
|
|
568
|
+
var clamp = (n, lo, hi) => Math.min(Math.max(n, lo), hi);
|
|
569
|
+
function randomLocal(length = 10) {
|
|
570
|
+
const abc = "abcdefghijklmnopqrstuvwxyz0123456789";
|
|
571
|
+
return [...(0, import_node_crypto.randomBytes)(length)].map((b) => abc[b % abc.length]).join("");
|
|
572
|
+
}
|
|
573
|
+
var CATCH_HEADERS = {
|
|
574
|
+
"X-Content-Type-Options": "nosniff",
|
|
575
|
+
"Content-Security-Policy": "default-src 'none'; sandbox",
|
|
576
|
+
"X-Frame-Options": "DENY",
|
|
577
|
+
"Cache-Control": "no-store",
|
|
578
|
+
"Referrer-Policy": "no-referrer",
|
|
579
|
+
"X-Robots-Tag": "noindex",
|
|
580
|
+
"Access-Control-Allow-Origin": "*"
|
|
581
|
+
};
|
|
582
|
+
function methodName(v) {
|
|
583
|
+
const m = (v ?? "").trim();
|
|
584
|
+
if (!m || m === "*" || m.toUpperCase() === "ANY") return void 0;
|
|
585
|
+
return /^[A-Za-z]{1,20}$/.test(m) ? m.toUpperCase() : "";
|
|
586
|
+
}
|
|
587
|
+
function maskHeaders(pairs) {
|
|
588
|
+
return pairs.map(([n, v]) => [n, SECRET_HEADERS.has(n.toLowerCase()) ? "***" : v]);
|
|
589
|
+
}
|
|
590
|
+
function utf8(b) {
|
|
591
|
+
try {
|
|
592
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(b);
|
|
593
|
+
} catch {
|
|
594
|
+
return void 0;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
function publicUrlProblem(v) {
|
|
598
|
+
if (typeof v !== "string" || !v.trim()) return "url (an absolute http or https URL) is required.";
|
|
599
|
+
let u;
|
|
600
|
+
try {
|
|
601
|
+
u = new URL(v.trim());
|
|
602
|
+
} catch {
|
|
603
|
+
return "url must be an absolute http or https URL.";
|
|
604
|
+
}
|
|
605
|
+
if (u.protocol !== "http:" && u.protocol !== "https:") return "url must be an absolute http or https URL.";
|
|
606
|
+
const host = u.hostname.replace(/^\[|\]$/g, "").toLowerCase();
|
|
607
|
+
if (host === "localhost" || host.endsWith(".localhost") || isPrivateAddress(host)) {
|
|
608
|
+
return "url must be a public address: MailPier never calls private, loopback or link-local addresses.";
|
|
609
|
+
}
|
|
610
|
+
return void 0;
|
|
611
|
+
}
|
|
612
|
+
function isPrivateAddress(host) {
|
|
613
|
+
const m = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(host);
|
|
614
|
+
if (m) {
|
|
615
|
+
const a = Number(m[1]);
|
|
616
|
+
const b = Number(m[2]);
|
|
617
|
+
return a === 0 || a === 10 || a === 127 || a === 100 && b >= 64 && b <= 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a >= 224;
|
|
618
|
+
}
|
|
619
|
+
if (!host.includes(":")) return false;
|
|
620
|
+
return host === "::" || host === "::1" || host.startsWith("fc") || host.startsWith("fd") || host.startsWith("fe80") || host.startsWith("::ffff:");
|
|
621
|
+
}
|
|
622
|
+
function findLinks(html, text) {
|
|
623
|
+
const out = [];
|
|
624
|
+
const seen = /* @__PURE__ */ new Set();
|
|
625
|
+
if (html) {
|
|
626
|
+
for (const m of html.matchAll(/<a\s[^>]*href\s*=\s*["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi)) {
|
|
627
|
+
const href = m[1].replace(/&/g, "&");
|
|
628
|
+
if (!/^https?:/i.test(href) || seen.has(href)) continue;
|
|
629
|
+
seen.add(href);
|
|
630
|
+
const t = m[2].replace(/<[^>]+>/g, "").trim();
|
|
631
|
+
out.push(t ? { href, text: t } : { href });
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
for (const m of (text ?? "").matchAll(/https?:\/\/[^\s<>"')]+/gi)) {
|
|
635
|
+
const href = m[0].replace(/[.,;:!?]+$/, "");
|
|
636
|
+
if (!seen.has(href)) {
|
|
637
|
+
seen.add(href);
|
|
638
|
+
out.push({ href });
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
return out;
|
|
642
|
+
}
|
|
643
|
+
function findCodes(subject, text) {
|
|
644
|
+
const out = [];
|
|
645
|
+
for (const m of `${subject ?? ""}
|
|
646
|
+
${text ?? ""}`.matchAll(/(?<![\w\/.-])\d{4,8}(?!\w|[.\/-]\d)/g)) if (!out.includes(m[0])) out.push(m[0]);
|
|
647
|
+
return out;
|
|
648
|
+
}
|
|
649
|
+
function buildEml(id, mail, to, atts) {
|
|
650
|
+
const boundary = `=_fake_${id}`;
|
|
651
|
+
const lines = [
|
|
652
|
+
`From: ${mail.fromName ? `"${mail.fromName}" ` : ""}<${mail.from ?? "sender@example.com"}>`,
|
|
653
|
+
`To: ${to.join(", ")}`,
|
|
654
|
+
`Subject: ${mail.subject ?? ""}`,
|
|
655
|
+
`Message-ID: <${id}@fake.mailpier.test>`,
|
|
656
|
+
"MIME-Version: 1.0",
|
|
657
|
+
`Content-Type: multipart/mixed; boundary="${boundary}"`,
|
|
658
|
+
"",
|
|
659
|
+
`--${boundary}`,
|
|
660
|
+
"Content-Type: text/plain; charset=utf-8",
|
|
661
|
+
"",
|
|
662
|
+
mail.text ?? ""
|
|
663
|
+
];
|
|
664
|
+
if (mail.html) lines.push(`--${boundary}`, "Content-Type: text/html; charset=utf-8", "", mail.html);
|
|
665
|
+
for (const a of atts) {
|
|
666
|
+
lines.push(
|
|
667
|
+
`--${boundary}`,
|
|
668
|
+
`Content-Type: ${a.contentType}; name="${a.fileName}"`,
|
|
669
|
+
"Content-Transfer-Encoding: base64",
|
|
670
|
+
`Content-Disposition: attachment; filename="${a.fileName}"`,
|
|
671
|
+
"",
|
|
672
|
+
a.bytes.toString("base64")
|
|
673
|
+
);
|
|
674
|
+
}
|
|
675
|
+
lines.push(`--${boundary}--`, "");
|
|
676
|
+
return Buffer.from(lines.join("\r\n"), "utf8");
|
|
677
|
+
}
|
|
678
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
679
|
+
0 && (module.exports = {
|
|
680
|
+
findCodes,
|
|
681
|
+
findLinks,
|
|
682
|
+
startFakeMailPier
|
|
683
|
+
});
|