@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 CHANGED
@@ -1,6 +1,21 @@
1
1
  # Changelog
2
2
 
3
- ## 0.1.0 (unreleased)
3
+ ## 0.1.1 (2026-11-16)
4
+ - Webhook inspector: `getWebhookEndpoint`, `createWebhookUrl`, `waitForWebhook` (long-poll, `MailPierWebhookTimeoutError`, a
5
+ `MailPierTimeoutError`), `listWebhooks`, `getWebhook`, `getWebhookBody`, `deleteWebhook`, `deleteWebhooks`, `replayWebhook`,
6
+ `addWebhookResponse`, `listWebhookResponses`, `deleteWebhookResponse`; `WebhookRequest` with `jsonBody()`, `header()`, `bytes()`.
7
+ Replay and adding a custom response are not retried on 502/504/network errors (they must not run twice).
8
+ - `mailpier listen <port|url> [--path] [--key] [--api]` (npm bin; `npx @mailpier/inbox listen 5000`): forwards caught requests to
9
+ localhost. The caught path stays below the target's path (`%` escaped except `%2F`, a path that would climb out with `/../` is
10
+ skipped), control characters from the request are printed as `\xHH`, and every header "Hide secrets" masks is left out.
11
+ - Fake API: like the real catcher, no `X-MailPier-Request-Id` on catch answers, and "Hide secrets" also masks `X-Api-Key`, `Api-Key`,
12
+ `X-Auth-Token`, `X-Access-Token` and `X-Amz-Security-Token`.
13
+ - Playwright fixture: `inbox.createWebhookUrl()`, `inbox.waitForWebhook(path)` (next request per path, none from before the test).
14
+ Cypress: `cy.mailpierCreateWebhookUrl()`, `cy.mailpierWaitForWebhook(path)` (tasks `mailpier:createWebhookUrl`,
15
+ `mailpier:waitForWebhook`).
16
+ - Fake API: the `/v1/hooks/*` endpoints, `catchWebhook()`, a catch route at `webhookUrl`, `replays`, option `webhooks: false`.
17
+
18
+ ## 0.1.0 (2026-11-14)
4
19
  - First version: `MailPierInbox` (newAddress, waitForMessage, waitForNextMessage, listMessages, getMessage, getRaw,
5
20
  getAttachment, deleteMessage, deleteAll, me), `message.code` / `message.firstLink()`, retries on 429 (Retry-After) and
6
21
  502/503/504/network errors, ESM + CJS builds with types.
package/README.md CHANGED
@@ -1,8 +1,9 @@
1
1
  # @mailpier/inbox
2
2
 
3
3
  Node.js client for [MailPier Inbox](https://mailpier.io): give each test its own email address, wait for the mail your app
4
- sends, and read its one-time code and links. TypeScript types, ESM and CommonJS, Node 18+, no runtime dependencies.
5
- Includes a **Playwright fixture**, **Cypress commands** and a **fake MailPier API** for offline tests.
4
+ sends, and read its one-time code and links. Catch your app's **webhooks** too, and forward them to localhost. TypeScript
5
+ types, ESM and CommonJS, Node 18+, no runtime dependencies. Includes a **Playwright fixture**, **Cypress commands**, the
6
+ `mailpier listen` command and a **fake MailPier API** for offline tests.
6
7
 
7
8
  ## Quick start
8
9
 
@@ -76,6 +77,61 @@ the message JSON plus `code` and `firstLink`), `cy.mailpierWaitForCode(to)`, `cy
76
77
  `cy.mailpierDeleteAll(to)`. The API key stays in the Cypress Node process (`MAILPIER_API_KEY`); it never reaches the browser.
77
78
  Example: `cypress/`.
78
79
 
80
+ ## Webhooks
81
+
82
+ Every environment has a catch URL (`https://hook.gather-io.com/<token>`): any request to it, or to any path below it, is stored
83
+ (method, path, query, headers, body) and can be waited for like a mail. Use a unique path per test, as with addresses.
84
+
85
+ ```ts
86
+ import { test, expect } from "@mailpier/inbox/playwright";
87
+
88
+ test("paying an order sends the order.paid webhook", async ({ page, inbox }) => {
89
+ const hook = await inbox.createWebhookUrl(); // { url: "https://hook.gather-io.com/<token>/t-8f2k1x", path: "/t-8f2k1x" }
90
+ await page.goto("/settings/webhooks");
91
+ await page.getByLabel("Webhook URL").fill(hook.url); // your app sends its webhooks there
92
+ await page.goto("/orders/42");
93
+ await page.getByRole("button", { name: "Pay" }).click();
94
+
95
+ const request = await inbox.waitForWebhook(hook.path, { method: "POST", timeoutSeconds: 30 });
96
+ expect(request.jsonBody()).toMatchObject({ event: "order.paid", orderId: "42" });
97
+ expect(request.header("X-Signature")).toBeTruthy();
98
+ });
99
+ ```
100
+
101
+ The fixture's `waitForWebhook(path)` returns the next request to that path on each call, and never one caught before the test
102
+ started (so a fixed path like `/stripe` is safe too). Cypress: `cy.mailpierCreateWebhookUrl()` and
103
+ `cy.mailpierWaitForWebhook(path, { method?, timeoutSeconds? })` (yields the request JSON). Runnable examples:
104
+ `playwright/webhook.spec.ts`, `cypress/e2e/webhook.cy.ts`.
105
+
106
+ | Call | What it does |
107
+ |---|---|
108
+ | `getWebhookEndpoint()` | The catch URL, `paused`, `hideSecrets`, `forwardUrl` and the plan's `limits`. |
109
+ | `createWebhookUrl()` | `{ url, path }` with a fresh random path (nothing is stored; any path works without it). |
110
+ | `waitForWebhook({ path?, method?, afterId?, since?, timeoutSeconds?, signal? })` | The **oldest** request newer than `afterId`/`since` whose path starts with `path`; long-polls; throws `MailPierWebhookTimeoutError` (a `MailPierTimeoutError`). Default 60 s. |
111
+ | `listWebhooks({ path?, method?, afterId?, since?, take?, skip? })` | Newest first, at most 100 per call. |
112
+ | `getWebhook(id)` / `getWebhookBody(id)` | Full request / raw body bytes; `null` when gone. |
113
+ | `deleteWebhook(id)` / `deleteWebhooks({ path? })` | Clean up (without `path`: every request of the environment). |
114
+ | `replayWebhook(id, url)` | Sends it again to a **public** URL; `{ status, durationMs }` of the target. A refused URL throws 400, a target that gave no answer 502; never retried on 502/504/network errors (it must not arrive twice). |
115
+ | `addWebhookResponse({ path, status?, method?, contentType?, body?, delayMs? })` | A custom answer (status 200-299/400-599, JSON/text/XML, delay) for requests whose path starts with `path`. |
116
+ | `listWebhookResponses()` / `deleteWebhookResponse(id)` | The environment's custom answers. |
117
+ | `request.jsonBody()` / `request.header(name)` / `request.bytes()` | The body as JSON (throws when it is not), a header (case-insensitive), the body bytes. |
118
+
119
+ A request also has `body` (UTF-8 text, else `null` and `bodyBase64`), `json`, `form` (url-encoded fields), `query`, `headers`,
120
+ `sourceIp` and `status` (what the catch URL answered). With "Hide secrets" on (the default) `Authorization`, `Proxy-Authorization`,
121
+ `Cookie`, `X-Api-Key`, `Api-Key`, `X-Auth-Token`, `X-Access-Token` and `X-Amz-Security-Token` read `***` (webhook signature headers stay
122
+ visible); the query string is stored as sent. Requests are deleted with the environment's mail retention.
123
+
124
+ ### Forward webhooks to localhost
125
+
126
+ ```
127
+ npx @mailpier/inbox listen 5000 # or: listen http://localhost:5000/api --path /stripe
128
+ ```
129
+
130
+ Prints the catch URL, then sends every new request to `http://localhost:5000` + its path (same method, query, headers and body)
131
+ and prints `POST /stripe -> 200 (34 ms)`. The key comes from `--key` or `MAILPIER_API_KEY` (`--api` / `MAILPIER_BASE_URL` for
132
+ the API root). It starts after the newest request already caught, reconnects with backoff, and stops on Ctrl+C. Only the given
133
+ target is called; the caller of the catch URL already got the environment's answer.
134
+
79
135
  ## Offline tests: the fake API
80
136
 
81
137
  ```ts
@@ -88,6 +144,10 @@ await fake.close();
88
144
 
89
145
  It implements every public endpoint with the real JSON shapes and errors, extracts links and 4-8 digit codes like the service,
90
146
  and can simulate failures (`fake.failNext({ status: 429, retryAfter: 1 })`). `POST /_fake/deliver` lets another process add mail.
147
+ Webhooks: `fake.catchWebhook({ method, path, query, headers, body })` stores a request in-process, and `fake.webhookUrl`
148
+ (`http://127.0.0.1:<port>/_fake/hook/<token>`) catches real HTTP calls like the hosted catch URL, custom responses included.
149
+ The fake never sends anything: replays are only recorded (`fake.replays`). `startFakeMailPier({ webhooks: false })` answers
150
+ 404 like the service while the feature is off.
91
151
 
92
152
  ## Develop
93
153
 
@@ -20,6 +20,17 @@ var MailPierTimeoutError = class extends Error {
20
20
  this.timeoutMs = timeoutMs;
21
21
  }
22
22
  };
23
+ var MailPierWebhookTimeoutError = class extends MailPierTimeoutError {
24
+ path;
25
+ method;
26
+ constructor(path, timeoutMs, method) {
27
+ super(path, timeoutMs);
28
+ this.message = `No ${method ? `${method.toUpperCase()} ` : ""}webhook request to ${path} arrived within ${Math.round(timeoutMs / 1e3)} seconds.`;
29
+ this.name = "MailPierWebhookTimeoutError";
30
+ this.path = path;
31
+ this.method = method;
32
+ }
33
+ };
23
34
 
24
35
  // src/message.ts
25
36
  var InboxMessage = class {
@@ -82,10 +93,72 @@ function normaliseCodes(codes) {
82
93
  return out;
83
94
  }
84
95
 
96
+ // src/webhook.ts
97
+ var WebhookRequest = class {
98
+ id;
99
+ receivedUtc;
100
+ method = "";
101
+ path = "/";
102
+ query;
103
+ contentType;
104
+ size = 0;
105
+ environment;
106
+ status = 0;
107
+ url;
108
+ headers = [];
109
+ body;
110
+ bodyBase64;
111
+ json;
112
+ form;
113
+ sourceIp;
114
+ headersTruncated = false;
115
+ ruleId;
116
+ forwardStatus;
117
+ constructor(data) {
118
+ Object.assign(this, data);
119
+ this.headers = Array.isArray(data.headers) ? data.headers.filter((h) => h && typeof h.name === "string").map((h) => ({ name: h.name, value: String(h.value ?? "") })) : [];
120
+ this.headersTruncated = data.headersTruncated === true;
121
+ }
122
+ /** The first value of a header (name case-insensitive), or undefined when the request has none. */
123
+ header(name) {
124
+ const n = name.toLowerCase();
125
+ return this.headers.find((h) => h.name.toLowerCase() === n)?.value;
126
+ }
127
+ /** The body bytes (from `body` or `bodyBase64`); empty when the request had no body. */
128
+ bytes() {
129
+ if (typeof this.bodyBase64 === "string" && this.bodyBase64) {
130
+ const bin = atob(this.bodyBase64);
131
+ const out = new Uint8Array(bin.length);
132
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
133
+ return out;
134
+ }
135
+ return new TextEncoder().encode(this.body ?? "");
136
+ }
137
+ /**
138
+ * The body as JSON: the server's parsed `json`, or the text body parsed here (a JSON body sent with another content type).
139
+ * Throws when the body is not JSON.
140
+ */
141
+ jsonBody() {
142
+ if (this.json !== void 0 && this.json !== null) return this.json;
143
+ if (typeof this.body === "string" && this.body.trim()) {
144
+ try {
145
+ return JSON.parse(this.body);
146
+ } catch {
147
+ }
148
+ }
149
+ throw new Error(`The body of ${this.method} ${this.path} (request ${this.id}, ${this.contentType ?? "no content type"}) is not JSON.`);
150
+ }
151
+ /** The plain JSON (what the API returned), e.g. to pass through a Cypress task. */
152
+ toJSON() {
153
+ const { ...plain } = this;
154
+ return plain;
155
+ }
156
+ };
157
+
85
158
  // src/client.ts
86
159
  var DEFAULT_BASE_URL = "https://api.mailpier.io";
87
160
  var MAX_POLL_SECONDS = 120;
88
- var VERSION = "0.1.0";
161
+ var VERSION = "0.1.1";
89
162
  var sleep = (ms, signal) => new Promise((resolve, reject) => {
90
163
  if (signal?.aborted) return reject(signal.reason);
91
164
  const t = setTimeout(() => {
@@ -107,6 +180,11 @@ function env(name) {
107
180
  const v = p?.env?.[name];
108
181
  return v && v.trim() ? v.trim() : void 0;
109
182
  }
183
+ function webhookPath(path) {
184
+ const p = path?.trim();
185
+ if (!p) return void 0;
186
+ return p.startsWith("/") ? p : `/${p}`;
187
+ }
110
188
  var MailPierInbox = class {
111
189
  baseUrl;
112
190
  apiKey;
@@ -215,6 +293,129 @@ var MailPierInbox = class {
215
293
  const resp = await this.request("GET", "/v1/me", {});
216
294
  return await resp.json();
217
295
  }
296
+ // ------------------------------------------------------------------ Webhook inspector (/v1/hooks; 404 while the feature is off)
297
+ /** The environment's catch URL (made on first use), its switches and the plan's webhook limits. */
298
+ async getWebhookEndpoint() {
299
+ const resp = await this.request("GET", "/v1/hooks", {});
300
+ const json = await resp.json();
301
+ if (!json?.url) throw new MailPierInboxError(resp.status, "The server returned no webhook URL.");
302
+ return json;
303
+ }
304
+ /**
305
+ * The catch URL with a fresh random path, e.g. `{ url: "https://hook.gather-io.com/<token>/t-8f2k1x", path: "/t-8f2k1x" }`.
306
+ * Give `url` to the app under test and wait with `waitForWebhook({ path })`. Nothing is stored: any path works without this call.
307
+ */
308
+ async createWebhookUrl() {
309
+ const resp = await this.request("POST", "/v1/hooks/urls", {});
310
+ const json = await resp.json();
311
+ if (!json?.url || !json.path) throw new MailPierInboxError(resp.status, "The server returned no webhook URL.");
312
+ return { url: json.url, path: json.path };
313
+ }
314
+ /**
315
+ * Waits until a request to the catch URL arrives and returns it: the OLDEST match newer than `afterId` / `since`.
316
+ * Throws MailPierWebhookTimeoutError (a MailPierTimeoutError) when nothing arrives within `timeoutSeconds`.
317
+ */
318
+ async waitForWebhook(options = {}) {
319
+ const path = webhookPath(options.path);
320
+ const method = options.method?.trim() || void 0;
321
+ const timeoutSeconds = options.timeoutSeconds ?? 60;
322
+ if (!(timeoutSeconds > 0)) throw new Error("timeoutSeconds must be greater than 0.");
323
+ const timeoutMs = timeoutSeconds * 1e3;
324
+ const deadline = Date.now() + timeoutMs;
325
+ const since = iso(options.since);
326
+ for (; ; ) {
327
+ const left = deadline - Date.now();
328
+ const seconds = Math.min(Math.max(Math.ceil(left / 1e3), 1), MAX_POLL_SECONDS);
329
+ const resp = await this.request("GET", "/v1/hooks/requests/wait", {
330
+ path,
331
+ method,
332
+ afterId: options.afterId,
333
+ since,
334
+ timeoutSeconds: seconds
335
+ }, { signal: options.signal, timeoutMs: (seconds + 30) * 1e3 });
336
+ if (resp.status !== 204) return new WebhookRequest(await resp.json());
337
+ if (Date.now() >= deadline) throw new MailPierWebhookTimeoutError(path ?? "/", timeoutMs, method);
338
+ }
339
+ }
340
+ /** Caught requests of the environment, newest first (at most 100 per call). */
341
+ async listWebhooks(options = {}) {
342
+ const resp = await this.request("GET", "/v1/hooks/requests", {
343
+ path: webhookPath(options.path),
344
+ method: options.method?.trim() || void 0,
345
+ afterId: options.afterId,
346
+ since: iso(options.since),
347
+ take: options.take ?? 50,
348
+ skip: options.skip ?? 0
349
+ }, { signal: options.signal });
350
+ const json = await resp.json();
351
+ return json?.items ?? [];
352
+ }
353
+ /** One caught request with headers and body; null when it does not exist (or expired). */
354
+ async getWebhook(id) {
355
+ const resp = await this.request("GET", `/v1/hooks/requests/${encodeURIComponent(String(id))}`, {}, { allow404: true });
356
+ if (resp.status === 404) return null;
357
+ return new WebhookRequest(await resp.json());
358
+ }
359
+ /** The raw body bytes of a caught request; null when it does not exist. */
360
+ getWebhookBody(id) {
361
+ return this.download(`/v1/hooks/requests/${encodeURIComponent(String(id))}/body`);
362
+ }
363
+ /** Deletes one caught request. False when it did not exist. */
364
+ async deleteWebhook(id) {
365
+ const resp = await this.request("DELETE", `/v1/hooks/requests/${encodeURIComponent(String(id))}`, {}, { allow404: true });
366
+ return resp.status !== 404;
367
+ }
368
+ /** Deletes the caught requests whose path starts with `path` (every request of the environment when omitted); returns how many. */
369
+ async deleteWebhooks(options = {}) {
370
+ const resp = await this.request("DELETE", "/v1/hooks/requests", { path: webhookPath(options.path) });
371
+ const json = await resp.json();
372
+ return json?.deleted ?? 0;
373
+ }
374
+ /**
375
+ * Sends a caught request again (method, path, query, headers, body) to `url`, a PUBLIC http(s) address (MailPier never calls
376
+ * private or loopback addresses: 400). Not retried on 502/504 or network errors, so the target never gets it twice.
377
+ */
378
+ async replayWebhook(id, url) {
379
+ if (!url?.trim()) throw new Error("replayWebhook needs the URL to send the request to.");
380
+ const resp = await this.request(
381
+ "POST",
382
+ `/v1/hooks/requests/${encodeURIComponent(String(id))}/replay`,
383
+ {},
384
+ { body: JSON.stringify({ url: url.trim() }), once: true }
385
+ );
386
+ const json = await resp.json();
387
+ return { status: json?.status ?? null, durationMs: json?.durationMs ?? null, error: json?.error ?? null };
388
+ }
389
+ /**
390
+ * Adds a custom response: requests whose path starts with `rule.path` (and of `rule.method`, when given) get this status,
391
+ * content type, body and delay instead of 200 OK. Throws MailPierInboxError (400) when it is invalid or over the plan's count.
392
+ */
393
+ async addWebhookResponse(rule) {
394
+ const path = webhookPath(rule?.path);
395
+ if (!path) throw new Error('addWebhookResponse needs a path (e.g. "/stripe"; "/" for every request).');
396
+ const isObject = rule.body !== void 0 && rule.body !== null && typeof rule.body === "object";
397
+ const payload = {
398
+ method: rule.method?.trim() ? rule.method.trim().toUpperCase() : null,
399
+ path,
400
+ status: rule.status ?? 200,
401
+ contentType: rule.contentType ?? (isObject ? "application/json" : "text/plain"),
402
+ body: isObject ? JSON.stringify(rule.body) : rule.body ?? "",
403
+ delayMs: rule.delayMs ?? 0
404
+ };
405
+ const resp = await this.request("POST", "/v1/hooks/responses", {}, { body: JSON.stringify(payload), once: true });
406
+ return await resp.json();
407
+ }
408
+ /** The environment's custom responses. */
409
+ async listWebhookResponses() {
410
+ const resp = await this.request("GET", "/v1/hooks/responses", {});
411
+ const json = await resp.json();
412
+ return json?.items ?? [];
413
+ }
414
+ /** Deletes a custom response. False when it did not exist. */
415
+ async deleteWebhookResponse(id) {
416
+ const resp = await this.request("DELETE", `/v1/hooks/responses/${encodeURIComponent(String(id))}`, {}, { allow404: true });
417
+ return resp.status !== 404;
418
+ }
218
419
  // ------------------------------------------------------------------ plumbing
219
420
  async download(path) {
220
421
  const resp = await this.request("GET", path, {}, { allow404: true, accept: "*/*" });
@@ -230,6 +431,8 @@ var MailPierInbox = class {
230
431
  /**
231
432
  * 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
232
433
  * (both capped at maxRetryDelayMs). Other errors throw MailPierInboxError with the server's {"error": "..."} text.
434
+ * `once`: a call that must not run twice (replay, add a rule) is retried only on 429 and 503 (refused before any work), never
435
+ * on 502/504 or network errors (it may have been done).
233
436
  */
234
437
  async request(method, path, query, o = {}) {
235
438
  const url = this.url(path, query);
@@ -255,7 +458,7 @@ var MailPierInbox = class {
255
458
  clearTimeout(timer);
256
459
  o.signal?.removeEventListener("abort", onAbort);
257
460
  if (o.signal?.aborted) throw err;
258
- if (attempt >= this.maxRetries) {
461
+ if (attempt >= this.maxRetries || o.once) {
259
462
  throw new MailPierInboxError(0, `Could not reach MailPier Inbox at ${this.baseUrl}: ${err instanceof Error ? err.message : String(err)}`);
260
463
  }
261
464
  await sleep(this.backoff(attempt), o.signal);
@@ -273,7 +476,8 @@ var MailPierInbox = class {
273
476
  }
274
477
  throw new MailPierInboxError(429, message ?? "Too many requests.", retryAfter);
275
478
  }
276
- if ((resp.status === 502 || resp.status === 503 || resp.status === 504) && attempt < this.maxRetries) {
479
+ const retryable = resp.status === 503 || !o.once && (resp.status === 502 || resp.status === 504);
480
+ if (retryable && attempt < this.maxRetries) {
277
481
  await sleep(this.backoff(attempt), o.signal);
278
482
  continue;
279
483
  }
@@ -309,9 +513,12 @@ function parseRetryAfter(v) {
309
513
  export {
310
514
  MailPierInboxError,
311
515
  MailPierTimeoutError,
516
+ MailPierWebhookTimeoutError,
312
517
  InboxMessage,
518
+ WebhookRequest,
313
519
  DEFAULT_BASE_URL,
314
520
  MAX_POLL_SECONDS,
315
521
  VERSION,
522
+ webhookPath,
316
523
  MailPierInbox
317
524
  };