Repository Public
1// SP Mail Next — organisation : étiquettes, recherches enregistrées, extraits, signatures, préférences de rédaction et reprise d'un envoi retenu.2// Tout est au niveau de l'utilisateur (valable dans toutes ses boîtes) et vit en base ; l'état des messages reste dans JMAP (mots-clés lbl_…).3import crypto from "node:crypto"4import type { FastifyInstance } from "fastify"5import { z } from "zod"6import { sql } from "../db.js"7import { jmapOk } from "../mailjmap.js"8import { cancelOutbound, outboundById } from "../outbound.js"9import { htmlToText, sanitizeHtml } from "../sanitize.js"10import { bad, parse, zUuid } from "../util.js"11import { nextUser, userMailbox, userMailboxes } from "./common.js"12import { parseQuery } from "./query.js"1314export const LIMITS = { labels: 200, saved_searches: 100, snippets: 300, signatures: 50 } as const15type Table = keyof typeof LIMITS16// Les dix teintes du système de design (DESIGN-SYSTEM-NEXT §2) — mêmes valeurs dans les trois clients.17const PALETTE = ["#b3261e", "#a14a00", "#7a5c00", "#2e6b2e", "#00695c", "#1d5fa8", "#4a4fb5", "#7a3fa0", "#a8327a", "#5c5f66"]1819// ------------------------------------------------------------------ outils communs20const zColor = z.string().regex(/^#[0-9a-fA-F]{6}$/, "expected #rrggbb").transform((s) => s.toLowerCase())21const zName = (max: number) => z.string().trim().min(1).max(max).refine((s) => !/[\u0000-\u001f\u007f]/.test(s), "control characters are not allowed")22const zPosition = z.number().int().min(0).max(10_000)23const iso = (d: Date | string | null) => (d ? new Date(d).toISOString() : null)24const idOf = (req: { params: unknown }) => {25 const id = (req.params as { id?: string }).id ?? ""26 if (!zUuid.safeParse(id).success) throw bad("not_found", 404)27 return id28}29/** Clés réellement présentes dans le corps (zod 4 : `.partial()` garderait les valeurs par défaut — un PATCH n'applique que ce qui est envoyé). */30const has = (raw: unknown, key: string) => !!raw && typeof raw === "object" && Object.prototype.hasOwnProperty.call(raw, key)3132async function assertRoom(table: Table, userId: string) {33 const [r] = await sql`select count(*)::int as n from ${sql(table)} where user_id = ${userId}`34 if (r.n >= LIMITS[table]) throw bad("limit_reached", 409, `At most ${LIMITS[table]} ${table.replace("_", " ")} per user`)35}36const nextPosition = async (table: Table, userId: string) => (await sql`select coalesce(max(position) + 1, 0)::int as p from ${sql(table)} where user_id = ${userId}`)[0].p as number37/** Place l'élément à l'index demandé et renumérote les autres (0..n-1), en une transaction. */38async function place(table: Table, userId: string, id: string, position: number) {39 await sql.begin(async (tx) => {40 const rows = await tx`select id from ${tx(table)} where user_id = ${userId} order by position, created_at, id for update`41 const ids = rows.map((r) => r.id as string).filter((x) => x !== id)42 ids.splice(Math.min(position, ids.length), 0, id)43 for (const [i, x] of ids.entries()) await tx`update ${tx(table)} set position = ${i} where id = ${x} and position <> ${i}`44 })45}46async function remove(table: Table, userId: string, id: string) {47 const r = await sql`delete from ${sql(table)} where id = ${id} and user_id = ${userId} returning id`48 if (!r.length) throw bad("not_found", 404)49 return { ok: true }50}51const isUnique = (e: unknown) => (e as { code?: string })?.code === "23505"5253// ------------------------------------------------------------------ étiquettes54const presentLabel = (l: Record<string, any>) => ({ id: l.id, name: l.name, color: l.color, keyword: l.keyword, position: l.position })55/** Étiquettes de l'utilisateur : nom replié → mot-clé (pour `label:` dans la recherche). */56export async function labelsOf(userId: string) {57 return (await sql`select id, name, color, keyword, position from labels where user_id = ${userId} order by position, created_at, id`).map(presentLabel)58}5960// ------------------------------------------------------------------ recherches enregistrées61const presentSearch = (s: Record<string, any>) => ({ id: s.id, name: s.name, query: s.query, mailbox_ids: s.mailbox_ids ?? null, icon: s.icon ?? null, color: s.color ?? null, pinned: s.pinned, position: s.position, notify: s.notify, updated_at: iso(s.updated_at) })62function checkQuery(q: string) {63 const p = parseQuery(q)64 if (p.errors.length) throw bad("invalid_query", 400, p.errors.map((e) => `${e.token || "query"}: ${e.message}`).join("; ").slice(0, 500))65}66async function checkMailboxes(userId: string, ids: string[] | null): Promise<string[] | null> {67 if (ids === null) return null68 for (const id of ids) await userMailbox(userId, id)69 return [...new Set(ids)]70}7172// ------------------------------------------------------------------ extraits73const presentSnippet = (s: Record<string, any>) => ({ id: s.id, name: s.name, shortcut: s.shortcut ?? null, subject: s.subject ?? null, html: s.html, text: s.text, position: s.position, updated_at: iso(s.updated_at) })74const zShortcut = z.string().trim().toLowerCase().regex(/^;?[a-z0-9_-]{1,24}$/, "1–24 characters of a-z 0-9 _ -").transform((s) => s.replace(/^;/, ""))75const zHtml = z.string().max(200_000)76const zText = z.string().max(200_000)7778// ------------------------------------------------------------------ signatures79const presentSignature = (s: Record<string, any>) => ({ id: s.id, source: "user" as const, read_only: false, name: s.name, html: s.html, text: s.text, default_for: s.default_for ?? [], default_for_replies: s.default_for_replies ?? [], position: s.position, updated_at: iso(s.updated_at) })80/** Adresses au nom desquelles l'utilisateur peut écrire (ses boîtes et celles partagées avec droit d'envoi). */81async function sendableAddresses(userId: string) {82 const boxes = (await userMailboxes(userId)).filter((m) => m.can_send)83 if (!boxes.length) return []84 return sql`select id, address, display_name, signature_text, signature_html, updated_at from addresses where mailbox_id = any(${boxes.map((b) => b.id)}::uuid[]) order by address`85}86async function checkAddressIds(userId: string, ids: string[]): Promise<string[]> {87 const mine = new Set((await sendableAddresses(userId)).map((a) => a.id as string))88 const unknown = ids.filter((id) => !mine.has(id))89 if (unknown.length) throw bad("unknown_address", 400, "default_for / default_for_replies must be ids of addresses you can send from")90 return [...new Set(ids)]91}92/** Une adresse n'a qu'une signature par défaut : celle qui la revendique la retire des autres. */93async function claim(tx: typeof sql, userId: string, id: string, col: "default_for" | "default_for_replies", ids: string[]) {94 if (!ids.length) return95 await tx`update signatures set ${tx(col)} = (select coalesce(array_agg(x), '{}') from unnest(${tx(col)}) x where x <> all(${ids}::uuid[])), updated_at = now()96 where user_id = ${userId} and id <> ${id} and ${tx(col)} && ${ids}::uuid[]`97}9899// ------------------------------------------------------------------ préférences de rédaction100const zSensitive = z.string().trim().toLowerCase().max(254).regex(/^(@[a-z0-9.-]+\.[a-z]{2,}|[^\s@]+@[a-z0-9.-]+\.[a-z]{2,})$/, "an address or @domain")101const zComposePrefs = z.object({102 undo_seconds: z.number().int().min(0).max(120).default(10),103 sensitive: z.array(zSensitive).max(200).default([]),104 warn_missing_attachment: z.boolean().default(true),105 warn_external: z.boolean().default(false),106}).strict()107export type ComposePrefs = z.infer<typeof zComposePrefs>108export async function composePrefs(userId: string): Promise<ComposePrefs> {109 const [r] = await sql`select prefs from compose_prefs where user_id = ${userId}`110 const p = zComposePrefs.safeParse(r?.prefs ?? {})111 return p.success ? p.data : zComposePrefs.parse({})112}113114export function organizeRoutes(app: FastifyInstance) {115 // ---------------------------------------------------------------- étiquettes116 app.get("/api/next/labels", async (req) => ({ data: await labelsOf((await nextUser(req)).userId) }))117 app.post("/api/next/labels", async (req, reply) => {118 const a = await nextUser(req)119 const b = parse(z.object({ name: zName(40), color: zColor.optional(), position: zPosition.optional() }).strict(), req.body)120 await assertRoom("labels", a.userId)121 const position = await nextPosition("labels", a.userId)122 let row: Record<string, any> | undefined123 // Le mot-clé est attribué par le serveur et ne change jamais : renommer une étiquette ne touche aucun message.124 for (let i = 0; i < 5 && !row; i++) {125 try {126 ;[row] = await sql`insert into labels (user_id, name, color, keyword, position) values (${a.userId}, ${b.name}, ${b.color ?? PALETTE[position % PALETTE.length]}, ${`lbl_${crypto.randomBytes(4).toString("hex")}`}, ${position}) returning *`127 } catch (e) {128 if (!isUnique(e)) throw e129 if (String((e as { constraint_name?: string }).constraint_name ?? "").includes("name")) throw bad("name_taken", 409, "A label with this name already exists")130 }131 }132 if (!row) throw bad("internal", 500)133 if (b.position !== undefined) await place("labels", a.userId, row.id, b.position)134 return reply.status(201).send(presentLabel((await sql`select * from labels where id = ${row.id}`)[0]))135 })136 app.patch("/api/next/labels/:id", async (req) => {137 const a = await nextUser(req)138 const id = idOf(req)139 const b = parse(z.object({ name: zName(40).optional(), color: zColor.optional(), position: zPosition.optional() }).strict(), req.body)140 const [cur] = await sql`select * from labels where id = ${id} and user_id = ${a.userId}`141 if (!cur) throw bad("not_found", 404)142 try {143 await sql`update labels set name = ${b.name ?? cur.name}, color = ${b.color ?? cur.color}, updated_at = now() where id = ${id}`144 } catch (e) {145 if (isUnique(e)) throw bad("name_taken", 409, "A label with this name already exists")146 throw e147 }148 if (b.position !== undefined) await place("labels", a.userId, id, b.position)149 return presentLabel((await sql`select * from labels where id = ${id}`)[0])150 })151 // Supprimer une étiquette ne modifie aucun message : les clients ignorent les mots-clés lbl_ inconnus.152 app.delete("/api/next/labels/:id", async (req) => remove("labels", (await nextUser(req)).userId, idOf(req)))153154 // ---------------------------------------------------------------- recherches enregistrées155 const zSearch = z.object({156 name: zName(80), query: z.string().trim().min(1).max(1000), mailbox_ids: z.array(zUuid).max(100).nullable().default(null),157 icon: z.string().trim().max(40).nullable().default(null), color: zColor.nullable().default(null), pinned: z.boolean().default(false), notify: z.boolean().default(false), position: zPosition.optional(),158 }).strict()159 app.get("/api/next/searches", async (req) => {160 const a = await nextUser(req)161 return { data: (await sql`select * from saved_searches where user_id = ${a.userId} order by position, created_at, id`).map(presentSearch) }162 })163 app.post("/api/next/searches", async (req, reply) => {164 const a = await nextUser(req)165 const b = parse(zSearch, req.body)166 checkQuery(b.query)167 const boxes = await checkMailboxes(a.userId, b.mailbox_ids)168 await assertRoom("saved_searches", a.userId)169 const [row] = await sql`insert into saved_searches (user_id, name, query, mailbox_ids, icon, color, pinned, notify, position)170 values (${a.userId}, ${b.name}, ${b.query}, ${boxes}, ${b.icon}, ${b.color}, ${b.pinned}, ${b.notify}, ${await nextPosition("saved_searches", a.userId)}) returning *`171 if (b.position !== undefined) await place("saved_searches", a.userId, row.id, b.position)172 return reply.status(201).send(presentSearch((await sql`select * from saved_searches where id = ${row.id}`)[0]))173 })174 app.patch("/api/next/searches/:id", async (req) => {175 const a = await nextUser(req)176 const id = idOf(req)177 const b = parse(z.object({178 name: zName(80).optional(), query: z.string().trim().min(1).max(1000).optional(), mailbox_ids: z.array(zUuid).max(100).nullable().optional(),179 icon: z.string().trim().max(40).nullable().optional(), color: zColor.nullable().optional(), pinned: z.boolean().optional(), notify: z.boolean().optional(), position: zPosition.optional(),180 }).strict(), req.body)181 const [cur] = await sql`select * from saved_searches where id = ${id} and user_id = ${a.userId}`182 if (!cur) throw bad("not_found", 404)183 if (b.query !== undefined) checkQuery(b.query)184 const boxes = has(req.body, "mailbox_ids") ? await checkMailboxes(a.userId, b.mailbox_ids ?? null) : cur.mailbox_ids185 await sql`update saved_searches set name = ${b.name ?? cur.name}, query = ${b.query ?? cur.query}, mailbox_ids = ${boxes},186 icon = ${has(req.body, "icon") ? b.icon ?? null : cur.icon}, color = ${has(req.body, "color") ? b.color ?? null : cur.color},187 pinned = ${b.pinned ?? cur.pinned}, notify = ${b.notify ?? cur.notify}, updated_at = now() where id = ${id}`188 if (b.position !== undefined) await place("saved_searches", a.userId, id, b.position)189 return presentSearch((await sql`select * from saved_searches where id = ${id}`)[0])190 })191 app.delete("/api/next/searches/:id", async (req) => remove("saved_searches", (await nextUser(req)).userId, idOf(req)))192193 // ---------------------------------------------------------------- extraits194 const snippetError = (e: unknown) => { if (isUnique(e)) throw bad("shortcut_taken", 409, "Another snippet already uses this shortcut"); throw e }195 app.get("/api/next/snippets", async (req) => {196 const a = await nextUser(req)197 return { data: (await sql`select * from snippets where user_id = ${a.userId} order by position, created_at, id`).map(presentSnippet) }198 })199 app.post("/api/next/snippets", { bodyLimit: 512 * 1024 }, async (req, reply) => {200 const a = await nextUser(req)201 const b = parse(z.object({ name: zName(80), shortcut: zShortcut.nullable().optional(), subject: z.string().trim().max(300).nullable().optional(), html: zHtml.optional(), text: zText.optional(), position: zPosition.optional() }).strict(), req.body)202 if (b.html === undefined && b.text === undefined) throw bad("invalid_request", 400, "Provide `html` and/or `text`")203 await assertRoom("snippets", a.userId)204 // Le HTML passe par la même liste blanche que la rédaction ; le texte est dérivé du HTML s'il n'est pas fourni.205 const html = b.html !== undefined ? sanitizeHtml(b.html) : ""206 const [row] = await sql`insert into snippets (user_id, name, shortcut, subject, html, text, position)207 values (${a.userId}, ${b.name}, ${b.shortcut ?? null}, ${b.subject ?? null}, ${html}, ${b.text ?? htmlToText(html)}, ${await nextPosition("snippets", a.userId)}) returning *`.catch(snippetError)208 if (b.position !== undefined) await place("snippets", a.userId, row.id, b.position)209 return reply.status(201).send(presentSnippet((await sql`select * from snippets where id = ${row.id}`)[0]))210 })211 app.patch("/api/next/snippets/:id", { bodyLimit: 512 * 1024 }, async (req) => {212 const a = await nextUser(req)213 const id = idOf(req)214 const b = parse(z.object({ name: zName(80).optional(), shortcut: zShortcut.nullable().optional(), subject: z.string().trim().max(300).nullable().optional(), html: zHtml.optional(), text: zText.optional(), position: zPosition.optional() }).strict(), req.body)215 const [cur] = await sql`select * from snippets where id = ${id} and user_id = ${a.userId}`216 if (!cur) throw bad("not_found", 404)217 const html = b.html !== undefined ? sanitizeHtml(b.html) : cur.html218 const text = b.text ?? (b.html !== undefined ? htmlToText(html) : cur.text)219 await sql`update snippets set name = ${b.name ?? cur.name}, shortcut = ${has(req.body, "shortcut") ? b.shortcut ?? null : cur.shortcut},220 subject = ${has(req.body, "subject") ? b.subject ?? null : cur.subject}, html = ${html}, text = ${text}, updated_at = now() where id = ${id}`.catch(snippetError)221 if (b.position !== undefined) await place("snippets", a.userId, id, b.position)222 return presentSnippet((await sql`select * from snippets where id = ${id}`)[0])223 })224 app.delete("/api/next/snippets/:id", async (req) => remove("snippets", (await nextUser(req)).userId, idOf(req)))225226 // ---------------------------------------------------------------- signatures227 app.get("/api/next/signatures", async (req) => {228 const a = await nextUser(req)229 const own = (await sql`select * from signatures where user_id = ${a.userId} order by position, created_at, id`).map(presentSignature)230 const claimed = new Set(own.flatMap((s) => s.default_for as string[]))231 const claimedReplies = new Set(own.flatMap((s) => s.default_for_replies as string[]))232 // Signature par adresse de la version 0.3.0 : exposée en lecture seule, par défaut tant qu'aucune signature ne revendique l'adresse.233 const legacy = (await sendableAddresses(a.userId)).filter((x) => x.signature_text || x.signature_html).map((x) => ({234 id: `address:${x.id}`, source: "address" as const, read_only: true, address_id: x.id as string, name: x.address as string, html: sanitizeHtml(x.signature_html ?? ""), text: (x.signature_text ?? "") as string,235 default_for: claimed.has(x.id) ? [] : [x.id as string], default_for_replies: claimedReplies.has(x.id) ? [] : [x.id as string], position: null, updated_at: iso(x.updated_at),236 }))237 return { data: [...own, ...legacy] }238 })239 const zSignature = z.object({ name: zName(80), html: zHtml.optional(), text: zText.optional(), default_for: z.array(zUuid).max(200).optional(), default_for_replies: z.array(zUuid).max(200).optional(), position: zPosition.optional() }).strict()240 app.post("/api/next/signatures", { bodyLimit: 512 * 1024 }, async (req, reply) => {241 const a = await nextUser(req)242 const b = parse(zSignature, req.body)243 await assertRoom("signatures", a.userId)244 const html = b.html !== undefined ? sanitizeHtml(b.html) : ""245 const df = await checkAddressIds(a.userId, b.default_for ?? []), dr = await checkAddressIds(a.userId, b.default_for_replies ?? [])246 const position = await nextPosition("signatures", a.userId)247 const row = await sql.begin(async (tx) => {248 const [r] = await tx`insert into signatures (user_id, name, html, text, default_for, default_for_replies, position)249 values (${a.userId}, ${b.name}, ${html}, ${b.text ?? htmlToText(html)}, ${df}::uuid[], ${dr}::uuid[], ${position}) returning *`250 await claim(tx as never, a.userId, r.id, "default_for", df)251 await claim(tx as never, a.userId, r.id, "default_for_replies", dr)252 return r253 })254 if (b.position !== undefined) await place("signatures", a.userId, row.id, b.position)255 return reply.status(201).send(presentSignature((await sql`select * from signatures where id = ${row.id}`)[0]))256 })257 app.patch("/api/next/signatures/:id", { bodyLimit: 512 * 1024 }, async (req) => {258 const a = await nextUser(req)259 const raw = (req.params as { id?: string }).id ?? ""260 if (raw.startsWith("address:")) throw bad("read_only", 409, "Per-address signatures are edited on the address itself")261 const id = idOf(req)262 const b = parse(zSignature.partial(), req.body)263 const [cur] = await sql`select * from signatures where id = ${id} and user_id = ${a.userId}`264 if (!cur) throw bad("not_found", 404)265 const html = b.html !== undefined ? sanitizeHtml(b.html) : cur.html266 const text = b.text ?? (b.html !== undefined ? htmlToText(html) : cur.text)267 const df = b.default_for !== undefined ? await checkAddressIds(a.userId, b.default_for) : (cur.default_for as string[])268 const dr = b.default_for_replies !== undefined ? await checkAddressIds(a.userId, b.default_for_replies) : (cur.default_for_replies as string[])269 await sql.begin(async (tx) => {270 await tx`update signatures set name = ${b.name ?? cur.name}, html = ${html}, text = ${text}, default_for = ${df}::uuid[], default_for_replies = ${dr}::uuid[], updated_at = now() where id = ${id}`271 if (b.default_for !== undefined) await claim(tx as never, a.userId, id, "default_for", df)272 if (b.default_for_replies !== undefined) await claim(tx as never, a.userId, id, "default_for_replies", dr)273 })274 if (b.position !== undefined) await place("signatures", a.userId, id, b.position)275 return presentSignature((await sql`select * from signatures where id = ${id}`)[0])276 })277 app.delete("/api/next/signatures/:id", async (req) => {278 const a = await nextUser(req)279 if (((req.params as { id?: string }).id ?? "").startsWith("address:")) throw bad("read_only", 409, "Per-address signatures are edited on the address itself")280 return remove("signatures", a.userId, idOf(req))281 })282283 // ---------------------------------------------------------------- ordre des boîtes de l'utilisateur284 // `ids` = TOUTES les boîtes possédées, dans l'ordre voulu (permutation complète : un client qui ignore une boîte ne peut pas la déplacer285 // par omission). Une boîte d'autrui, partagée ou inconnue : 404, indiscernable. L'ordre vaut pour /api/me et toutes les listes de boîtes.286 app.put("/api/next/mailboxes/order", async (req) => {287 const a = await nextUser(req)288 const { ids } = parse(z.object({ ids: z.array(zUuid).min(1).max(200) }).strict(), req.body)289 const owned = (await userMailboxes(a.userId)).filter((m) => m.owner).map((m) => m.id)290 if (ids.some((id) => !owned.includes(id))) throw bad("not_found", 404)291 if (new Set(ids).size !== ids.length || ids.length !== owned.length) throw bad("invalid_request", 400, "ids: must list each of your mailboxes exactly once")292 await sql.begin(async (tx) => {293 for (const [i, id] of ids.entries()) await tx`update mailboxes set position = ${i} where id = ${id} and user_id = ${a.userId}`294 })295 return { ok: true }296 })297298 // ---------------------------------------------------------------- préférences de rédaction299 app.get("/api/next/compose/prefs", async (req) => composePrefs((await nextUser(req)).userId))300 app.put("/api/next/compose/prefs", async (req) => {301 const a = await nextUser(req)302 const b = parse(zComposePrefs, req.body)303 b.sensitive = [...new Set(b.sensitive)]304 await sql`insert into compose_prefs (user_id, prefs) values (${a.userId}, ${sql.json(b as never)})305 on conflict (user_id) do update set prefs = excluded.prefs, updated_at = now()`306 return b307 })308309 // ---------------------------------------------------------------- reprise d'un envoi retenu (annulation d'envoi)310 // GET : rend le contenu du message encore retenu, sans rien changer. POST : annule l'envoi EN GARDANT le brouillon (pièces jointes comprises)311 // dans « Brouillons » et rend son contenu — la rédaction reprend sur ce brouillon. (DELETE /api/v1/messages/scheduled/{id} annule aussi,312 // mais détruit le brouillon et donc ses pièces jointes.) Réservé à la session qui a créé l'envoi, et seulement tant qu'il est annulable.313 async function held(userId: string, id: string) {314 const o = /^msg_out_[A-Za-z0-9_-]{10,40}$/.test(id) ? await outboundById(id) : null315 if (!o || o.user_id !== userId) throw bad("not_found", 404)316 if (o.status !== "scheduled" || !o.email_id) throw bad("not_cancellable", 409, "This message can no longer be cancelled")317 const mb = await userMailbox(userId, o.mailbox_id)318 const [r] = await jmapOk(mb, [["Email/get", { ids: [o.email_id], properties: ["threadId", "from", "to", "cc", "bcc", "replyTo", "subject", "inReplyTo", "references", "bodyValues", "textBody", "htmlBody", "attachments"], fetchAllBodyValues: true, maxBodyValueBytes: 2_000_000 }]])319 const e = (r.list as Record<string, any>[])[0]320 if (!e) throw bad("not_cancellable", 409, "This message can no longer be cancelled")321 const bv = e.bodyValues ?? {}322 const join = (parts: { partId: string; type: string }[] | undefined, type: string) => {323 const vals = (parts ?? []).filter((p) => p.type === type && bv[p.partId]).map((p) => String(bv[p.partId].value ?? ""))324 return vals.length ? vals.join("\n") : null325 }326 const addrs = (l: { email: string; name: string | null }[] | null | undefined) => (l ?? []).map((x) => ({ email: String(x.email ?? ""), name: x.name ?? null }))327 const html = join(e.htmlBody, "text/html")328 const content = {329 id: o.id, status: o.status as string, mailbox_id: mb.id, email_id: e.id as string, thread_id: e.threadId as string,330 from: addrs(e.from)[0] ?? { email: o.from_address, name: null }, to: addrs(e.to), cc: addrs(e.cc), bcc: addrs(e.bcc), reply_to: addrs(e.replyTo),331 subject: (e.subject ?? "") as string, html: html === null ? null : sanitizeHtml(html), text: join(e.textBody, "text/plain"),332 attachments: ((e.attachments ?? []) as Record<string, any>[]).map((x) => ({ blob_id: x.blobId as string, name: x.name ?? null, type: x.type ?? "application/octet-stream", size: x.size ?? 0, cid: x.cid ?? null, inline: x.disposition === "inline" })),333 in_reply_to: (e.inReplyTo ?? []) as string[], references: (e.references ?? []) as string[],334 send_at: iso(o.send_at), undo_until: iso(o.undo_until ?? null),335 }336 return { o, content }337 }338 app.get("/api/next/compose/undo/:id", async (req) => (await held((await nextUser(req)).userId, (req.params as { id?: string }).id ?? "")).content)339 app.post("/api/next/compose/undo/:id", async (req) => {340 const a = await nextUser(req)341 const { o, content } = await held(a.userId, (req.params as { id?: string }).id ?? "")342 await cancelOutbound(o, "undone by the sender", true)343 return { ...content, status: "cancelled", draft: true }344 })345}346