caelum0x 9429ff20da feat(mail): Scribase Mail Rust platform: sending core, accounts, auth, SMTP submission, Supabase hook, deliverability, TS SDK, docs
Clean-room Rust rewrite (written without reference to useSend source).
Crates: mail-types, mail-core, mail-server, mail-auth, mail-submit,
mail-hooks, mail-deliverability; sdks/ts (@scribase/mail); docs/.
Each verified by running locally (see plans/scribase-mail-rust-2026-11-12.md).
mail-mta, mail-inbound, mail-oci are still in progress and not in this commit.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-13 01:03:09 +03:00
..

@scribase/mail

TypeScript SDK for Scribase Mail: send email, manage domains, API keys and webhooks, verify webhook signatures, and run magic-link / OTP sign-in with JWT verification.

  • Zero runtime dependencies; fetch + WebCrypto only
  • Node 18+, Bun, Deno, Cloudflare Workers, Vercel Edge
  • ESM and CommonJS builds with type definitions
  • Every call returns { data, error }, the same shape as the Resend SDK, so migrating is an import change
npm install @scribase/mail

Send an email

import { ScribaseMail } from "@scribase/mail";

const mail = new ScribaseMail(process.env.SCRIBASE_MAIL_API_KEY);

const { data, error } = await mail.emails.send({
  from: "Acme <hello@acme.com>",
  to: ["jane@example.com"],
  subject: "Welcome",
  html: "<p>Thanks for signing up.</p>",
  text: "Thanks for signing up.",
});

if (error) throw new Error(`${error.name}: ${error.message}`);
console.log(data.id);

Options: new ScribaseMail(apiKey, { baseUrl, adminToken, fetch, userAgent }). Defaults: baseUrl = SCRIBASE_MAIL_BASE_URL or https://mail-api.scribase.com; apiKey = SCRIBASE_MAIL_API_KEY.

Already using the resend npm package?

Resend's SDK accepts a custom base URL, so you can keep it:

import { Resend } from "resend";
const resend = new Resend(process.env.SCRIBASE_MAIL_API_KEY, { baseUrl: "https://mail-api.scribase.com" });

or set RESEND_BASE_URL=https://mail-api.scribase.com and change nothing. (resend-node reads options.baseUrl ?? process.env.RESEND_BASE_URL ?? "https://api.resend.com".) emails.*, batch.send, domains.*, apiKeys.*, webhooks.* and webhooks.verify() keep working. Switch to @scribase/mail when you want the auth helpers or zero dependencies.

Emails

await mail.emails.send(payload, { idempotencyKey: "order-123" }); // replayed for 24h
await mail.emails.batch([p1, p2]);        // up to 100, no attachments
await mail.batch.send([p1, p2]);          // Resend-style alias
await mail.emails.get(id);
await mail.emails.list({ limit: 20, after: id });
await mail.emails.update({ id, scheduledAt: "2026-11-13T10:00:00Z" });
await mail.emails.cancel(id);
await mail.emails.reportEvent(id, { type: "bounced", recipient: "x@y.com", code: 550 });

camelCase (replyTo, scheduledAt, contentType) and snake_case (reply_to, ...) are both accepted.

Domains, API keys, webhooks

const { data: domain } = await mail.domains.create({ name: "acme.com" });
domain.records; // DKIM / SPF / DMARC records to publish
await mail.domains.verify(domain.id);
await mail.domains.get(domain.id); // status: not_started | pending | verified | failed
await mail.domains.update(domain.id, { openTracking: true });
await mail.domains.list(); await mail.domains.remove(domain.id);

const { data: key } = await mail.apiKeys.create({ name: "server", permission: "sending_access", domainId: domain.id });
key.token; // shown once
await mail.apiKeys.list(); await mail.apiKeys.remove(key.id);

const { data: hook } = await mail.webhooks.create({ endpoint: "https://acme.com/hooks/mail", events: ["email.delivered", "email.bounced"] });
hook.signing_secret; // whsec_...
await mail.webhooks.get(hook.id); await mail.webhooks.list();
await mail.webhooks.update(hook.id, { status: "disabled" }); await mail.webhooks.remove(hook.id);

Verify a webhook

HMAC-SHA256 over "{id}.{timestamp}.{body}", constant-time via crypto.subtle.verify, 5-minute timestamp tolerance. Accepts webhook-* or svix-* headers; headers can be a Headers, a Node headers object, or anything with get().

import { WebhookVerificationError } from "@scribase/mail";

export async function POST(req: Request) {
  const raw = await req.text(); // raw body, never re-serialize
  try {
    const event = await mail.webhooks.verify(raw, req.headers, process.env.MAIL_WEBHOOK_SECRET!);
    if (event.type === "email.bounced") console.log("bounced:", event.data.to);
    return new Response("{}", { status: 200 });
  } catch (e) {
    if (e instanceof WebhookVerificationError) return new Response("bad signature", { status: 400 });
    throw e;
  }
}

A client-free verifyWebhookSignature(payload, headers, secret, { toleranceSeconds }) is also exported.

The auth endpoints need no API key; they are addressed by project slug.

await mail.auth.sendMagicLink({ email, redirectTo: "https://acme.com/welcome", project: "acme" });
await mail.auth.sendOtp({ email, project: "acme" });
const { data: session } = await mail.auth.verifyOtp({ email, project: "acme", code: "482913" });
// { access_token, token_type: "Bearer", expires_in, purpose, user: { id, email, email_verified_at } }

await mail.auth.sendEmailVerification({ email, redirectTo, project });
await mail.auth.sendPasswordReset({ email, redirectTo, project });
await mail.auth.verifyMagicLink(token);          // JSON session instead of the redirect
await mail.auth.verifyToken({ token, audience }); // server-side check

Verify the session JWT locally (Ed25519 via WebCrypto, JWKS cached 5 minutes):

import { verifyJwt } from "@scribase/mail";

const claims = await mail.auth.verifyJwt(session.access_token, { audience: "acme" });
// or standalone:
const claims2 = await verifyJwt(token, {
  jwksUrl: "https://mail-api.scribase.com/.well-known/jwks.json",
  audience: "acme",
  issuer: "scribase-mail-auth",
});
// { iss, sub, aud, email, email_verified, project, purpose, iat, exp, jti }

Throws JwtVerificationError on a bad signature, unknown key, expiry, or audience/issuer mismatch. decodeJwt(token) reads claims without verifying (logging only).

Project admin (needs adminToken):

const admin = new ScribaseMail(undefined, { adminToken: process.env.AUTH_ADMIN_TOKEN }).auth.admin;
await admin.createProject({ slug: "acme", app_name: "Acme", from_address: "login@acme.com", allowed_redirect_origins: ["https://acme.com"] });
await admin.listProjects(); await admin.getProject(id); await admin.updateProject(id, { app_name: "Acme Inc" });

Errors

Nothing throws on HTTP errors. error is { statusCode, name, message } with the API's names: missing_api_key, validation_error, missing_required_field, restricted_api_key, rate_limit_exceeded, not_found, invalid_idempotent_request, application_error; connection failures give network_error with statusCode: 0. Auth-router errors ({ error, message }) are normalized to the same shape. Only webhooks.verify and verifyJwt throw, because a failed verification must not be mistaken for data.

Development

npm install
npm run build          # tsup: dist/index.js (ESM), dist/index.cjs, dist/index.d.ts
node examples/quickstart.mjs   # see the header of that file for the env vars

examples/quickstart.mjs walks every method against a running API: domain, key, webhook, send, idempotent replay, get, batch, schedule/update/cancel, permission check, webhook signature verification (positive and negative), then the magic-link and OTP flows with JWKS verification when SCRIBASE_MAIL_AUTH_URL is set.

License

MIT. Independent implementation, written without reference to useSend source.