@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.
@@ -3,6 +3,19 @@ import { createServer } from "http";
3
3
  import { randomBytes, randomUUID } from "crypto";
4
4
  var MAX_TAKE = 100;
5
5
  var GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
6
+ var HOOK_LIMITS = { requestsPerMonth: 1e5, maxBodyBytes: 1048576, responseRules: 50, maxDelayMs: 3e4, requestsPerSecond: 25, forward: true };
7
+ var HOOK_CONTENT_TYPES = ["application/json", "text/plain", "application/xml"];
8
+ var HOP_BY_HOP = /* @__PURE__ */ new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-connection", "te", "trailer", "transfer-encoding", "upgrade", "host"]);
9
+ var SECRET_HEADERS = /* @__PURE__ */ new Set([
10
+ "authorization",
11
+ "proxy-authorization",
12
+ "cookie",
13
+ "x-api-key",
14
+ "api-key",
15
+ "x-auth-token",
16
+ "x-access-token",
17
+ "x-amz-security-token"
18
+ ]);
6
19
  async function startFakeMailPier(options = {}) {
7
20
  const apiKey = options.apiKey ?? "mpi_test_key";
8
21
  const account = options.account ?? "demo";
@@ -44,6 +57,48 @@ async function startFakeMailPier(options = {}) {
44
57
  for (const w of [...waiters]) w();
45
58
  return id;
46
59
  }
60
+ const webhooksOn = options.webhooks ?? true;
61
+ const token = randomLocal(20);
62
+ let baseUrl = "";
63
+ const hookUrl = () => `${baseUrl}/_fake/hook/${token}`;
64
+ let hookSeq = 0;
65
+ let ruleSeq = 0;
66
+ let hookCounter = 0;
67
+ let hooks = [];
68
+ let rules = [];
69
+ let forwardUrl = null;
70
+ const replays = [];
71
+ function matchRule(method, path) {
72
+ 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];
73
+ }
74
+ function storeHook(h) {
75
+ const rule = matchRule(h.method, h.path);
76
+ const status = rule?.status ?? (h.method === "OPTIONS" ? 204 : 200);
77
+ const stored = { ...h, id: ++hookSeq, status, ruleId: rule?.id ?? null };
78
+ hookCounter++;
79
+ hooks.push(stored);
80
+ for (const w of [...waiters]) w();
81
+ return { stored, rule };
82
+ }
83
+ function catchWebhook(r = {}) {
84
+ const method = (r.method ?? "POST").trim().toUpperCase() || "POST";
85
+ const path = r.path?.trim() ? r.path.startsWith("/") ? r.path : `/${r.path}` : "/";
86
+ const isObject = r.body !== void 0 && !(r.body instanceof Uint8Array) && typeof r.body === "object";
87
+ 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");
88
+ const pairs = Array.isArray(r.headers) ? r.headers.map(([n, v]) => [n, v]) : Object.entries(r.headers ?? {});
89
+ 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);
90
+ if (contentType && !pairs.some(([n]) => n.toLowerCase() === "content-type")) pairs.push(["Content-Type", contentType]);
91
+ return storeHook({
92
+ received: (r.receivedUtc ?? /* @__PURE__ */ new Date()).getTime(),
93
+ method,
94
+ path,
95
+ query: (r.query ?? "").replace(/^\?/, ""),
96
+ headers: maskHeaders(pairs.filter(([n]) => !HOP_BY_HOP.has(n.toLowerCase()))),
97
+ body,
98
+ contentType: contentType ?? null,
99
+ sourceIp: r.sourceIp ?? "203.0.113.10"
100
+ }).stored.id;
101
+ }
47
102
  const summary = (s) => clean({
48
103
  id: s.id,
49
104
  receivedUtc: new Date(s.received).toISOString(),
@@ -71,6 +126,61 @@ async function startFakeMailPier(options = {}) {
71
126
  auth: { spf: "pass", dkim: "pass", dmarc: "pass" },
72
127
  spam: { score: 0.1, verdict: "ham" }
73
128
  });
129
+ const hookSummary = (h) => ({
130
+ id: h.id,
131
+ receivedUtc: new Date(h.received).toISOString(),
132
+ method: h.method,
133
+ path: h.path,
134
+ query: h.query,
135
+ contentType: h.contentType,
136
+ size: h.body.length,
137
+ environment,
138
+ status: h.status
139
+ });
140
+ const hookDetail = (h) => {
141
+ const text = utf8(h.body);
142
+ const type = (h.contentType ?? "").split(";")[0].trim().toLowerCase();
143
+ let json = null;
144
+ if (text !== void 0 && (type === "application/json" || type.endsWith("+json"))) {
145
+ try {
146
+ json = JSON.parse(text);
147
+ } catch {
148
+ json = null;
149
+ }
150
+ }
151
+ const form = text !== void 0 && type === "application/x-www-form-urlencoded" ? Object.fromEntries(new URLSearchParams(text)) : null;
152
+ return {
153
+ ...hookSummary(h),
154
+ url: `${hookUrl()}${h.path}${h.query ? `?${h.query}` : ""}`,
155
+ headers: h.headers.map(([name, value]) => ({ name, value })),
156
+ body: text ?? null,
157
+ bodyBase64: text === void 0 ? h.body.toString("base64") : null,
158
+ json,
159
+ form,
160
+ sourceIp: h.sourceIp,
161
+ headersTruncated: false,
162
+ ruleId: h.ruleId,
163
+ forwardStatus: null
164
+ };
165
+ };
166
+ const endpointJson = () => ({
167
+ url: hookUrl(),
168
+ paused: false,
169
+ hideSecrets: true,
170
+ forwardUrl,
171
+ limits: { ...HOOK_LIMITS, usedThisMonth: hookCounter }
172
+ });
173
+ const ruleJson = (r) => ({
174
+ id: r.id,
175
+ method: r.method,
176
+ path: r.path,
177
+ status: r.status,
178
+ contentType: r.contentType,
179
+ body: r.body,
180
+ delayMs: r.delayMs,
181
+ createdUtc: new Date(r.created).toISOString(),
182
+ inForce: true
183
+ });
74
184
  function matches(f) {
75
185
  let afterSeq = 0;
76
186
  if (f.since !== void 0 && f.afterId) afterSeq = store.find((s) => s.id === f.afterId)?.seq ?? 0;
@@ -92,7 +202,10 @@ async function startFakeMailPier(options = {}) {
92
202
  if (!body || typeof body !== "object") return send(res, 400, { error: "JSON body required." });
93
203
  return send(res, 201, { id: deliver(body) });
94
204
  }
205
+ if (u.pathname.startsWith("/_fake/hook/")) return handleCatch(req, res, u, method);
95
206
  if (!u.pathname.startsWith("/v1/")) return send(res, 404, { error: "Not found." });
207
+ const isHooks = u.pathname === "/v1/hooks" || u.pathname.startsWith("/v1/hooks/");
208
+ if (isHooks && !webhooksOn) return send(res, 404, { error: "Not found." });
96
209
  if ((req.headers.authorization ?? "") !== `Bearer ${apiKey}`) {
97
210
  res.setHeader("WWW-Authenticate", "Bearer");
98
211
  return send(res, 401, { error: "Missing, unknown or revoked API key. Send Authorization: Bearer mpi_..." });
@@ -115,6 +228,7 @@ async function startFakeMailPier(options = {}) {
115
228
  since = Date.parse(sinceText);
116
229
  if (Number.isNaN(since)) return send(res, 400, { error: "since must be an ISO 8601 date/time." });
117
230
  }
231
+ if (isHooks) return handleHooks(req, res, u, method, since);
118
232
  const filter = { to, subject: q.get("subject") ?? void 0, since, afterId: q.get("afterId") ?? void 0 };
119
233
  const parts = u.pathname.split("/").filter(Boolean);
120
234
  if (u.pathname === "/v1/me" && method === "GET") {
@@ -148,23 +262,7 @@ async function startFakeMailPier(options = {}) {
148
262
  }
149
263
  if (u.pathname === "/v1/messages/wait" && method === "GET") {
150
264
  const seconds = clamp(int(q.get("timeoutSeconds"), 30), 1, 120);
151
- const first = () => matches(filter).sort((a, b) => a.received - b.received || a.seq - b.seq)[0];
152
- const found = first() ?? await new Promise((resolve) => {
153
- const done = (s) => {
154
- clearTimeout(timer);
155
- waiters.delete(check);
156
- res.off("close", gone);
157
- resolve(s);
158
- };
159
- const check = () => {
160
- const s = first();
161
- if (s) done(s);
162
- };
163
- const gone = () => done(void 0);
164
- const timer = setTimeout(() => done(void 0), seconds * 1e3);
165
- waiters.add(check);
166
- res.on("close", gone);
167
- });
265
+ const found = await longPoll(res, seconds, () => matches(filter).sort((a, b) => a.received - b.received || a.seq - b.seq)[0]);
168
266
  if (!found) {
169
267
  res.statusCode = 204;
170
268
  return res.end();
@@ -201,13 +299,190 @@ async function startFakeMailPier(options = {}) {
201
299
  }
202
300
  return send(res, 404, { error: "Not found." });
203
301
  }
302
+ function longPoll(res, seconds, first) {
303
+ const now = first();
304
+ if (now !== void 0) return Promise.resolve(now);
305
+ return new Promise((resolve) => {
306
+ const done = (s) => {
307
+ clearTimeout(timer);
308
+ waiters.delete(check);
309
+ res.off("close", gone);
310
+ resolve(s);
311
+ };
312
+ const check = () => {
313
+ const s = first();
314
+ if (s !== void 0) done(s);
315
+ };
316
+ const gone = () => done(void 0);
317
+ const timer = setTimeout(() => done(void 0), seconds * 1e3);
318
+ waiters.add(check);
319
+ res.on("close", gone);
320
+ });
321
+ }
322
+ async function handleCatch(req, res, u, method) {
323
+ const rest = u.pathname.slice("/_fake/hook/".length);
324
+ const slash = rest.indexOf("/");
325
+ const t = slash < 0 ? rest : rest.slice(0, slash);
326
+ const path = slash < 0 ? "/" : rest.slice(slash);
327
+ const plain = (status, text, extra = {}) => {
328
+ res.writeHead(status, { ...CATCH_HEADERS, "Content-Type": "text/plain; charset=utf-8", ...extra });
329
+ res.end(method === "HEAD" ? void 0 : text);
330
+ };
331
+ if (!webhooksOn || t !== token) return plain(404, "MailPier Inbox webhook catcher (fake): no such URL.");
332
+ if (path.length > 2048) return plain(414, "The path is too long.");
333
+ const chunks = [];
334
+ let size = 0;
335
+ for await (const c of req) {
336
+ size += c.length;
337
+ if (size <= HOOK_LIMITS.maxBodyBytes) chunks.push(c);
338
+ }
339
+ if (size > HOOK_LIMITS.maxBodyBytes) return plain(413, "The request body is too large.");
340
+ const pairs = [];
341
+ for (let i = 0; i + 1 < req.rawHeaders.length; i += 2) {
342
+ if (!HOP_BY_HOP.has(req.rawHeaders[i].toLowerCase())) pairs.push([req.rawHeaders[i], req.rawHeaders[i + 1]]);
343
+ }
344
+ const { stored, rule } = storeHook({
345
+ received: Date.now(),
346
+ method,
347
+ path,
348
+ query: u.search.replace(/^\?/, ""),
349
+ headers: maskHeaders(pairs),
350
+ body: Buffer.concat(chunks),
351
+ contentType: req.headers["content-type"] ?? null,
352
+ sourceIp: req.socket.remoteAddress ?? "127.0.0.1"
353
+ });
354
+ if (rule) {
355
+ if (rule.delayMs > 0) await new Promise((r) => setTimeout(r, rule.delayMs));
356
+ res.writeHead(rule.status, { ...CATCH_HEADERS, "Content-Type": `${rule.contentType}; charset=utf-8` });
357
+ return res.end(method === "HEAD" ? void 0 : rule.body);
358
+ }
359
+ if (method === "OPTIONS") {
360
+ res.writeHead(204, { ...CATCH_HEADERS, "Access-Control-Allow-Methods": "*", "Access-Control-Allow-Headers": "*", "Access-Control-Max-Age": "600" });
361
+ return res.end();
362
+ }
363
+ return plain(200, "OK");
364
+ }
365
+ async function handleHooks(req, res, u, method, since) {
366
+ const q = u.searchParams;
367
+ const parts = u.pathname.split("/").filter(Boolean);
368
+ const path = q.get("path") || void 0;
369
+ if (path && (!path.startsWith("/") || path.length > 2048)) return send(res, 400, { error: "path must start with /." });
370
+ const hookMethod = methodName(q.get("method"));
371
+ if (hookMethod === "") return send(res, 400, { error: "method must be an HTTP method name (letters only, at most 20)." });
372
+ let afterId;
373
+ if (q.get("afterId")) {
374
+ afterId = Number(q.get("afterId"));
375
+ if (!Number.isInteger(afterId)) return send(res, 400, { error: "afterId must be a request id (a whole number)." });
376
+ }
377
+ const filter = (h) => (!path || h.path.startsWith(path)) && (!hookMethod || h.method === hookMethod) && (afterId === void 0 || h.id > afterId) && (since === void 0 || h.received >= since);
378
+ const bad = (error) => send(res, 400, { error });
379
+ const notFound = () => send(res, 404, { error: "No such request in this environment." });
380
+ if (parts.length === 2 && method === "GET") return send(res, 200, endpointJson());
381
+ if (parts[2] === "urls" && parts.length === 3 && method === "POST") {
382
+ const p = `/t-${randomLocal(6)}`;
383
+ return send(res, 201, { url: `${hookUrl()}${p}`, path: p });
384
+ }
385
+ if (parts[2] === "requests") {
386
+ if (parts.length === 3 && method === "GET") {
387
+ const take = clamp(int(q.get("take"), 50), 1, MAX_TAKE);
388
+ const skip = clamp(int(q.get("skip"), 0), 0, 1e4);
389
+ const items = hooks.filter(filter).sort((a, b) => b.id - a.id).slice(skip, skip + take).map(hookSummary);
390
+ return send(res, 200, { items, skip, take });
391
+ }
392
+ if (parts.length === 3 && method === "DELETE") {
393
+ const gone = hooks.filter((h) => !path || h.path.startsWith(path));
394
+ hooks = hooks.filter((h) => !gone.includes(h));
395
+ return send(res, 200, { deleted: gone.length });
396
+ }
397
+ if (parts.length === 4 && parts[3] === "wait" && method === "GET") {
398
+ const seconds = clamp(int(q.get("timeoutSeconds"), 30), 1, 120);
399
+ const found = await longPoll(res, seconds, () => hooks.filter(filter).sort((a, b) => a.id - b.id)[0]);
400
+ if (!found) {
401
+ res.statusCode = 204;
402
+ return res.end();
403
+ }
404
+ return send(res, 200, hookDetail(found));
405
+ }
406
+ if (parts.length >= 4 && /^\d+$/.test(parts[3])) {
407
+ const h = hooks.find((x) => x.id === Number(parts[3]));
408
+ if (parts.length === 4 && method === "GET") return h ? send(res, 200, hookDetail(h)) : notFound();
409
+ if (parts.length === 4 && method === "DELETE") {
410
+ if (!h) return notFound();
411
+ hooks = hooks.filter((x) => x !== h);
412
+ res.statusCode = 204;
413
+ return res.end();
414
+ }
415
+ if (parts.length === 5 && parts[4] === "body" && method === "GET") {
416
+ if (!h) return notFound();
417
+ res.writeHead(200, { "Content-Type": "application/octet-stream", "Content-Disposition": `attachment; filename="webhook-${h.id}.bin"` });
418
+ return res.end(h.body);
419
+ }
420
+ if (parts.length === 5 && parts[4] === "replay" && method === "POST") {
421
+ if (!h) return notFound();
422
+ const body = await readJson(req);
423
+ const refused = publicUrlProblem(body?.url);
424
+ if (refused) return bad(refused);
425
+ replays.push({ id: h.id, url: String(body.url).trim() });
426
+ return send(res, 200, { status: 200, durationMs: 1 });
427
+ }
428
+ }
429
+ }
430
+ if (parts[2] === "responses") {
431
+ if (parts.length === 3 && method === "GET") return send(res, 200, { items: rules.map(ruleJson) });
432
+ if (parts.length === 3 && method === "POST") {
433
+ const b = await readJson(req);
434
+ if (!b) return bad("The body must be a JSON object.");
435
+ const rulePath = b.path;
436
+ if (typeof rulePath !== "string" || !rulePath.startsWith("/") || rulePath.length > 2048) return bad("path must start with / (at most 2,048 characters).");
437
+ const ruleMethod = b.method === null || b.method === void 0 ? null : typeof b.method === "string" ? methodName(b.method) ?? null : "";
438
+ if (ruleMethod === "") return bad("method must be an HTTP method name (letters only, at most 20) or null for any method.");
439
+ const status = typeof b.status === "number" ? b.status : Number.NaN;
440
+ if (!Number.isInteger(status) || !(status >= 200 && status <= 299 || status >= 400 && status <= 599)) {
441
+ return bad("status must be 200-299 or 400-599 (no 1xx or 3xx).");
442
+ }
443
+ const contentType = typeof b.contentType === "string" && b.contentType.trim() ? b.contentType.trim().toLowerCase() : b.contentType === void 0 || b.contentType === null || b.contentType === "" ? "text/plain" : "";
444
+ if (!HOOK_CONTENT_TYPES.includes(contentType)) return bad(`contentType must be one of: ${HOOK_CONTENT_TYPES.join(", ")}.`);
445
+ const ruleBody = b.body ?? "";
446
+ if (typeof ruleBody !== "string" || Buffer.byteLength(ruleBody) > 8192) return bad("body must be text of at most 8 KB.");
447
+ const delayMs = b.delayMs ?? 0;
448
+ if (typeof delayMs !== "number" || !Number.isInteger(delayMs) || delayMs < 0 || delayMs > HOOK_LIMITS.maxDelayMs) {
449
+ return bad(`delayMs must be 0-${HOOK_LIMITS.maxDelayMs} (the plan's longest delay).`);
450
+ }
451
+ if (rules.length >= HOOK_LIMITS.responseRules) return bad(`Your plan allows ${HOOK_LIMITS.responseRules} custom responses per environment.`);
452
+ const rule = { id: ++ruleSeq, method: ruleMethod, path: rulePath, status, contentType, body: ruleBody, delayMs, created: Date.now() };
453
+ rules.push(rule);
454
+ return send(res, 201, ruleJson(rule));
455
+ }
456
+ if (parts.length === 4 && /^\d+$/.test(parts[3]) && method === "DELETE") {
457
+ const r = rules.find((x) => x.id === Number(parts[3]));
458
+ if (!r) return send(res, 404, { error: "No such custom response in this environment." });
459
+ rules = rules.filter((x) => x !== r);
460
+ res.statusCode = 204;
461
+ return res.end();
462
+ }
463
+ }
464
+ if (parts[2] === "forward" && parts.length === 3 && method === "PUT") {
465
+ const b = await readJson(req);
466
+ if (!b) return bad("The body must be a JSON object.");
467
+ if (b.url === null || b.url === void 0 || b.url === "") {
468
+ forwardUrl = null;
469
+ } else {
470
+ const refused = publicUrlProblem(b.url);
471
+ if (refused) return bad(refused);
472
+ forwardUrl = String(b.url).trim();
473
+ }
474
+ return send(res, 200, endpointJson());
475
+ }
476
+ return send(res, 404, { error: "Not found." });
477
+ }
204
478
  await new Promise((resolve, reject) => {
205
479
  server.once("error", reject);
206
480
  server.listen(options.port ?? 0, "127.0.0.1", () => resolve());
207
481
  });
208
482
  const port = server.address().port;
483
+ baseUrl = `http://127.0.0.1:${port}`;
209
484
  return {
210
- url: `http://127.0.0.1:${port}`,
485
+ url: baseUrl,
211
486
  apiKey,
212
487
  zone,
213
488
  requests,
@@ -216,10 +491,19 @@ async function startFakeMailPier(options = {}) {
216
491
  failures.push({ ...f });
217
492
  },
218
493
  count: () => store.length,
494
+ webhookUrl: hookUrl(),
495
+ catchWebhook,
496
+ webhookCount: () => hooks.length,
497
+ replays,
219
498
  reset: () => {
220
499
  store = [];
221
500
  failures = [];
222
501
  requests.length = 0;
502
+ hooks = [];
503
+ rules = [];
504
+ forwardUrl = null;
505
+ hookCounter = 0;
506
+ replays.length = 0;
223
507
  },
224
508
  close: () => new Promise((resolve) => {
225
509
  for (const w of [...waiters]) w();
@@ -254,9 +538,58 @@ var int = (v, d) => {
254
538
  return Number.isFinite(n) ? n : d;
255
539
  };
256
540
  var clamp = (n, lo, hi) => Math.min(Math.max(n, lo), hi);
257
- function randomLocal() {
541
+ function randomLocal(length = 10) {
258
542
  const abc = "abcdefghijklmnopqrstuvwxyz0123456789";
259
- return [...randomBytes(10)].map((b) => abc[b % abc.length]).join("");
543
+ return [...randomBytes(length)].map((b) => abc[b % abc.length]).join("");
544
+ }
545
+ var CATCH_HEADERS = {
546
+ "X-Content-Type-Options": "nosniff",
547
+ "Content-Security-Policy": "default-src 'none'; sandbox",
548
+ "X-Frame-Options": "DENY",
549
+ "Cache-Control": "no-store",
550
+ "Referrer-Policy": "no-referrer",
551
+ "X-Robots-Tag": "noindex",
552
+ "Access-Control-Allow-Origin": "*"
553
+ };
554
+ function methodName(v) {
555
+ const m = (v ?? "").trim();
556
+ if (!m || m === "*" || m.toUpperCase() === "ANY") return void 0;
557
+ return /^[A-Za-z]{1,20}$/.test(m) ? m.toUpperCase() : "";
558
+ }
559
+ function maskHeaders(pairs) {
560
+ return pairs.map(([n, v]) => [n, SECRET_HEADERS.has(n.toLowerCase()) ? "***" : v]);
561
+ }
562
+ function utf8(b) {
563
+ try {
564
+ return new TextDecoder("utf-8", { fatal: true }).decode(b);
565
+ } catch {
566
+ return void 0;
567
+ }
568
+ }
569
+ function publicUrlProblem(v) {
570
+ if (typeof v !== "string" || !v.trim()) return "url (an absolute http or https URL) is required.";
571
+ let u;
572
+ try {
573
+ u = new URL(v.trim());
574
+ } catch {
575
+ return "url must be an absolute http or https URL.";
576
+ }
577
+ if (u.protocol !== "http:" && u.protocol !== "https:") return "url must be an absolute http or https URL.";
578
+ const host = u.hostname.replace(/^\[|\]$/g, "").toLowerCase();
579
+ if (host === "localhost" || host.endsWith(".localhost") || isPrivateAddress(host)) {
580
+ return "url must be a public address: MailPier never calls private, loopback or link-local addresses.";
581
+ }
582
+ return void 0;
583
+ }
584
+ function isPrivateAddress(host) {
585
+ const m = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(host);
586
+ if (m) {
587
+ const a = Number(m[1]);
588
+ const b = Number(m[2]);
589
+ 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;
590
+ }
591
+ if (!host.includes(":")) return false;
592
+ return host === "::" || host === "::1" || host.startsWith("fc") || host.startsWith("fd") || host.startsWith("fe80") || host.startsWith("::ffff:");
260
593
  }
261
594
  function findLinks(html, text) {
262
595
  const out = [];
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mailpier/inbox",
3
- "version": "0.1.0",
4
- "description": "MailPier Inbox client for Node.js tests: a fresh email address per test, wait for the mail, read its code and links. Playwright fixture and Cypress commands included.",
3
+ "version": "0.1.1",
4
+ "description": "MailPier Inbox client for Node.js tests: a fresh email address per test, wait for the mail, read its code and links; wait for webhooks and forward them to localhost. Playwright fixture and Cypress commands included.",
5
5
  "license": "MIT",
6
6
  "author": "Solutions Group Unlimited",
7
7
  "homepage": "https://mailpier.io",
@@ -13,14 +13,19 @@
13
13
  "playwright",
14
14
  "cypress",
15
15
  "e2e",
16
+ "webhook",
16
17
  "mailpier"
17
18
  ],
18
19
  "type": "module",
19
20
  "engines": {
20
21
  "node": ">=18"
21
22
  },
23
+ "bin": {
24
+ "mailpier": "./dist/cli.js"
25
+ },
22
26
  "sideEffects": [
23
- "./dist/cypress/commands.*"
27
+ "./dist/cypress/commands.*",
28
+ "./dist/cli.*"
24
29
  ],
25
30
  "files": [
26
31
  "dist",
@@ -1,194 +0,0 @@
1
- /** A mailbox from a header: display name (may be null) and address. */
2
- interface InboxAddress {
3
- name?: string | null;
4
- address: string;
5
- }
6
- /** The parsed headers (what the sender wrote). */
7
- interface InboxHeaders {
8
- from?: InboxAddress | null;
9
- to?: InboxAddress[];
10
- cc?: InboxAddress[];
11
- replyTo?: InboxAddress | null;
12
- subject?: string | null;
13
- /** The Date header (ISO 8601); null when missing or unreadable. */
14
- date?: string | null;
15
- messageId?: string | null;
16
- }
17
- interface InboxLink {
18
- href: string;
19
- text?: string | null;
20
- }
21
- interface InboxAttachment {
22
- index: number;
23
- fileName?: string | null;
24
- contentType?: string | null;
25
- size: number;
26
- }
27
- /** A mail as the list call returns it. `to` holds the environment's own (envelope) recipients. */
28
- interface InboxMessageSummary {
29
- id: string;
30
- /** ISO 8601, UTC. */
31
- receivedUtc: string;
32
- from?: string | null;
33
- to: string[];
34
- subject?: string | null;
35
- sizeBytes: number;
36
- /** Exact up to 16 KiB, a best guess above; getMessage is exact. */
37
- hasAttachments: boolean;
38
- }
39
- /** The full JSON of GET /v1/messages/{id} and GET /v1/messages/wait. */
40
- interface InboxMessageData extends InboxMessageSummary {
41
- text?: string | null;
42
- /** The HTML part as received, NOT sanitised: never render it in a page of your own origin. */
43
- html?: string | null;
44
- headers?: InboxHeaders | null;
45
- links?: InboxLink[];
46
- /** One-time codes found in the mail (verification codes, OTPs, PINs), best guess first. */
47
- codes?: string[];
48
- attachments?: InboxAttachment[];
49
- /** Sender authentication verdicts (SPF/DKIM/DMARC) as the server reports them. */
50
- auth?: unknown;
51
- /** Spam check result as the server reports it. */
52
- spam?: unknown;
53
- }
54
- /** A full mail with helpers: `message.code` and `message.firstLink("verify")`. */
55
- declare class InboxMessage implements InboxMessageData {
56
- id: string;
57
- receivedUtc: string;
58
- from?: string | null;
59
- to: string[];
60
- subject?: string | null;
61
- sizeBytes: number;
62
- hasAttachments: boolean;
63
- text?: string | null;
64
- html?: string | null;
65
- headers?: InboxHeaders | null;
66
- links: InboxLink[];
67
- codes: string[];
68
- attachments: InboxAttachment[];
69
- auth?: unknown;
70
- spam?: unknown;
71
- constructor(data: InboxMessageData);
72
- /** The first one-time code in the mail (best guess first), or undefined when it has none. */
73
- get code(): string | undefined;
74
- /**
75
- * The first link whose address (or text) contains `contains` (case-insensitive), or the first link when it is omitted;
76
- * undefined when none matches.
77
- */
78
- firstLink(contains?: string): string | undefined;
79
- /** The plain JSON (what the API returned), e.g. to pass through a Cypress task. */
80
- toJSON(): InboxMessageData & {
81
- code?: string;
82
- };
83
- }
84
-
85
- /** The public API. */
86
- declare const DEFAULT_BASE_URL = "https://api.mailpier.io";
87
- /** The server caps one long-poll at 120 seconds; longer waits are made of several polls. */
88
- declare const MAX_POLL_SECONDS = 120;
89
- declare const VERSION = "0.1.0";
90
- interface MailPierInboxOptions {
91
- /** An API key from the environment's API keys page (`mpi_...`). Defaults to the MAILPIER_API_KEY environment variable. */
92
- apiKey?: string;
93
- /** API root; defaults to MAILPIER_BASE_URL or https://api.mailpier.io. */
94
- baseUrl?: string;
95
- /** How often one call is retried on 429 (after Retry-After), 502/503/504 and network errors. Default 5. */
96
- maxRetries?: number;
97
- /** The longest single pause between retries, in ms (Retry-After is honoured up to this). Default 60000. */
98
- maxRetryDelayMs?: number;
99
- /** A fetch implementation (default: the global fetch of Node 18+). */
100
- fetch?: typeof fetch;
101
- }
102
- interface NewAddressOptions {
103
- /** One of the environment's base domains; omitted for its default. */
104
- domain?: string;
105
- /** A readable start of the address (a-z, 0-9, '-', at most 30). */
106
- prefix?: string;
107
- }
108
- interface WaitForMessageOptions {
109
- /** The full address the mail was sent to. */
110
- to: string;
111
- /** Only a mail whose subject contains this (case-insensitive). */
112
- subjectContains?: string;
113
- /** How long to wait in total, in ms. Default 60000. */
114
- timeoutMs?: number;
115
- /** Only a mail received at or after this time. Pass the time your test started to ignore older mail to the same address. */
116
- since?: Date | string;
117
- /** Together with `since`: skip this mail id (and the ones stored before it in the same millisecond). */
118
- afterId?: string;
119
- signal?: AbortSignal;
120
- }
121
- interface ListMessagesOptions {
122
- to?: string;
123
- subjectContains?: string;
124
- since?: Date | string;
125
- afterId?: string;
126
- /** 1..100, default 50. */
127
- take?: number;
128
- skip?: number;
129
- signal?: AbortSignal;
130
- }
131
- interface DeleteAllResult {
132
- deleted: number;
133
- /** Mails that were also sent outside this environment; they expire with the retention period instead. */
134
- skippedShared: number;
135
- }
136
- /**
137
- * Client for the MailPier Inbox API. Create one per API key and reuse it.
138
- *
139
- * ```ts
140
- * const inbox = new MailPierInbox({ apiKey: process.env.MAILPIER_API_KEY });
141
- * const address = await inbox.newAddress({ prefix: "signup" });
142
- * // ... make your app send a mail to address ...
143
- * const mail = await inbox.waitForMessage({ to: address, subjectContains: "Confirm", timeoutMs: 60_000 });
144
- * mail.code; // "482913"
145
- * mail.firstLink("verify"); // "https://app.example.com/verify?t=..."
146
- * ```
147
- */
148
- declare class MailPierInbox {
149
- readonly baseUrl: string;
150
- private readonly apiKey;
151
- private readonly maxRetries;
152
- private readonly maxRetryDelayMs;
153
- private readonly fetchImpl;
154
- constructor(options?: MailPierInboxOptions);
155
- /** A fresh random address of the key's environment, e.g. `signup-k3v9q2mz7a@qa.acme.mailpier.io`. */
156
- newAddress(options?: NewAddressOptions): Promise<string>;
157
- /**
158
- * Waits until a mail to `to` arrives and returns it (the OLDEST match received at or after `since`).
159
- * Throws MailPierTimeoutError when nothing arrives within `timeoutMs`.
160
- */
161
- waitForMessage(options: WaitForMessageOptions): Promise<InboxMessage>;
162
- /**
163
- * Waits for the next mail to `to` after `previous` (one you already received): passes its receivedUtc as `since` and its id as
164
- * `afterId`, so a mail stored in the same millisecond is not missed and `previous` itself is never returned again.
165
- */
166
- waitForNextMessage(previous: Pick<InboxMessageSummary, "id" | "receivedUtc">, options: Omit<WaitForMessageOptions, "since" | "afterId">): Promise<InboxMessage>;
167
- /** Mail of the environment, newest first (at most 100 per call). */
168
- listMessages(options?: ListMessagesOptions): Promise<InboxMessageSummary[]>;
169
- /** One mail with its text, HTML, headers, links, codes and attachment list; null when it does not exist (or expired). */
170
- getMessage(id: string): Promise<InboxMessage | null>;
171
- /** The original message (.eml bytes); null when it does not exist. */
172
- getRaw(id: string): Promise<Uint8Array | null>;
173
- /** One attachment's bytes; null when it does not exist. */
174
- getAttachment(id: string, index: number): Promise<Uint8Array | null>;
175
- /** Deletes one mail. False when it did not exist. Throws (409) when the mail was also sent outside this environment. */
176
- deleteMessage(id: string): Promise<boolean>;
177
- /** Deletes every mail to one address; returns how many were deleted. */
178
- deleteAll(to: string): Promise<number>;
179
- /** Like deleteAll, but also says how many shared mails were skipped. */
180
- deleteAllDetailed(to: string): Promise<DeleteAllResult>;
181
- /** The key's account, environment, domains, plan and usage (GET /v1/me). */
182
- me(): Promise<Record<string, unknown>>;
183
- private download;
184
- private url;
185
- /**
186
- * One call with retries: 429 waits Retry-After (default 1 s), 502/503/504 and network errors back off 0.5, 1, 2, 4 ... s
187
- * (both capped at maxRetryDelayMs). Other errors throw MailPierInboxError with the server's {"error": "..."} text.
188
- */
189
- private request;
190
- private backoff;
191
- }
192
-
193
- export { DEFAULT_BASE_URL as D, MAX_POLL_SECONDS as M, VERSION as V, InboxMessage as e, MailPierInbox as h };
194
- export type { InboxAddress as I, ListMessagesOptions as L, NewAddressOptions as N, WaitForMessageOptions as W, DeleteAllResult as a, InboxAttachment as b, InboxHeaders as c, InboxLink as d, InboxMessageData as f, InboxMessageSummary as g, MailPierInboxOptions as i };