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

165 lines
6.7 KiB
JavaScript

// Thin client for the mail-server JSON API. Errors use Resend's shape
// `{statusCode, name, message}` and surface as ApiError.
import { accountId, signOut, token } from "./session.js";
const cfg = () => window.MAIL_DASHBOARD || {};
export const apiBase = () => (cfg().apiBase || "").replace(/\/$/, "");
export const projectSlug = () => cfg().project || "dashboard";
export class ApiError extends Error {
constructor(status, name, message) {
super(message || name || `HTTP ${status}`);
this.status = status;
this.name = name || "error";
}
get missing() {
return this.status === 404 || this.status === 405 || this.status === 501;
}
}
/**
* request("GET", "/emails?limit=50")
* request("POST", "/domains", {name})
* opts.noAccount — leave out X-Account-Id (for `/accounts`, `/auth/*`).
* opts.auth — explicit bearer (an API key) instead of the session.
*/
export async function request(method, path, body, opts = {}) {
const headers = { accept: "application/json" };
const bearer = opts.auth || token();
if (bearer) headers.authorization = `Bearer ${bearer}`;
const acct = accountId();
if (acct && !opts.noAccount && !opts.auth) headers["x-account-id"] = acct;
if (body !== undefined) headers["content-type"] = "application/json";
let res;
try {
res = await fetch(apiBase() + path, {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
});
} catch (e) {
throw new ApiError(0, "network_error", "Cannot reach the server.");
}
const text = await res.text();
let data = null;
if (text) {
try {
data = JSON.parse(text);
} catch {
data = { message: text };
}
}
if (!res.ok) {
const name = data?.name || "error";
if (res.status === 401 && !opts.auth && name !== "restricted_api_key") {
// Session token rejected: sign out so the next render shows login.
signOut();
}
throw new ApiError(res.status, name, data?.message || res.statusText);
}
return data;
}
export const get = (path, opts) => request("GET", path, undefined, opts);
export const post = (path, body, opts) => request("POST", path, body ?? {}, opts);
export const patch = (path, body, opts) => request("PATCH", path, body ?? {}, opts);
export const del = (path, opts) => request("DELETE", path, undefined, opts);
/** GET that treats "endpoint not there yet" as `null` instead of an error. */
export async function getOptional(path, opts) {
try {
return await get(path, opts);
} catch (e) {
if (e instanceof ApiError && e.missing) return null;
throw e;
}
}
// --- Auth (mail-auth router) -------------------------------------------------
export const requestMagicLink = (email) =>
post(
"/auth/magic-link",
{
email,
project: projectSlug(),
redirect_to: location.origin + location.pathname,
},
{ noAccount: true }
);
// --- Accounts ----------------------------------------------------------------
export const listAccounts = () => get("/accounts", { noAccount: true });
export const createAccount = (name) => post("/accounts", { name }, { noAccount: true });
export const getAccount = (id) => get(`/accounts/${id}`);
export const renameAccount = (id, name) => patch(`/accounts/${id}`, { name });
// --- Members -----------------------------------------------------------------
export const listMembers = (id) => get(`/accounts/${id}/members`);
export const invite = (id, email, role) => post(`/accounts/${id}/members`, { email, role });
export const setRole = (id, userId, role) => patch(`/accounts/${id}/members/${userId}`, { role });
export const removeMember = (id, userId) => del(`/accounts/${id}/members/${userId}`);
export const revokeInvite = (id, inviteId) => del(`/accounts/${id}/invites/${inviteId}`);
// --- Domains -----------------------------------------------------------------
export const listDomains = () => get("/domains");
export const getDomain = (id) => get(`/domains/${id}`);
export const createDomain = (body) => post("/domains", body);
export const verifyDomain = (id) => post(`/domains/${id}/verify`);
export const updateDomain = (id, body) => patch(`/domains/${id}`, body);
export const deleteDomain = (id) => del(`/domains/${id}`);
// --- API keys ----------------------------------------------------------------
export const listKeys = () => get("/api-keys");
export const createKey = (body) => post("/api-keys", body);
export const deleteKey = (id) => del(`/api-keys/${id}`);
// --- Emails ------------------------------------------------------------------
export const listEmails = (q = "") => get(`/emails${q}`);
export const getEmail = (id) => get(`/emails/${id}`);
export const sendEmail = (body, auth) => post("/emails", body, auth ? { auth } : undefined);
export const cancelEmail = (id) => post(`/emails/${id}/cancel`);
/** Status history + webhook delivery log; null only on an older server. */
export const emailEvents = (id) => getOptional(`/emails/${id}/events`);
export const emailWebhookDeliveries = (id) => getOptional(`/emails/${id}/webhook-deliveries`);
// --- Webhooks ----------------------------------------------------------------
export const listWebhooks = () => get("/webhooks");
export const getWebhook = (id) => get(`/webhooks/${id}`);
export const createWebhook = (endpoint, events) => post("/webhooks", { endpoint, events });
export const updateWebhook = (id, body) => patch(`/webhooks/${id}`, body);
export const deleteWebhook = (id) => del(`/webhooks/${id}`);
/** Delivery log of one endpoint; null only on an older server. */
export const webhookDeliveries = (id) => getOptional(`/webhooks/${id}/deliveries?limit=100`);
// --- Suppressions ------------------------------------------------------------
/** Server-side substring search over address + reason when `q` is given. */
export const listSuppressions = (q = "") => get(`/suppressions?limit=1000${q ? `&q=${encodeURIComponent(q)}` : ""}`);
export const addSuppression = (email) => post("/suppressions", { email });
export const removeSuppression = (email) => del(`/suppressions/${encodeURIComponent(email)}`);
// --- Usage / billing ---------------------------------------------------------
export const usage = (from, to) =>
get(`/usage${from ? `?from=${from}&to=${to || ""}` : ""}`);
/** Plan + usage + limits; null only on a server without billing routes. */
export const billing = () => getOptional("/billing");
export const checkout = (plan) =>
post("/billing/checkout", {
plan,
success_url: location.origin + location.pathname + "#/usage?upgraded=1",
cancel_url: location.origin + location.pathname + "#/usage",
});
/** Dodo customer portal link (24 h); 409 until a checkout has happened. */
export const billingPortal = () => post("/billing/portal");
export const auditLog = () => get("/audit-log?limit=50");