SPB Git

Repository Public

README.md 11.4 KB 227 lines markdown

1# @spboucher/spmail — TypeScript SDK for the SP Mail API23Client of the SP Mail REST API (`https://mail.spboucher.ai/api/v1`, contract in [`docs/API.md`](../../docs/API.md) and [`docs/OPENAPI.yaml`](../../docs/OPENAPI.yaml)).45- Zero runtime dependencies, ESM, global `fetch` and WebCrypto only: Node 20+, Bun, Deno, browsers, edge runtimes.6- Types generated from the OpenAPI document (`src/generated.ts`).7- Typed errors, automatic `Idempotency-Key`, safe retries, async iterators for pagination, `waitForDelivery`, webhook signature verification.89> An API key is a server-side secret. Do not ship one to a browser you do not control.1011## Install and build1213The package lives in this repository (it is not published to a registry).1415```bash16cd packages/sdk-ts17pnpm install --ignore-workspace   # dev dependencies only (typescript, yaml)18pnpm build                        # → dist/ (ESM + .d.ts)19```2021Use it from another project with a path dependency (`"@spboucher/spmail": "file:../sp-mail/packages/sdk-ts"`) or by bundling.2223## Quickstart2425```ts26import { SPMail } from "@spboucher/spmail"2728const mail = new SPMail({ apiKey: process.env.SPMAIL_API_KEY! })   // spm_xxxxxxxxxx_…2930const sent = await mail.messages.send({31  from: "notifications@example.org",32  to: ["owner@example.org", { email: "ops@example.org", name: "Ops" }],33  subject: "Disk at 91 %",34  text: "The /data volume is at 91 %.",35})36if (sent.status === "pending_approval") {37  // external recipient + key policy "approval": NOTHING was sent; an administrator must approve in SP Mail38} else {39  const final = await mail.waitForDelivery(sent.id, { timeoutMs: 60_000 })   // delivered | bounced | failed | cancelled40  console.log(final.status, final.recipients)41}4243for await (const m of mail.messages.iterate({ folder: "inbox", unread: true })) {44  console.log(m.received_at, m.from[0]?.email, m.subject)45}46```4748### Options4950```ts51new SPMail({52  apiKey,                                   // required53  baseUrl: "https://mail.spboucher.ai",     // default; "/api/v1" is appended when missing54  fetch,                                    // custom fetch (tests, proxies)55  timeoutMs: 30_000,                        // per HTTP attempt56  maxRetries: 2,                            // retries after the first attempt (retryable failures only)57  maxRetryDelayMs: 60_000,                  // longest Retry-After the client will sleep through58  allowInsecureHttp: false,                 // plain http:// is refused except on localhost59  defaultHeaders: { "user-agent": "my-app/1.0" },60})61```6263Every method takes a last optional argument `{ idempotencyKey?, signal?, timeoutMs?, maxRetries?, headers? }`.6465The key is held in a private field: it does not appear in `console.log(client)`, `JSON.stringify(client)`, `util.inspect` or in any error. The SDK logs nothing.6667## Resources6869| Resource | Methods |70|---|---|71| `mail.me()`, `mail.health()` | identity, scopes, usable addresses, limits · public health probe |72| `mail.messages` | `send`, `sendBatch`, `list`, `iterate`, `get`, `changes`, `reply`, `forward`, `update`, `markRead`, `markUnread`, `move`, `archive`, `delete`, `waitForDelivery` |73| `mail.messages.outbound` | `list`, `iterate`, `get` — status of sends, per recipient |74| `mail.messages.scheduled` | `list`, `iterate`, `cancel` |75| `mail.messages.attachments` | `list(messageId)`, `download(messageId, attachmentId)` → `{ data: Uint8Array, filename, size }` |76| `mail.threads` | `list`, `iterate`, `get` |77| `mail.drafts` | `create`, `list`, `iterate`, `get`, `update` (returns a **new id**), `delete`, `send` |78| `mail.folders` | `list`, `create` |79| `mail.files` | `upload({ data, filename, contentType?, address? })` → `file_…` id for `attachments` |80| `mail.addresses` | `list`, `get`, `create`, `update`, `delete`, `getAutomation`, `updateAutomation` |81| `mail.aliases` | `list`, `create`, `update`, `delete` |82| `mail.webhooks` | `create`, `list`, `get`, `update`, `delete`, `test`, `replay`, `deliveries.list/iterate/replay`, `verifySignature`, `constructEvent`, `sign` |83| `mail.events` | `list`, `iterate` |84| `mail.templates` | `list`, `get`, `render` |85| `mail.request(method, path, { query, body })` | escape hatch for an endpoint not wrapped yet |8687```ts88// attachment89const file = await mail.files.upload({ data: pdfBytes, filename: "report.pdf", contentType: "application/pdf" })90await mail.messages.send({ from, to, subject: "Report", text: "Attached.", attachments: [{ file_id: file.id }] })9192// read, reply, file away93const page = await mail.messages.list({ folder: "inbox", from: "billing", has_attachment: true, limit: 20 })94const message = await mail.messages.get(page.data[0].id)           // text, sanitised html, attachments, auth results95await mail.messages.reply(message.id, { text: "Received, thank you." })96await mail.messages.markRead(message.id)97await mail.messages.archive(message.id)9899// drafts, scheduling100const draft = await mail.drafts.create({ from, to, subject: "Draft", text: "v1" })101const edited = await mail.drafts.update(draft.id, { text: "v2" })   // edited.id !== draft.id102await mail.drafts.send(edited.id, { send_at: "2026-12-01T13:00:00Z" })103await mail.messages.scheduled.cancel(outboundId)104105// incremental sync106let { state } = await mail.messages.changes({ address })107const delta = await mail.messages.changes({ address, since: state })   // 409 resync_required → list again108```109110### Send by template111112```ts113const templates = await mail.templates.list()114const preview = await mail.templates.render(templates[0].id, { variables: { first_name: "Zoé", code: "424242" } })   // nothing is sent115await mail.messages.send({116  from: "notifications@example.org", to: ["zoe@example.org"],117  template_id: templates[0].id,118  variables: { first_name: "Zoé", code: "424242" },119})120```121122With `template_id`, omit `html`/`text` (`400 template_conflict`); every required variable must be given (`400 missing_variables`); unknown names are refused (`400 unknown_variables`).123124## Idempotency and retries125126- Creating POSTs (`messages.send`, `sendBatch`, `reply`, `forward`, `drafts.create`, `drafts.send`, `folders.create`, `addresses.create`, `aliases.create`, `webhooks.create`) carry an `Idempotency-Key`. The SDK generates one per call and **reuses it for every retry of that call**, so a network failure can never duplicate a send. Pass `{ idempotencyKey: "order-42" }` to make a retry of *your own process* idempotent as well (the API stores answers for 24 h; a different body with the same key → `409 idempotency_conflict`).127- Retried automatically, with exponential backoff and jitter (0.5 s, 1 s, 2 s… capped at 8 s), up to `maxRetries`:128  - network errors, timeouts, `502`/`503`/`504` and `409 idempotency_in_progress` — **only** for idempotent requests (`GET`, `PUT`, `DELETE`, flag/move/render calls) or requests carrying an idempotency key;129  - `429 rate_limited`, honouring `Retry-After` — for any request, because the API refused it before processing it. A `Retry-After` longer than `maxRetryDelayMs` is thrown instead.130- Never retried: `429 daily_send_limit_exceeded`, `files.upload` and `drafts.update` on 5xx/network errors (not idempotent), and every other 4xx.131132## Errors133134Every failure throws an `SPMailError` with `status`, `code`, `message`, `details`, `requestId`, `retryAfterSec`.135136| Class | When |137|---|---|138| `BadRequestError` | 400 — validation, `header_not_allowed`, `missing_variables`… |139| `AuthenticationError` | 401 — `invalid_api_key`, `key_revoked`, `key_expired` |140| `PermissionDeniedError` | 403 — `insufficient_scope` (`details.required`), `from_not_allowed`, `external_send_denied`… |141| `NotFoundError` | 404 — unknown **or** not visible to this key |142| `ConflictError` | 409 — `idempotency_conflict`, `resync_required`, `not_cancellable`, `address_taken`… |143| `UnprocessableEntityError` | 422 — reserved; the API currently answers validation failures with 400 |144| `RateLimitError` | 429 — `rate_limited`, `daily_send_limit_exceeded` |145| `ServerError` | 5xx |146| `ConnectionError` / `TimeoutError` | no answer (`status` 0); `waitForDelivery` timeout (`details.last` = last status seen) |147| `SignatureVerificationError` | `constructEvent` on a bad webhook signature |148149```ts150import { PermissionDeniedError, RateLimitError, SPMailError } from "@spboucher/spmail"151152try {153  await mail.messages.send({ from, to, subject, text })154} catch (e) {155  if (e instanceof PermissionDeniedError && e.code === "from_not_allowed") { /* this key cannot send from that address */ }156  else if (e instanceof RateLimitError) { /* e.retryAfterSec */ }157  else if (e instanceof SPMailError) console.error(e.status, e.code, e.message, e.requestId)158  else throw e159}160```161162## Webhooks163164`SPMail-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, t + "." + raw body)>`. Verify over the **raw body**, before any JSON parsing; the default replay window is 300 s; the comparison is constant-time. Deduplicate on `event.id` (deliveries are at-least-once).165166```ts167import { constructWebhookEvent, verifyWebhookSignature } from "@spboucher/spmail"168169const ok = await verifyWebhookSignature({ payload: rawBody, header: req.headers["spmail-signature"], secret: process.env.SPMAIL_WEBHOOK_SECRET!, toleranceSec: 300 })170const event = await constructWebhookEvent({ payload: rawBody, header, secret })   // throws SignatureVerificationError171```172173**Fastify**174175```ts176app.addContentTypeParser("application/json", { parseAs: "buffer" }, (_req, body, done) => done(null, body))   // keep the raw bytes177app.post("/hooks/spmail", async (req, reply) => {178  let event179  try {180    event = await constructWebhookEvent({ payload: req.body as Buffer, header: req.headers["spmail-signature"] as string, secret: process.env.SPMAIL_WEBHOOK_SECRET! })181  } catch { return reply.code(400).send() }182  if (await alreadySeen(event.id)) return reply.code(204).send()183  if (event.type === "message.received") await enqueue(event.data)184  return reply.code(204).send()185})186```187188**Express**189190```ts191app.post("/hooks/spmail", express.raw({ type: "application/json" }), async (req, res) => {192  try {193    const event = await constructWebhookEvent({ payload: req.body, header: req.get("SPMail-Signature"), secret: process.env.SPMAIL_WEBHOOK_SECRET! })194    /* dedupe on event.id, then handle */195    res.sendStatus(204)196  } catch { res.sendStatus(400) }197})198```199200**Next.js (App Router, Node or Edge runtime)**201202```ts203export async function POST(req: Request) {204  const raw = await req.text()205  try {206    const event = await constructWebhookEvent({ payload: raw, header: req.headers.get("spmail-signature"), secret: process.env.SPMAIL_WEBHOOK_SECRET! })207    /* dedupe on event.id, then handle */208    return new Response(null, { status: 204 })209  } catch { return new Response(null, { status: 400 }) }210}211```212213Answer 2xx within 10 s and do the work asynchronously; a non-2xx answer is retried (1 min, 5 min, 30 min, 2 h, 6 h, 24 h).214215## Generated types216217`pnpm generate` rewrites `src/generated.ts` from `docs/OPENAPI.yaml`; `pnpm generate:check` (run by the test suite) fails when the file is stale. The friendly names (`Message`, `MessageSummary`, `OutboundMessage`, `SendParams`, `Address`, `Webhook`, `Template`, `Me`…) and the full `Operations` map are exported from the package root, with `OPERATION_SCOPES` (the scopes each operation accepts).218219## Tests220221From the repository root (real server, real PostgreSQL, real mail server, test addresses on `stg.spboucher.ai` purged at the end):222223```bash224SPMAIL_TEST_PORT=8801 SPMAIL_TEST_DB=postgres://127.0.0.1/sp_mail_sdk_test \225  node --import tsx --test --test-concurrency=1 tests/integration/sdk-ts.test.ts226```227
Files main
Menu

Theme