SPB Git

Repository Public

README.md 11.4 KB

# @spboucher/spmail — TypeScript SDK for the SP Mail API

Client of the SP Mail REST API (https://mail.spboucher.ai/api/v1, contract in docs/API.md and docs/OPENAPI.yaml).

  • Zero runtime dependencies, ESM, global fetch and WebCrypto only: Node 20+, Bun, Deno, browsers, edge runtimes.
  • Types generated from the OpenAPI document (src/generated.ts).
  • Typed errors, automatic Idempotency-Key, safe retries, async iterators for pagination, waitForDelivery, webhook signature verification.

An API key is a server-side secret. Do not ship one to a browser you do not control.

# Install and build

The package lives in this repository (it is not published to a registry).

bash
cd packages/sdk-ts
pnpm install --ignore-workspace   # dev dependencies only (typescript, yaml)
pnpm build                        # → dist/ (ESM + .d.ts)

Use it from another project with a path dependency ("@spboucher/spmail": "file:../sp-mail/packages/sdk-ts") or by bundling.

# Quickstart

ts
import { SPMail } from "@spboucher/spmail"

const mail = new SPMail({ apiKey: process.env.SPMAIL_API_KEY! })   // spm_xxxxxxxxxx_…

const sent = await mail.messages.send({
  from: "notifications@example.org",
  to: ["owner@example.org", { email: "ops@example.org", name: "Ops" }],
  subject: "Disk at 91 %",
  text: "The /data volume is at 91 %.",
})
if (sent.status === "pending_approval") {
  // external recipient + key policy "approval": NOTHING was sent; an administrator must approve in SP Mail
} else {
  const final = await mail.waitForDelivery(sent.id, { timeoutMs: 60_000 })   // delivered | bounced | failed | cancelled
  console.log(final.status, final.recipients)
}

for await (const m of mail.messages.iterate({ folder: "inbox", unread: true })) {
  console.log(m.received_at, m.from[0]?.email, m.subject)
}

# Options

ts
new SPMail({
  apiKey,                                   // required
  baseUrl: "https://mail.spboucher.ai",     // default; "/api/v1" is appended when missing
  fetch,                                    // custom fetch (tests, proxies)
  timeoutMs: 30_000,                        // per HTTP attempt
  maxRetries: 2,                            // retries after the first attempt (retryable failures only)
  maxRetryDelayMs: 60_000,                  // longest Retry-After the client will sleep through
  allowInsecureHttp: false,                 // plain http:// is refused except on localhost
  defaultHeaders: { "user-agent": "my-app/1.0" },
})

Every method takes a last optional argument { idempotencyKey?, signal?, timeoutMs?, maxRetries?, headers? }.

The 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.

# Resources

Resource Methods
mail.me(), mail.health() identity, scopes, usable addresses, limits · public health probe
mail.messages send, sendBatch, list, iterate, get, changes, reply, forward, update, markRead, markUnread, move, archive, delete, waitForDelivery
mail.messages.outbound list, iterate, get — status of sends, per recipient
mail.messages.scheduled list, iterate, cancel
mail.messages.attachments list(messageId), download(messageId, attachmentId) → { data: Uint8Array, filename, size }
mail.threads list, iterate, get
mail.drafts create, list, iterate, get, update (returns a new id), delete, send
mail.folders list, create
mail.files upload({ data, filename, contentType?, address? }) → file_… id for attachments
mail.addresses list, get, create, update, delete, getAutomation, updateAutomation
mail.aliases list, create, update, delete
mail.webhooks create, list, get, update, delete, test, replay, deliveries.list/iterate/replay, verifySignature, constructEvent, sign
mail.events list, iterate
mail.templates list, get, render
mail.request(method, path, { query, body }) escape hatch for an endpoint not wrapped yet
ts
// attachment
const file = await mail.files.upload({ data: pdfBytes, filename: "report.pdf", contentType: "application/pdf" })
await mail.messages.send({ from, to, subject: "Report", text: "Attached.", attachments: [{ file_id: file.id }] })

// read, reply, file away
const page = await mail.messages.list({ folder: "inbox", from: "billing", has_attachment: true, limit: 20 })
const message = await mail.messages.get(page.data[0].id)           // text, sanitised html, attachments, auth results
await mail.messages.reply(message.id, { text: "Received, thank you." })
await mail.messages.markRead(message.id)
await mail.messages.archive(message.id)

// drafts, scheduling
const draft = await mail.drafts.create({ from, to, subject: "Draft", text: "v1" })
const edited = await mail.drafts.update(draft.id, { text: "v2" })   // edited.id !== draft.id
await mail.drafts.send(edited.id, { send_at: "2026-12-01T13:00:00Z" })
await mail.messages.scheduled.cancel(outboundId)

// incremental sync
let { state } = await mail.messages.changes({ address })
const delta = await mail.messages.changes({ address, since: state })   // 409 resync_required → list again

# Send by template

ts
const templates = await mail.templates.list()
const preview = await mail.templates.render(templates[0].id, { variables: { first_name: "Zoé", code: "424242" } })   // nothing is sent
await mail.messages.send({
  from: "notifications@example.org", to: ["zoe@example.org"],
  template_id: templates[0].id,
  variables: { first_name: "Zoé", code: "424242" },
})

With template_id, omit html/text (400 template_conflict); every required variable must be given (400 missing_variables); unknown names are refused (400 unknown_variables).

# Idempotency and retries

  • 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).
  • Retried automatically, with exponential backoff and jitter (0.5 s, 1 s, 2 s… capped at 8 s), up to maxRetries:
    • 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;
    • 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.
  • Never retried: 429 daily_send_limit_exceeded, files.upload and drafts.update on 5xx/network errors (not idempotent), and every other 4xx.

# Errors

Every failure throws an SPMailError with status, code, message, details, requestId, retryAfterSec.

Class When
BadRequestError 400 — validation, header_not_allowed, missing_variables…
AuthenticationError 401 — invalid_api_key, key_revoked, key_expired
PermissionDeniedError 403 — insufficient_scope (details.required), from_not_allowed, external_send_denied…
NotFoundError 404 — unknown or not visible to this key
ConflictError 409 — idempotency_conflict, resync_required, not_cancellable, address_taken…
UnprocessableEntityError 422 — reserved; the API currently answers validation failures with 400
RateLimitError 429 — rate_limited, daily_send_limit_exceeded
ServerError 5xx
ConnectionError / TimeoutError no answer (status 0); waitForDelivery timeout (details.last = last status seen)
SignatureVerificationError constructEvent on a bad webhook signature
ts
import { PermissionDeniedError, RateLimitError, SPMailError } from "@spboucher/spmail"

try {
  await mail.messages.send({ from, to, subject, text })
} catch (e) {
  if (e instanceof PermissionDeniedError && e.code === "from_not_allowed") { /* this key cannot send from that address */ }
  else if (e instanceof RateLimitError) { /* e.retryAfterSec */ }
  else if (e instanceof SPMailError) console.error(e.status, e.code, e.message, e.requestId)
  else throw e
}

# Webhooks

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).

ts
import { constructWebhookEvent, verifyWebhookSignature } from "@spboucher/spmail"

const ok = await verifyWebhookSignature({ payload: rawBody, header: req.headers["spmail-signature"], secret: process.env.SPMAIL_WEBHOOK_SECRET!, toleranceSec: 300 })
const event = await constructWebhookEvent({ payload: rawBody, header, secret })   // throws SignatureVerificationError

Fastify

ts
app.addContentTypeParser("application/json", { parseAs: "buffer" }, (_req, body, done) => done(null, body))   // keep the raw bytes
app.post("/hooks/spmail", async (req, reply) => {
  let event
  try {
    event = await constructWebhookEvent({ payload: req.body as Buffer, header: req.headers["spmail-signature"] as string, secret: process.env.SPMAIL_WEBHOOK_SECRET! })
  } catch { return reply.code(400).send() }
  if (await alreadySeen(event.id)) return reply.code(204).send()
  if (event.type === "message.received") await enqueue(event.data)
  return reply.code(204).send()
})

Express

ts
app.post("/hooks/spmail", express.raw({ type: "application/json" }), async (req, res) => {
  try {
    const event = await constructWebhookEvent({ payload: req.body, header: req.get("SPMail-Signature"), secret: process.env.SPMAIL_WEBHOOK_SECRET! })
    /* dedupe on event.id, then handle */
    res.sendStatus(204)
  } catch { res.sendStatus(400) }
})

Next.js (App Router, Node or Edge runtime)

ts
export async function POST(req: Request) {
  const raw = await req.text()
  try {
    const event = await constructWebhookEvent({ payload: raw, header: req.headers.get("spmail-signature"), secret: process.env.SPMAIL_WEBHOOK_SECRET! })
    /* dedupe on event.id, then handle */
    return new Response(null, { status: 204 })
  } catch { return new Response(null, { status: 400 }) }
}

Answer 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).

# Generated types

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).

# Tests

From the repository root (real server, real PostgreSQL, real mail server, test addresses on stg.spboucher.ai purged at the end):

bash
SPMAIL_TEST_PORT=8801 SPMAIL_TEST_DB=postgres://127.0.0.1/sp_mail_sdk_test \
  node --import tsx --test --test-concurrency=1 tests/integration/sdk-ts.test.ts
Files main
Menu

Theme