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>
157 lines
8.8 KiB
JavaScript
157 lines
8.8 KiB
JavaScript
// End-to-end walk through the SDK against a running Scribase Mail API.
|
|
//
|
|
// SCRIBASE_MAIL_BASE_URL=http://127.0.0.1:8790 \
|
|
// SCRIBASE_MAIL_API_KEY=sk_... \
|
|
// node examples/quickstart.mjs
|
|
//
|
|
// Optional: SCRIBASE_MAIL_AUTH_URL + SCRIBASE_MAIL_ADMIN_TOKEN to also run the
|
|
// magic-link / OTP flows (the auth router may be mounted on a different port in dev).
|
|
import { createServer } from "node:http";
|
|
import { readdir, readFile } from "node:fs/promises";
|
|
import { ScribaseMail, WebhookVerificationError } from "../dist/index.js";
|
|
|
|
const must = (label, result) => {
|
|
if (result.error) throw new Error(`${label}: ${result.error.statusCode} ${result.error.name}: ${result.error.message}`);
|
|
console.log(`ok ${label}`, JSON.stringify(result.data).slice(0, 160));
|
|
return result.data;
|
|
};
|
|
|
|
const mail = new ScribaseMail();
|
|
console.log("API:", mail.baseUrl);
|
|
|
|
// A fresh domain name per run; the server refuses duplicates.
|
|
const DOMAIN = process.env.SDK_DEMO_DOMAIN ?? `sdk-${Date.now().toString(36)}.example.com`;
|
|
|
|
// 1. Domain + key + webhook endpoint
|
|
const domain = must("domains.create", await mail.domains.create({ name: DOMAIN, openTracking: false }));
|
|
console.log(" DNS records to publish:", domain.records.map((r) => `${r.record} ${r.type} ${r.name}.${domain.name}`).join(" | "));
|
|
must("domains.verify", await mail.domains.verify(domain.id));
|
|
must("domains.get", await mail.domains.get(domain.id));
|
|
must("domains.list", await mail.domains.list());
|
|
|
|
const sendingKey = must("apiKeys.create", await mail.apiKeys.create({ name: "ci", permission: "sending_access", domainId: domain.id }));
|
|
must("apiKeys.list", await mail.apiKeys.list());
|
|
|
|
// Local receiver for webhook deliveries.
|
|
const received = [];
|
|
const receiver = createServer(async (req, res) => {
|
|
let raw = "";
|
|
for await (const chunk of req) raw += chunk;
|
|
received.push({ raw, headers: req.headers });
|
|
res.writeHead(200).end("{}");
|
|
});
|
|
await new Promise((r) => receiver.listen(0, "127.0.0.1", r));
|
|
const receiverUrl = `http://127.0.0.1:${receiver.address().port}/hooks/mail`;
|
|
|
|
const hook = must("webhooks.create", await mail.webhooks.create({ endpoint: receiverUrl, events: ["email.sent", "email.delivered", "email.bounced"] }));
|
|
must("webhooks.get", await mail.webhooks.get(hook.id));
|
|
must("webhooks.list", await mail.webhooks.list());
|
|
|
|
// 2. Send with the sending-only key, with an idempotency key.
|
|
const sender = new ScribaseMail(sendingKey.token, { baseUrl: mail.baseUrl });
|
|
const idempotencyKey = `quickstart-${Date.now()}`;
|
|
const sent = must("emails.send", await sender.emails.send({
|
|
from: `Scribase <hello@${DOMAIN}>`,
|
|
to: ["reader@example.org"],
|
|
subject: "Hello from the SDK",
|
|
html: "<p>It works.</p>",
|
|
text: "It works.",
|
|
replyTo: `support@${DOMAIN}`,
|
|
tags: [{ name: "category", value: "quickstart" }],
|
|
}, { idempotencyKey }));
|
|
const replay = must("emails.send (idempotent replay)", await sender.emails.send({ from: `Scribase <hello@${DOMAIN}>`, to: ["reader@example.org"], subject: "Hello from the SDK", html: "<p>It works.</p>", text: "It works.", replyTo: `support@${DOMAIN}`, tags: [{ name: "category", value: "quickstart" }] }, { idempotencyKey }));
|
|
if (replay.id !== sent.id) throw new Error("idempotent replay returned a different id");
|
|
|
|
const fetched = must("emails.get", await sender.emails.get(sent.id));
|
|
if (fetched.subject !== "Hello from the SDK") throw new Error("emails.get subject mismatch");
|
|
must("emails.batch", await sender.emails.batch([
|
|
{ from: `hello@${DOMAIN}`, to: "a@example.org", subject: "Batch 1", text: "one" },
|
|
{ from: `hello@${DOMAIN}`, to: "b@example.org", subject: "Batch 2", text: "two" },
|
|
]));
|
|
const inHours = (h) => new Date(Date.now() + h * 3600_000).toISOString();
|
|
const scheduled = must("emails.send (scheduled)", await sender.emails.send({ from: `hello@${DOMAIN}`, to: "c@example.org", subject: "Later", text: "later", scheduledAt: inHours(1) }));
|
|
must("emails.update", await sender.emails.update({ id: scheduled.id, scheduledAt: inHours(2) }));
|
|
must("emails.cancel", await sender.emails.cancel(scheduled.id));
|
|
must("emails.list", await mail.emails.list({ limit: 5 }));
|
|
|
|
// 3. Permission check: a sending key must be refused on /domains.
|
|
const refused = await sender.domains.list();
|
|
if (!refused.error || refused.error.name !== "restricted_api_key") throw new Error("sending key was not refused on /domains");
|
|
console.log("ok restricted key refused:", refused.error.statusCode, refused.error.name);
|
|
|
|
// 4. Webhook signature verification on the real delivery.
|
|
// Deliveries for the batch emails may arrive first; wait for the one about `sent`.
|
|
const forSent = (d) => d.raw.includes(sent.id);
|
|
for (let i = 0; i < 100 && !received.some(forSent); i++) await new Promise((r) => setTimeout(r, 200));
|
|
const delivery = received.find(forSent);
|
|
if (!delivery) throw new Error(`no webhook delivery for ${sent.id} within 20s (${received.length} other deliveries)`);
|
|
const event = await mail.webhooks.verify(delivery.raw, delivery.headers, hook.signing_secret);
|
|
console.log("ok webhooks.verify ->", event.type, event.data.email_id, `(${received.length} deliveries received)`);
|
|
if (event.data.email_id !== sent.id) throw new Error("verified payload is for a different email");
|
|
try {
|
|
await mail.webhooks.verify(delivery.raw.replace("Hello", "Hacked"), delivery.headers, hook.signing_secret);
|
|
throw new Error("tampered payload was accepted");
|
|
} catch (e) {
|
|
if (!(e instanceof WebhookVerificationError)) throw e;
|
|
console.log("ok tampered payload rejected:", e.message);
|
|
}
|
|
try {
|
|
await mail.webhooks.verify(delivery.raw, delivery.headers, "whsec_" + Buffer.alloc(24, 1).toString("base64"));
|
|
throw new Error("wrong secret was accepted");
|
|
} catch (e) {
|
|
if (!(e instanceof WebhookVerificationError)) throw e;
|
|
console.log("ok wrong secret rejected:", e.message);
|
|
}
|
|
receiver.close();
|
|
|
|
// 5. Auth: magic link + OTP + JWT verification, if an auth router is reachable.
|
|
const authUrl = process.env.SCRIBASE_MAIL_AUTH_URL;
|
|
if (authUrl) {
|
|
const auth = new ScribaseMail(undefined, { baseUrl: authUrl, adminToken: process.env.SCRIBASE_MAIL_ADMIN_TOKEN }).auth;
|
|
const slug = `sdk-${Date.now().toString(36)}`;
|
|
const project = must("auth.admin.createProject", await auth.admin.createProject({ slug, app_name: "SDK Demo", from_address: "login@example.com", allowed_redirect_origins: ["http://localhost:3000"] }));
|
|
must("auth.admin.listProjects", await auth.admin.listProjects());
|
|
|
|
const outbox = process.env.MAIL_AUTH_OUTBOX ?? "/tmp/mail-auth-outbox";
|
|
const before = new Set(await readdir(outbox).catch(() => []));
|
|
const newestEmail = async () => {
|
|
for (let i = 0; i < 20; i++) {
|
|
const files = (await readdir(outbox)).filter((f) => !before.has(f));
|
|
if (files.length) { before.add(files[0]); return readFile(`${outbox}/${files[0]}`, "utf8"); }
|
|
await new Promise((r) => setTimeout(r, 100));
|
|
}
|
|
throw new Error("no auth email appeared in " + outbox);
|
|
};
|
|
|
|
must("auth.sendMagicLink", await auth.sendMagicLink({ email: "person@example.org", redirectTo: "http://localhost:3000/welcome", project: slug }));
|
|
const linkMail = await newestEmail();
|
|
const token = linkMail.match(/[?&]token=([A-Za-z0-9_-]+)/)?.[1];
|
|
if (!token) throw new Error("no token in magic-link email");
|
|
const session = must("auth.verifyMagicLink", await auth.verifyMagicLink(token));
|
|
const second = await auth.verifyMagicLink(token);
|
|
if (!second.error) throw new Error("magic link was accepted twice");
|
|
console.log("ok second use of link refused:", second.error.statusCode, second.error.name);
|
|
|
|
const claims = await auth.verifyJwt(session.access_token, { audience: project.jwt_audience });
|
|
console.log("ok auth.verifyJwt (WebCrypto Ed25519 via JWKS) ->", claims.email, claims.purpose);
|
|
must("auth.verifyToken", await auth.verifyToken({ token: session.access_token, audience: project.jwt_audience }));
|
|
const badAud = await auth.verifyJwt(session.access_token, { audience: "someone-else" }).then(() => null, (e) => e);
|
|
if (!badAud) throw new Error("wrong audience accepted");
|
|
console.log("ok wrong audience rejected:", badAud.message);
|
|
|
|
must("auth.sendOtp", await auth.sendOtp({ email: "person@example.org", project: slug }));
|
|
const otpMail = await newestEmail();
|
|
const code = otpMail.match(/\b(\d{6})\b/)?.[1];
|
|
if (!code) throw new Error("no code in OTP email");
|
|
const wrong = await auth.verifyOtp({ email: "person@example.org", project: slug, code: code === "000000" ? "111111" : "000000" });
|
|
if (!wrong.error) throw new Error("wrong OTP accepted");
|
|
console.log("ok wrong OTP rejected:", wrong.error.name, "-", wrong.error.message);
|
|
const otpSession = must("auth.verifyOtp", await auth.verifyOtp({ email: "person@example.org", project: slug, code }));
|
|
await auth.verifyJwt(otpSession.access_token, { audience: project.jwt_audience });
|
|
console.log("ok OTP session JWT verified");
|
|
} else {
|
|
console.log("skip auth flows (set SCRIBASE_MAIL_AUTH_URL to run them)");
|
|
}
|
|
|
|
console.log("\nAll SDK calls succeeded.");
|