@mailpier/inbox 0.1.0 → 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 +16 -1
- package/README.md +62 -2
- package/dist/{chunk-FR6JEAV7.js → chunk-2NMZ2IWD.js} +210 -3
- 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 +17 -2
- package/dist/cypress/commands.d.cts +13 -3
- package/dist/cypress/commands.d.ts +13 -3
- package/dist/cypress/commands.js +17 -2
- package/dist/cypress/index.cjs +221 -4
- package/dist/cypress/index.d.cts +17 -2
- package/dist/cypress/index.d.ts +17 -2
- package/dist/cypress/index.js +15 -2
- package/dist/index.cjs +213 -5
- package/dist/index.d.cts +12 -3
- package/dist/index.d.ts +12 -3
- package/dist/index.js +7 -3
- package/dist/playwright.cjs +232 -3
- package/dist/playwright.d.cts +17 -2
- package/dist/playwright.d.ts +17 -2
- package/dist/playwright.js +28 -2
- package/dist/testing/index.cjs +353 -20
- package/dist/testing/index.d.cts +32 -1
- package/dist/testing/index.d.ts +32 -1
- package/dist/testing/index.js +353 -20
- package/package.json +8 -3
- package/dist/client-CqysQIQJ.d.cts +0 -194
- package/dist/client-CqysQIQJ.d.ts +0 -194
package/dist/testing/index.cjs
CHANGED
|
@@ -31,6 +31,19 @@ var import_node_http = require("http");
|
|
|
31
31
|
var import_node_crypto = require("crypto");
|
|
32
32
|
var MAX_TAKE = 100;
|
|
33
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
|
+
]);
|
|
34
47
|
async function startFakeMailPier(options = {}) {
|
|
35
48
|
const apiKey = options.apiKey ?? "mpi_test_key";
|
|
36
49
|
const account = options.account ?? "demo";
|
|
@@ -72,6 +85,48 @@ async function startFakeMailPier(options = {}) {
|
|
|
72
85
|
for (const w of [...waiters]) w();
|
|
73
86
|
return id;
|
|
74
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
|
+
}
|
|
75
130
|
const summary = (s) => clean({
|
|
76
131
|
id: s.id,
|
|
77
132
|
receivedUtc: new Date(s.received).toISOString(),
|
|
@@ -99,6 +154,61 @@ async function startFakeMailPier(options = {}) {
|
|
|
99
154
|
auth: { spf: "pass", dkim: "pass", dmarc: "pass" },
|
|
100
155
|
spam: { score: 0.1, verdict: "ham" }
|
|
101
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
|
+
});
|
|
102
212
|
function matches(f) {
|
|
103
213
|
let afterSeq = 0;
|
|
104
214
|
if (f.since !== void 0 && f.afterId) afterSeq = store.find((s) => s.id === f.afterId)?.seq ?? 0;
|
|
@@ -120,7 +230,10 @@ async function startFakeMailPier(options = {}) {
|
|
|
120
230
|
if (!body || typeof body !== "object") return send(res, 400, { error: "JSON body required." });
|
|
121
231
|
return send(res, 201, { id: deliver(body) });
|
|
122
232
|
}
|
|
233
|
+
if (u.pathname.startsWith("/_fake/hook/")) return handleCatch(req, res, u, method);
|
|
123
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." });
|
|
124
237
|
if ((req.headers.authorization ?? "") !== `Bearer ${apiKey}`) {
|
|
125
238
|
res.setHeader("WWW-Authenticate", "Bearer");
|
|
126
239
|
return send(res, 401, { error: "Missing, unknown or revoked API key. Send Authorization: Bearer mpi_..." });
|
|
@@ -143,6 +256,7 @@ async function startFakeMailPier(options = {}) {
|
|
|
143
256
|
since = Date.parse(sinceText);
|
|
144
257
|
if (Number.isNaN(since)) return send(res, 400, { error: "since must be an ISO 8601 date/time." });
|
|
145
258
|
}
|
|
259
|
+
if (isHooks) return handleHooks(req, res, u, method, since);
|
|
146
260
|
const filter = { to, subject: q.get("subject") ?? void 0, since, afterId: q.get("afterId") ?? void 0 };
|
|
147
261
|
const parts = u.pathname.split("/").filter(Boolean);
|
|
148
262
|
if (u.pathname === "/v1/me" && method === "GET") {
|
|
@@ -176,23 +290,7 @@ async function startFakeMailPier(options = {}) {
|
|
|
176
290
|
}
|
|
177
291
|
if (u.pathname === "/v1/messages/wait" && method === "GET") {
|
|
178
292
|
const seconds = clamp(int(q.get("timeoutSeconds"), 30), 1, 120);
|
|
179
|
-
const
|
|
180
|
-
const found = first() ?? await new Promise((resolve) => {
|
|
181
|
-
const done = (s) => {
|
|
182
|
-
clearTimeout(timer);
|
|
183
|
-
waiters.delete(check);
|
|
184
|
-
res.off("close", gone);
|
|
185
|
-
resolve(s);
|
|
186
|
-
};
|
|
187
|
-
const check = () => {
|
|
188
|
-
const s = first();
|
|
189
|
-
if (s) done(s);
|
|
190
|
-
};
|
|
191
|
-
const gone = () => done(void 0);
|
|
192
|
-
const timer = setTimeout(() => done(void 0), seconds * 1e3);
|
|
193
|
-
waiters.add(check);
|
|
194
|
-
res.on("close", gone);
|
|
195
|
-
});
|
|
293
|
+
const found = await longPoll(res, seconds, () => matches(filter).sort((a, b) => a.received - b.received || a.seq - b.seq)[0]);
|
|
196
294
|
if (!found) {
|
|
197
295
|
res.statusCode = 204;
|
|
198
296
|
return res.end();
|
|
@@ -229,13 +327,190 @@ async function startFakeMailPier(options = {}) {
|
|
|
229
327
|
}
|
|
230
328
|
return send(res, 404, { error: "Not found." });
|
|
231
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
|
+
}
|
|
232
506
|
await new Promise((resolve, reject) => {
|
|
233
507
|
server.once("error", reject);
|
|
234
508
|
server.listen(options.port ?? 0, "127.0.0.1", () => resolve());
|
|
235
509
|
});
|
|
236
510
|
const port = server.address().port;
|
|
511
|
+
baseUrl = `http://127.0.0.1:${port}`;
|
|
237
512
|
return {
|
|
238
|
-
url:
|
|
513
|
+
url: baseUrl,
|
|
239
514
|
apiKey,
|
|
240
515
|
zone,
|
|
241
516
|
requests,
|
|
@@ -244,10 +519,19 @@ async function startFakeMailPier(options = {}) {
|
|
|
244
519
|
failures.push({ ...f });
|
|
245
520
|
},
|
|
246
521
|
count: () => store.length,
|
|
522
|
+
webhookUrl: hookUrl(),
|
|
523
|
+
catchWebhook,
|
|
524
|
+
webhookCount: () => hooks.length,
|
|
525
|
+
replays,
|
|
247
526
|
reset: () => {
|
|
248
527
|
store = [];
|
|
249
528
|
failures = [];
|
|
250
529
|
requests.length = 0;
|
|
530
|
+
hooks = [];
|
|
531
|
+
rules = [];
|
|
532
|
+
forwardUrl = null;
|
|
533
|
+
hookCounter = 0;
|
|
534
|
+
replays.length = 0;
|
|
251
535
|
},
|
|
252
536
|
close: () => new Promise((resolve) => {
|
|
253
537
|
for (const w of [...waiters]) w();
|
|
@@ -282,9 +566,58 @@ var int = (v, d) => {
|
|
|
282
566
|
return Number.isFinite(n) ? n : d;
|
|
283
567
|
};
|
|
284
568
|
var clamp = (n, lo, hi) => Math.min(Math.max(n, lo), hi);
|
|
285
|
-
function randomLocal() {
|
|
569
|
+
function randomLocal(length = 10) {
|
|
286
570
|
const abc = "abcdefghijklmnopqrstuvwxyz0123456789";
|
|
287
|
-
return [...(0, import_node_crypto.randomBytes)(
|
|
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:");
|
|
288
621
|
}
|
|
289
622
|
function findLinks(html, text) {
|
|
290
623
|
const out = [];
|
package/dist/testing/index.d.cts
CHANGED
|
@@ -31,6 +31,26 @@ interface FakeMailPierOptions {
|
|
|
31
31
|
domains?: string[];
|
|
32
32
|
/** Port to listen on (127.0.0.1); 0 = any free port. */
|
|
33
33
|
port?: number;
|
|
34
|
+
/** The Webhook inspector is on (default true); false = every /v1/hooks call answers 404 like the service while it is off. */
|
|
35
|
+
webhooks?: boolean;
|
|
36
|
+
}
|
|
37
|
+
/** A request as if the environment's catch URL had received it (FakeMailPier.catchWebhook). */
|
|
38
|
+
interface FakeWebhook {
|
|
39
|
+
/** Default "POST". */
|
|
40
|
+
method?: string;
|
|
41
|
+
/** The path after the token. Default "/". */
|
|
42
|
+
path?: string;
|
|
43
|
+
/** The query string, without "?". */
|
|
44
|
+
query?: string;
|
|
45
|
+
headers?: Record<string, string> | [string, string][];
|
|
46
|
+
/** Text (UTF-8), bytes, or an object/array (sent as JSON). */
|
|
47
|
+
body?: string | Uint8Array | Record<string, unknown> | unknown[];
|
|
48
|
+
/** Default application/json for an object body, text/plain for a text body, none without a body. */
|
|
49
|
+
contentType?: string;
|
|
50
|
+
/** Defaults to now. */
|
|
51
|
+
receivedUtc?: Date;
|
|
52
|
+
/** Default 203.0.113.10. */
|
|
53
|
+
sourceIp?: string;
|
|
34
54
|
}
|
|
35
55
|
interface FailNext {
|
|
36
56
|
status: number;
|
|
@@ -58,6 +78,17 @@ interface FakeMailPier {
|
|
|
58
78
|
failNext(f: FailNext): void;
|
|
59
79
|
/** Number of stored mails (all addresses). */
|
|
60
80
|
count(): number;
|
|
81
|
+
/** The environment's catch URL on this fake: any request to it, or to any path below it, is caught. */
|
|
82
|
+
readonly webhookUrl: string;
|
|
83
|
+
/** Stores a request as if the catch URL had received it (custom responses decide its status); wakes waits. Returns its id. */
|
|
84
|
+
catchWebhook(request?: FakeWebhook): number;
|
|
85
|
+
/** Number of stored webhook requests. */
|
|
86
|
+
webhookCount(): number;
|
|
87
|
+
/** Every replay the API was asked for, oldest first (the fake never sends anything). */
|
|
88
|
+
readonly replays: {
|
|
89
|
+
id: number;
|
|
90
|
+
url: string;
|
|
91
|
+
}[];
|
|
61
92
|
reset(): void;
|
|
62
93
|
close(): Promise<void>;
|
|
63
94
|
}
|
|
@@ -72,4 +103,4 @@ declare function findLinks(html?: string, text?: string): {
|
|
|
72
103
|
declare function findCodes(subject?: string, text?: string): string[];
|
|
73
104
|
|
|
74
105
|
export { findCodes, findLinks, startFakeMailPier };
|
|
75
|
-
export type { FailNext, FakeAttachment, FakeMail, FakeMailPier, FakeMailPierOptions };
|
|
106
|
+
export type { FailNext, FakeAttachment, FakeMail, FakeMailPier, FakeMailPierOptions, FakeWebhook };
|
package/dist/testing/index.d.ts
CHANGED
|
@@ -31,6 +31,26 @@ interface FakeMailPierOptions {
|
|
|
31
31
|
domains?: string[];
|
|
32
32
|
/** Port to listen on (127.0.0.1); 0 = any free port. */
|
|
33
33
|
port?: number;
|
|
34
|
+
/** The Webhook inspector is on (default true); false = every /v1/hooks call answers 404 like the service while it is off. */
|
|
35
|
+
webhooks?: boolean;
|
|
36
|
+
}
|
|
37
|
+
/** A request as if the environment's catch URL had received it (FakeMailPier.catchWebhook). */
|
|
38
|
+
interface FakeWebhook {
|
|
39
|
+
/** Default "POST". */
|
|
40
|
+
method?: string;
|
|
41
|
+
/** The path after the token. Default "/". */
|
|
42
|
+
path?: string;
|
|
43
|
+
/** The query string, without "?". */
|
|
44
|
+
query?: string;
|
|
45
|
+
headers?: Record<string, string> | [string, string][];
|
|
46
|
+
/** Text (UTF-8), bytes, or an object/array (sent as JSON). */
|
|
47
|
+
body?: string | Uint8Array | Record<string, unknown> | unknown[];
|
|
48
|
+
/** Default application/json for an object body, text/plain for a text body, none without a body. */
|
|
49
|
+
contentType?: string;
|
|
50
|
+
/** Defaults to now. */
|
|
51
|
+
receivedUtc?: Date;
|
|
52
|
+
/** Default 203.0.113.10. */
|
|
53
|
+
sourceIp?: string;
|
|
34
54
|
}
|
|
35
55
|
interface FailNext {
|
|
36
56
|
status: number;
|
|
@@ -58,6 +78,17 @@ interface FakeMailPier {
|
|
|
58
78
|
failNext(f: FailNext): void;
|
|
59
79
|
/** Number of stored mails (all addresses). */
|
|
60
80
|
count(): number;
|
|
81
|
+
/** The environment's catch URL on this fake: any request to it, or to any path below it, is caught. */
|
|
82
|
+
readonly webhookUrl: string;
|
|
83
|
+
/** Stores a request as if the catch URL had received it (custom responses decide its status); wakes waits. Returns its id. */
|
|
84
|
+
catchWebhook(request?: FakeWebhook): number;
|
|
85
|
+
/** Number of stored webhook requests. */
|
|
86
|
+
webhookCount(): number;
|
|
87
|
+
/** Every replay the API was asked for, oldest first (the fake never sends anything). */
|
|
88
|
+
readonly replays: {
|
|
89
|
+
id: number;
|
|
90
|
+
url: string;
|
|
91
|
+
}[];
|
|
61
92
|
reset(): void;
|
|
62
93
|
close(): Promise<void>;
|
|
63
94
|
}
|
|
@@ -72,4 +103,4 @@ declare function findLinks(html?: string, text?: string): {
|
|
|
72
103
|
declare function findCodes(subject?: string, text?: string): string[];
|
|
73
104
|
|
|
74
105
|
export { findCodes, findLinks, startFakeMailPier };
|
|
75
|
-
export type { FailNext, FakeAttachment, FakeMail, FakeMailPier, FakeMailPierOptions };
|
|
106
|
+
export type { FailNext, FakeAttachment, FakeMail, FakeMailPier, FakeMailPierOptions, FakeWebhook };
|