caelum0x 70653ae53b feat(mail): mount the dashboard, email event + webhook delivery logs, billing shape, friendly bad magic links
mail-server serves apps/mail/dashboard at /dashboard/ (tower-http fs,
DASHBOARD_DIR, mock/ and MOUNT.md never served). New account-scoped,
Resend-shaped endpoints the dashboard reads: GET /emails/{id}/events
(status history with timestamps and a one-line detail from the stored
payload), GET /emails/{id}/webhook-deliveries and
GET /webhooks/{id}/deliveries (delivery log joined with event + endpoint),
GET /emails?test=true|false and GET /suppressions?q= server filters.
GET /billing now carries description, next_plan, upgrade_label,
current_period_end/renews_at; POST /billing/checkout accepts success_url
(own origin only) and returns url. mail-auth: a bad, used or expired link
opened in a browser redirects to <redirect_to>#error=invalid_token (or a
plain HTML page when the token was never ours); the dashboard shows the
message on the login form. Dashboard uses the server-side test filter,
portal via POST /billing/portal, docs updated.

Verified live against local Postgres mail_e2e + fake relay + webhook
listener: curl of every endpoint (404 for another account's ids, 401
without auth, 422 on test=maybe), and a headless-browser pass through the
real magic-link login, email timeline, webhook delivery log, usage card
and the expired-link redirect.

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

151 lines
7.3 KiB
JavaScript

// Emails: list (filtered by live/test) and detail with a status timeline.
import * as api from "../api.js";
import * as S from "../session.js";
import { append, badge, button, copyRow, el, errorBox, fullTime, label, loading, pageHead, table, testBadge, timeAgo, toast } from "../ui.js";
const testBanner = () =>
S.isTest()
? el("div.testbanner", el("b", "Test mode"), el("span.muted", "Showing emails sent with sk_test_ keys. Nothing here reached a real inbox."))
: null;
export async function emailsView(ctx) {
const wrap = el("div");
const list = el("div.card.tight");
const pager = el("div.row.end");
let cursor = { after: null, before: null };
async function load() {
list.replaceChildren(loading());
pager.replaceChildren();
try {
const test = S.isTest();
// Server-side live/test filter, so a page is never short in test mode.
const base = `?limit=50&test=${test}`;
const q = cursor.after ? `${base}&after=${cursor.after}` : cursor.before ? `${base}&before=${cursor.before}` : base;
const page = await api.listEmails(q);
const rows = (page.data || []).filter((e) => Boolean(e.test) === test);
list.replaceChildren(
table(
["Status", "To", "Subject", "From", { label: "Sent" }],
rows.map((e) =>
el(
"tr.click",
{ onclick: () => (location.hash = `#/emails/${e.id}`) },
el("td", badge(e.last_event), e.scheduled_at && e.last_event === "scheduled" ? el("span.small.muted", ` ${fullTime(e.scheduled_at)}`) : null),
el("td.trunc", (e.to || []).join(", ")),
el("td.trunc", e.subject || el("span.faint", "(no subject)")),
el("td.trunc.muted", e.from),
el("td.muted", { title: fullTime(e.created_at) }, timeAgo(e.created_at))
)
),
test ? "No test emails yet. Send one with an sk_test_ key." : "No emails yet. Send one from the setup guide."
)
);
if (page.has_more && rows.length) pager.append(button("Older", () => { cursor = { after: rows[rows.length - 1].id }; load(); }, "btn secondary sm"));
if (cursor.after || cursor.before) pager.append(button("Newest", () => { cursor = {}; load(); }, "btn secondary sm"));
} catch (e) {
list.replaceChildren(errorBox(e));
}
}
await load();
return append(wrap, [pageHead("Emails", "Every send in this account.", button("Refresh", load, "btn secondary")), testBanner(), list, pager]);
}
// Happy path, and where each other state sits on it:
// scheduled/canceled/suppressed replace "queued", failed replaces "sent"
// (it never left), bounced/complained/delayed come after "sent".
const FLOW = ["queued", "sent", "delivered"];
const PLACE = { scheduled: 0, canceled: 0, suppressed: 0, failed: 1, bounced: 2, complained: 2, delivery_delayed: 2 };
const PENDING_AFTER = new Set(["scheduled", "delivery_delayed"]);
const WARN = new Set(["scheduled", "delivery_delayed"]);
function timeline(status) {
const steps = [];
const idx = FLOW.indexOf(status);
if (idx >= 0) {
FLOW.forEach((s, i) => steps.push({ name: s, cls: i <= idx ? "done" : "" }));
} else {
const at = PLACE[status] ?? 0;
FLOW.forEach((s, i) => {
if (i < at) steps.push({ name: s, cls: "done" });
else if (i === at) steps.push({ name: status, cls: WARN.has(status) ? "done warn" : "done bad" });
else if (PENDING_AFTER.has(status)) steps.push({ name: s, cls: "" });
});
}
return el(
"div.timeline",
steps.map((s) => el(`div.step${s.cls ? "." + s.cls.split(" ").join(".") : ""}`, el("div.lbl", label(s.name))))
);
}
function eventsTable(events) {
const rows = (events?.data || events || []).map((ev) =>
el("tr", el("td", badge(ev.type?.replace(/^email\./, "") || ev.status)), el("td.muted", ev.message || ev.detail || ""), el("td.muted", fullTime(ev.created_at)))
);
return table(["Event", "Detail", "When"], rows, "No events recorded.");
}
function deliveriesTable(deliveries) {
const rows = (deliveries?.data || deliveries || []).map((d) =>
el("tr", el("td", d.type || d.event), el("td.trunc.mono", d.endpoint || d.url), el("td", badge(d.status || (d.response_status >= 200 && d.response_status < 300 ? "delivered" : "failed"))), el("td.muted", d.response_status ?? ""), el("td.muted", fullTime(d.created_at || d.delivered_at)))
);
return table(["Event", "Endpoint", "Result", "HTTP", "When"], rows, "No webhook deliveries for this email.");
}
export async function emailDetailView(ctx) {
const e = await api.getEmail(ctx.id);
const [events, deliveries] = await Promise.all([api.emailEvents(ctx.id), api.emailWebhookDeliveries(ctx.id)]);
const head = pageHead(
e.subject || "(no subject)",
`${e.from} to ${(e.to || []).join(", ")}`,
e.test ? testBadge() : null,
["queued", "scheduled"].includes(e.last_event)
? button("Cancel send", async () => { try { await api.cancelEmail(e.id); toast("Canceled"); location.reload(); } catch (err) { alert(err.message); } }, "btn danger")
: null,
el("a.btn.secondary", { href: "#/emails" }, "Back")
);
const headers = el(
"dl.kv",
el("dt", "Status"), el("dd", badge(e.last_event)),
el("dt", "Email ID"), el("dd", copyRow(e.id)),
el("dt", "Message-ID"), el("dd.mono", e.message_id || ""),
el("dt", "From"), el("dd", e.from),
el("dt", "To"), el("dd", (e.to || []).join(", ")),
e.cc?.length ? [el("dt", "Cc"), el("dd", e.cc.join(", "))] : null,
e.bcc?.length ? [el("dt", "Bcc"), el("dd", e.bcc.join(", "))] : null,
e.reply_to?.length ? [el("dt", "Reply-To"), el("dd", [].concat(e.reply_to).join(", "))] : null,
el("dt", "Created"), el("dd", fullTime(e.created_at)),
e.scheduled_at ? [el("dt", "Scheduled"), el("dd", fullTime(e.scheduled_at))] : null,
e.tags?.length ? [el("dt", "Tags"), el("dd", e.tags.map((t) => el("span.badge", { style: "margin-right:6px" }, `${t.name}=${t.value}`)))] : null
);
const body = el("div");
const tabs = el("div.tabs");
const show = (k) => {
[...tabs.children].forEach((b) => b.classList.toggle("on", b.dataset.k === k));
if (k === "html") {
const frame = el("iframe", { sandbox: "", style: "width:100%;height:360px;border:1px solid var(--line);border-radius:6px;background:#fff" });
body.replaceChildren(e.html ? frame : el("div.empty", "No HTML body."));
if (e.html) frame.srcdoc = e.html;
} else body.replaceChildren(el("pre", { style: "white-space:pre-wrap" }, e.text || "(no text body)"));
};
tabs.append(el("button", { type: "button", dataset: { k: "html" }, onclick: () => show("html") }, "HTML"), el("button", { type: "button", dataset: { k: "text" }, onclick: () => show("text") }, "Text"));
show(e.html ? "html" : "text");
return el(
"div",
head,
el("div.card", el("h2", "Delivery"), timeline(e.last_event),
events === null
? el("p.help", "Per-event timestamps are not exposed yet; this shows the latest status.")
: eventsTable(events)),
el("div.grid2",
el("div.card", el("h2", "Headers"), headers),
el("div.card", el("h2", "Body"), tabs, body)),
el("div.card", el("h2", "Webhook deliveries"),
deliveries === null
? el("p.help", "Delivery history per email is not exposed yet. Endpoints and their secrets are under Webhooks.")
: deliveriesTable(deliveries))
);
}