SPB Git

Repository Public

messages.ts 29.0 KB 409 lines typescript

1// /api/v1 — lecture, recherche, fils, synchronisation incrémentale, modification, pièces jointes, dossiers.2import { Readable } from "node:stream"3import { z } from "zod"4import { hasScope, requireScope, type Principal } from "../keys.js"5import { downloadBlob, folders, invalidateFolders, jmap, jmapOk, roleFolder, type Folder, type Mbx } from "../mailjmap.js"6import { sanitizeHtml } from "../sanitize.js"7import { bad } from "../util.js"8import { deliveredTo, fullViewOfMailbox, matchesView, readViews, viewOfMailbox, type View } from "./context.js"9import { zLabel } from "./headers.js"10import { attachmentId, decodeCursor, encodeCursor, filterHash, folderId, msgId, parseAttachmentId, parseFolderId, parseMsgId, parseStateToken, parseThreadId, stateToken, threadId, type ListCursor } from "./ids.js"11import { route } from "./registry.js"1213// ------------------------------------------------------------------ schémas de réponse14const zAddr = z.object({ email: z.string(), name: z.string().nullable() })15export const zMessageSummary = z.object({16  id: z.string(), thread_id: z.string(), mailbox: z.string().describe("Primary address of the physical mailbox holding the message"),17  delivered_to: z.array(z.string()).describe("Envelope recipients recorded by the mail server (Delivered-To)"),18  folders: z.array(z.object({ id: z.string(), role: z.string().nullable(), name: z.string() })),19  from: z.array(zAddr), to: z.array(zAddr), cc: z.array(zAddr), subject: z.string(), preview: z.string(),20  received_at: z.string(), sent_at: z.string().nullable(), size: z.number(), unread: z.boolean(), starred: z.boolean(), draft: z.boolean(),21  answered: z.boolean(), forwarded: z.boolean(), has_attachment: z.boolean(), labels: z.array(z.string()),22  pinned: z.boolean().describe("Pinned to the top of its lists (`$pinned` keyword)"),23  snoozed: z.boolean().describe("Currently snoozed (`$snoozed` keyword); it returns to the inbox when the snooze ends"),24  followup: z.boolean().describe("A follow-up reminder is set on the message (`$followup` keyword)"),25})26const zAttachment = z.object({ id: z.string(), name: z.string().nullable(), type: z.string(), size: z.number(), cid: z.string().nullable(), disposition: z.string().nullable(), inline: z.boolean() })27export const zMessage = zMessageSummary.extend({28  bcc: z.array(zAddr), reply_to: z.array(zAddr), message_id: z.string().nullable(), in_reply_to: z.array(z.string()), references: z.array(z.string()),29  headers: z.array(z.object({ name: z.string(), value: z.string() })),30  text: z.string().nullable(), html: z.string().nullable().describe("Sanitised server-side (strict allowlist); remote images are NOT fetched or rewritten"),31  truncated: z.boolean(), attachments: z.array(zAttachment),32  auth: z.object({ spf: z.string().nullable(), dkim: z.string().nullable(), dmarc: z.string().nullable(), raw: z.string().nullable() }),33})34const zPage = <T extends z.ZodTypeAny>(item: T) => z.object({ data: z.array(item), next_cursor: z.string().nullable(), has_more: z.boolean() })35export const zOk = z.object({ ok: z.literal(true) })3637export const LIST_PROPS = ["threadId", "mailboxIds", "keywords", "from", "to", "cc", "bcc", "subject", "preview", "receivedAt", "sentAt", "size", "hasAttachment", "header:Delivered-To:asText:all"]38export const FULL_PROPS = [...LIST_PROPS, "replyTo", "messageId", "inReplyTo", "references", "headers", "bodyValues", "textBody", "htmlBody", "attachments"]39type JAddr = { email: string; name: string | null }40export type JEmail = Record<string, any> & { id: string }41const addrs = (l: JAddr[] | null | undefined) => (l ?? []).map((a) => ({ email: String(a.email ?? ""), name: a.name ?? null }))4243export function presentSummary(mb: Mbx, e: JEmail, fl: Folder[]) {44  const kw = e.keywords ?? {}45  return {46    id: msgId(mb.id, e.id), thread_id: threadId(mb.id, e.threadId), mailbox: mb.address, delivered_to: deliveredTo(e),47    folders: Object.keys(e.mailboxIds ?? {}).map((id) => { const f = fl.find((x) => x.id === id); return { id: folderId(mb.id, id), role: f?.role ?? null, name: f?.name ?? "" } }),48    from: addrs(e.from), to: addrs(e.to), cc: addrs(e.cc), subject: e.subject ?? "", preview: e.preview ?? "",49    received_at: e.receivedAt, sent_at: e.sentAt ?? null, size: e.size ?? 0, unread: !kw.$seen, starred: !!kw.$flagged, draft: !!kw.$draft,50    answered: !!kw.$answered, forwarded: !!kw.$forwarded, has_attachment: !!e.hasAttachment, labels: Object.keys(kw).filter((k) => !k.startsWith("$")).sort(),51    // états de SP Mail Next portés par des mots-clés système : évite un aller-retour JMAP par boîte aux clients de la liste unifiée52    pinned: !!kw.$pinned, snoozed: !!kw.$snoozed, followup: !!kw.$followup,53  }54}55function authResults(headers: { name: string; value: string }[]) {56  const raw = headers.filter((h) => h.name.toLowerCase() === "authentication-results").map((h) => h.value.trim()).join(" | ") || null57  const pick = (k: string) => (raw ? (new RegExp(`\\b${k}=([a-z]+)`, "i").exec(raw)?.[1]?.toLowerCase() ?? null) : null)58  return { spf: pick("spf"), dkim: pick("dkim"), dmarc: pick("dmarc"), raw: raw ? raw.slice(0, 2000) : null }59}60export function presentMessage(mb: Mbx, e: JEmail, fl: Folder[]) {61  const bv = e.bodyValues ?? {}62  const join = (parts: { partId: string; type: string }[] | undefined, type: string) => {63    const vals = (parts ?? []).filter((p) => p.type === type && bv[p.partId]).map((p) => String(bv[p.partId].value ?? ""))64    return vals.length ? vals.join("\n") : null65  }66  const html = join(e.htmlBody, "text/html")67  const headers = ((e.headers ?? []) as { name: string; value: string }[]).map((h) => ({ name: h.name, value: String(h.value ?? "").trim() }))68  return {69    ...presentSummary(mb, e, fl), bcc: addrs(e.bcc), reply_to: addrs(e.replyTo), message_id: e.messageId?.[0] ?? null, in_reply_to: e.inReplyTo ?? [], references: e.references ?? [],70    headers, text: join(e.textBody, "text/plain"), html: html === null ? null : sanitizeHtml(html),71    truncated: Object.values(bv).some((v: any) => v.isTruncated),72    attachments: ((e.attachments ?? []) as any[]).map((a) => ({ id: attachmentId(a.blobId), name: a.name ?? null, type: a.type ?? "application/octet-stream", size: a.size ?? 0, cid: a.cid ?? null, disposition: a.disposition ?? null, inline: a.disposition === "inline" })),73    auth: authResults(headers),74  }75}7677/** Charge un message désigné par son identifiant opaque, en revérifiant la boîte ET (vue restreinte) les adresses de l'appelant. */78export async function loadEmail(p: Principal, id: string, properties: string[] = FULL_PROPS, full = true): Promise<{ mb: Mbx; view: View; email: JEmail }> {79  const { mailboxId, jmapId } = parseMsgId(id)80  const view = await viewOfMailbox(p, mailboxId)81  const [r] = await jmapOk(view.mailbox, [["Email/get", { ids: [jmapId], properties, ...(full ? { fetchAllBodyValues: true, maxBodyValueBytes: 1_000_000 } : {}) }]])82  const email = (r.list as JEmail[])[0]83  if (!email || !matchesView(view, email)) throw bad("not_found", 404, "Unknown message")84  return { mb: view.mailbox, view, email }85}8687// ------------------------------------------------------------------ liste unifiée, paginée par curseur composite88const zBool = z.enum(["true", "false"]).transform((v) => v === "true")89const zList = z.string().max(2000).transform((s) => s.split(",").map((x) => x.trim().toLowerCase()).filter(Boolean))90const zDate = z.string().refine((s) => !Number.isNaN(Date.parse(s)), "invalid date").transform((s) => new Date(s).toISOString().replace(/\.\d{3}Z$/, "Z"))91export const zListQuery = z.object({92  address: zList.optional().describe("Comma-separated addresses to read (each must be allowed). A mailbox's primary address means the whole mailbox; an alias means only mail delivered to / sent from it. Omitted = every address the caller may read."),93  mailbox: zList.optional().describe("Synonym of `address` for primary mailbox addresses"),94  folder: z.string().max(300).optional().describe("Folder role (inbox, drafts, sent, trash, junk, archive) resolved in each mailbox, or a folder id (fld_…)"),95  unread: zBool.optional(), flagged: zBool.optional().describe("Starred / important"), has_attachment: zBool.optional(),96  from: z.string().max(200).optional(), to: z.string().max(200).optional(), subject: z.string().max(200).optional(),97  text: z.string().max(300).optional().describe("Full-text search (headers, bodies and, as far as the server indexes them, attachments)"),98  before: zDate.optional().describe("Received strictly before (ISO 8601)"), after: zDate.optional().describe("Received at or after (ISO 8601)"),99  label: zLabel.optional(),100  limit: z.coerce.number().int().min(1).max(100).default(25),101  cursor: z.string().max(2000).optional(),102})103type ListQuery = z.infer<typeof zListQuery>104type Item = { t: number; k: string; mb: Mbx; e: JEmail }105const ROLES = new Set(["inbox", "drafts", "sent", "trash", "junk", "archive"])106const SCAN_CAP = 3000107108async function folderFor(mb: Mbx, folder: string | undefined): Promise<string | null | undefined> {109  if (!folder) return undefined110  if (ROLES.has(folder)) return roleFolder(mb, folder)111  const f = parseFolderId(folder)112  if (!f) throw bad("invalid_request", 400, "folder must be a role (inbox, drafts, sent, trash, junk, archive) or a folder id")113  return f.mailboxId === mb.id ? f.jmapId : null114}115async function buildFilter(mb: Mbx, q: ListQuery, beforeIso?: string): Promise<Record<string, unknown> | null> {116  const c: Record<string, unknown>[] = []117  const f = await folderFor(mb, q.folder)118  if (f === null) return null // ce dossier n'existe pas dans cette boîte119  if (f) c.push({ inMailbox: f })120  if (q.unread !== undefined) c.push(q.unread ? { notKeyword: "$seen" } : { hasKeyword: "$seen" })121  if (q.flagged !== undefined) c.push(q.flagged ? { hasKeyword: "$flagged" } : { notKeyword: "$flagged" })122  if (q.has_attachment !== undefined) c.push({ hasAttachment: q.has_attachment })123  for (const k of ["from", "to", "subject", "text"] as const) if (q[k]) c.push({ [k]: q[k] })124  if (q.label) c.push({ hasKeyword: q.label })125  if (q.after) c.push({ after: q.after })126  const before = [q.before, beforeIso].filter(Boolean).sort()[0]127  if (before) c.push({ before })128  return c.length === 0 ? {} : c.length === 1 ? c[0] : { operator: "AND", conditions: c }129}130const afterCursor = (c: ListCursor | null, t: number, k: string) => !c || t < Date.parse(c.t) || (t === Date.parse(c.t) && k > c.k)131132async function collect(view: View, q: ListQuery, cursor: ListCursor | null, need: number, collapse: boolean) {133  const mb = view.mailbox134  const ct = cursor ? Date.parse(cursor.t) : 0135  const filter = await buildFilter(mb, q, cursor ? new Date(Math.floor(ct / 1000) * 1000 + 1000).toISOString().replace(/\.\d{3}Z$/, "Z") : undefined)136  const items: Item[] = []137  if (filter === null) return { items, exhausted: true, frontier: 0 }138  const page = Math.min(200, Math.max(50, need + 10))139  let position = 0, frontier = 0, exhausted = false140  for (;;) {141    const res = await jmapOk(mb, [142      ["Email/query", { filter, sort: [{ property: "receivedAt", isAscending: false }], position, limit: page, ...(collapse && !view.restrict ? { collapseThreads: true } : {}) }, "q"],143      ["Email/get", { "#ids": { resultOf: "q", name: "Email/query", path: "/ids" }, properties: LIST_PROPS }, "g"],144    ])145    const ids = res[0].ids as string[]146    if (!ids.length) { exhausted = true; break }147    const byId = new Map((res[1].list as JEmail[]).map((e) => [e.id, e]))148    for (const id of ids) {149      const e = byId.get(id)150      if (!e) continue151      const t = Date.parse(e.receivedAt)152      frontier = t153      const k = `${mb.id}:${e.id}`154      if (afterCursor(cursor, t, k) && matchesView(view, e)) items.push({ t, k, mb, e })155    }156    position += ids.length157    if (ids.length < page) { exhausted = true; break }158    // assez d'éléments, et toutes les égalités d'horodatage du dernier retenu ont été vues159    if (items.length >= need && frontier < items[need - 1].t) break160    if (position >= SCAN_CAP) break161  }162  return { items, exhausted, frontier }163}164165export async function listMessages(p: Principal, q: ListQuery, collapse = false) {166  const only = [...(q.address ?? []), ...(q.mailbox ?? [])]167  const views = await readViews(p, only.length ? only : undefined)168  const { cursor: rawCursor, limit, ...rest } = q169  const h = filterHash({ ...rest, collapse, views: views.map((v) => [v.mailbox.id, v.restrict]) })170  const cursor = decodeCursor<ListCursor>(rawCursor, (c) => typeof c.t === "string" && typeof c.k === "string" && c.h === h && !Number.isNaN(Date.parse(c.t)))171  const parts = await Promise.all(views.map((v) => collect(v, q, cursor, limit + 1, collapse)))172  // On ne peut émettre que ce qui est plus récent que la frontière de lecture de chaque boîte non épuisée.173  const bound = Math.max(0, ...parts.filter((x) => !x.exhausted).map((x) => x.frontier))174  let merged = parts.flatMap((x) => x.items).sort((a, b) => b.t - a.t || (a.k < b.k ? -1 : 1))175  if (collapse) {176    const seen = new Set<string>()177    merged = merged.filter((i) => { const key = `${i.mb.id}:${i.e.threadId}`; if (seen.has(key)) return false; seen.add(key); return true })178  }179  const anyOpen = parts.some((x) => !x.exhausted)180  const safe = anyOpen ? merged.filter((i) => i.t > bound) : merged181  const out = safe.slice(0, limit)182  let next: string | null = null183  if (safe.length > limit) next = encodeCursor({ t: new Date(out[out.length - 1].t).toISOString(), k: out[out.length - 1].k, h })184  else if (anyOpen) next = encodeCursor({ t: new Date(bound).toISOString(), k: "", h }) // reprise à la frontière (tout ce qui est ≤ frontière reste à lire)185  const fl = new Map<string, Folder[]>()186  for (const i of out) if (!fl.has(i.mb.id)) fl.set(i.mb.id, await folders(i.mb, false, out.filter((x) => x.mb.id === i.mb.id).flatMap((x) => Object.keys(x.e.mailboxIds ?? {}))))187  return { items: out, folders: fl, next_cursor: next, has_more: next !== null }188}189190route({191  method: "GET", path: "/messages", tag: "Messages", summary: "List / search messages (unified across mailboxes)", scopes: ["mail.read", "mail.search"],192  description: "Newest first. With several addresses (or none = all allowed) results are merged across mailboxes by date with a composite cursor: no duplicates, no gaps. Any search filter (from, to, subject, text, label) requires `mail.search`.",193  query: zListQuery, response: zPage(zMessageSummary),194  handler: async ({ principal, query }) => {195    if (query.from || query.to || query.subject || query.text || query.label) requireScope(principal, "mail.search")196    else requireScope(principal, "mail.read")197    const r = await listMessages(principal, query)198    return { data: r.items.map((i) => presentSummary(i.mb, i.e, r.folders.get(i.mb.id)!)), next_cursor: r.next_cursor, has_more: r.has_more }199  },200})201202const zThreadSummary = z.object({ id: z.string(), mailbox: z.string(), latest: zMessageSummary })203route({204  method: "GET", path: "/threads", tag: "Messages", summary: "List conversations (one entry per thread, newest message first)", scopes: ["mail.read"],205  description: "Same filters and cursor as GET /messages. For address-restricted (alias-level) views threads are collapsed per page, so a thread may reappear on a later page.",206  query: zListQuery, response: zPage(zThreadSummary),207  handler: async ({ principal, query }) => {208    if (query.from || query.to || query.subject || query.text || query.label) requireScope(principal, "mail.search")209    const r = await listMessages(principal, query, true)210    return { data: r.items.map((i) => ({ id: threadId(i.mb.id, i.e.threadId), mailbox: i.mb.address, latest: presentSummary(i.mb, i.e, r.folders.get(i.mb.id)!) })), next_cursor: r.next_cursor, has_more: r.has_more }211  },212})213214route({215  method: "GET", path: "/threads/{id}", tag: "Messages", summary: "Messages of a conversation, oldest first", scopes: ["mail.read"],216  params: z.object({ id: z.string().max(400) }), response: z.object({ id: z.string(), mailbox: z.string(), messages: z.array(zMessageSummary) }),217  handler: async ({ principal, params }) => {218    const { mailboxId, jmapId } = parseThreadId(params.id)219    const view = await viewOfMailbox(principal, mailboxId)220    const res = await jmapOk(view.mailbox, [221      ["Thread/get", { ids: [jmapId] }, "t"],222      ["Email/get", { "#ids": { resultOf: "t", name: "Thread/get", path: "/list/*/emailIds" }, properties: LIST_PROPS }, "g"],223    ])224    const order = ((res[0].list as { emailIds: string[] }[])[0]?.emailIds ?? []) as string[]225    const byId = new Map((res[1].list as JEmail[]).map((e) => [e.id, e]))226    const list = order.map((id) => byId.get(id)).filter((e): e is JEmail => !!e && matchesView(view, e))227    if (!list.length) throw bad("not_found", 404, "Unknown thread")228    const fl = await folders(view.mailbox, false, list.flatMap((e) => Object.keys(e.mailboxIds ?? {})))229    return { id: params.id, mailbox: view.mailbox.address, messages: list.map((e) => presentSummary(view.mailbox, e, fl)) }230  },231})232233// ------------------------------------------------------------------ synchronisation incrémentale234route({235  method: "GET", path: "/messages/changes", tag: "Messages", summary: "Incremental sync of one mailbox (JMAP Email/changes)", scopes: ["mail.read"],236  description: "Without `since`: returns the current `state` and empty lists (bootstrap after a full listing). With `since`: ids created / updated / destroyed since that state. An unknown or too old state answers 409 `resync_required`. In an address-restricted view, created/updated are filtered to visible messages; destroyed ids are returned unfiltered (ids only).",237  query: z.object({ address: z.string().max(254).optional().describe("Address whose mailbox is synchronised (required when the caller can read several mailboxes)"), since: z.string().max(600).optional(), limit: z.coerce.number().int().min(1).max(500).default(200) }),238  response: z.object({ mailbox: z.string(), state: z.string(), created: z.array(z.string()), updated: z.array(z.string()), destroyed: z.array(z.string()), has_more: z.boolean() }),239  otherStatuses: { 409: "resync_required" },240  handler: async ({ principal, query }) => {241    const views = await readViews(principal, query.address ? [query.address] : undefined)242    if (views.length !== 1) throw bad("address_required", 400, "Specify `address`: this caller can read several mailboxes")243    const view = views[0], mb = view.mailbox244    if (!query.since) {245      const [r] = await jmapOk(mb, [["Email/get", { ids: [] }]])246      return { mailbox: mb.address, state: stateToken(mb.id, r.state), created: [], updated: [], destroyed: [], has_more: false }247    }248    const st = parseStateToken(query.since)249    if (st.m !== mb.id) throw bad("resync_required", 409, "This state token belongs to another mailbox")250    const res = await jmap(mb, [["Email/changes", { sinceState: st.s, maxChanges: query.limit }, "c"]])251    // Stalwart répond invalidArguments « invalid JMAP State » là où la RFC prévoit cannotCalculateChanges.252    if (res[0][0] === "error") {253      if (["cannotCalculateChanges", "invalidArguments"].includes(res[0][1].type)) throw bad("resync_required", 409, "The state is unknown or too old: perform a full resynchronisation")254      throw bad("mail_server_error", 502, String(res[0][1].type))255    }256    const ch = res[0][1] as { created: string[]; updated: string[]; destroyed: string[]; newState: string; hasMoreChanges: boolean }257    let created = ch.created, updated = ch.updated258    if (view.restrict && (created.length || updated.length)) {259      const [g] = await jmapOk(mb, [["Email/get", { ids: [...created, ...updated], properties: ["from", "to", "cc", "bcc", "header:Delivered-To:asText:all"] }]])260      const ok = new Set((g.list as JEmail[]).filter((e) => matchesView(view, e)).map((e) => e.id))261      created = created.filter((i) => ok.has(i)); updated = updated.filter((i) => ok.has(i))262    }263    const ids = (l: string[]) => l.map((i) => msgId(mb.id, i))264    return { mailbox: mb.address, state: stateToken(mb.id, ch.newState), created: ids(created), updated: ids(updated), destroyed: ids(ch.destroyed), has_more: !!ch.hasMoreChanges }265  },266})267268// ------------------------------------------------------------------ message : lecture, drapeaux, déplacement, suppression269const zIdParam = z.object({ id: z.string().max(400) })270route({271  method: "GET", path: "/messages/{id}", tag: "Messages", summary: "Read one message (headers, text, sanitised HTML, attachment metadata)", scopes: ["mail.read"],272  params: zIdParam, response: zMessage,273  handler: async ({ principal, params }) => {274    const { mb, email } = await loadEmail(principal, params.id)275    return presentMessage(mb, email, await folders(mb, false, Object.keys(email.mailboxIds ?? {})))276  },277})278279route({280  method: "PATCH", path: "/messages/{id}", tag: "Messages", summary: "Mark read/unread, star, add or remove labels", scopes: ["mail.modify"],281  params: zIdParam,282  body: z.object({ unread: z.boolean().optional(), starred: z.boolean().optional(), add_labels: z.array(zLabel).max(20).optional(), remove_labels: z.array(zLabel).max(20).optional() }).strict(),283  response: zMessageSummary,284  handler: async ({ principal, params, body }) => {285    const { mb, email } = await loadEmail(principal, params.id, LIST_PROPS, false)286    const patch: Record<string, unknown> = {}287    if (body.unread !== undefined) patch["keywords/$seen"] = body.unread ? null : true288    if (body.starred !== undefined) patch["keywords/$flagged"] = body.starred ? true : null289    for (const l of body.add_labels ?? []) patch[`keywords/${l}`] = true290    for (const l of body.remove_labels ?? []) patch[`keywords/${l}`] = null291    if (Object.keys(patch).length) {292      const [r] = await jmapOk(mb, [["Email/set", { update: { [email.id]: patch } }]])293      if (r.notUpdated?.[email.id]) throw bad("mail_server_error", 502, String(r.notUpdated[email.id].type))294    }295    const [g] = await jmapOk(mb, [["Email/get", { ids: [email.id], properties: LIST_PROPS }]])296    return presentSummary(mb, (g.list as JEmail[])[0], await folders(mb))297  },298})299300export async function moveEmail(mb: Mbx, emailId: string, target: string) {301  const [r] = await jmapOk(mb, [["Email/set", { update: { [emailId]: { mailboxIds: { [target]: true } } } }]])302  if (r.notUpdated?.[emailId]) throw bad("mail_server_error", 502, String(r.notUpdated[emailId].type))303}304route({305  method: "POST", path: "/messages/{id}/move", tag: "Messages", summary: "Move to a folder (archive, trash, inbox = restore, or a folder id)", scopes: ["mail.modify"],306  description: "`folder` is a role (inbox, archive, trash, junk, sent, drafts) or a folder id of the same mailbox. The Archive folder is created (role archive) when missing.",307  params: zIdParam, body: z.object({ folder: z.string().max(300) }).strict(), response: zMessageSummary,308  handler: async ({ principal, params, body }) => {309    const { mb, email } = await loadEmail(principal, params.id, LIST_PROPS, false)310    let target: string | null311    if (ROLES.has(body.folder)) target = await roleFolder(mb, body.folder, body.folder === "archive")312    else {313      const f = parseFolderId(body.folder)314      if (!f || f.mailboxId !== mb.id || !(await folders(mb, true)).some((x) => x.id === f.jmapId)) throw bad("unknown_folder", 400, "Unknown folder for this mailbox")315      target = f.jmapId316    }317    if (!target) throw bad("unknown_folder", 400, "This mailbox has no such folder")318    await moveEmail(mb, email.id, target)319    const [g] = await jmapOk(mb, [["Email/get", { ids: [email.id], properties: LIST_PROPS }]])320    return presentSummary(mb, (g.list as JEmail[])[0], await folders(mb, true))321  },322})323324route({325  method: "DELETE", path: "/messages/{id}", tag: "Messages", summary: "Move to trash, or delete permanently with explicit confirmation", scopes: ["mail.modify", "mail.delete"],326  description: "Default: the message goes to Trash (restorable with POST /messages/{id}/move {folder:\"inbox\"}). `?permanent=true` destroys it and requires the scope `mail.delete` AND the body `{\"confirm\":\"permanently-delete\"}`.",327  params: zIdParam, query: z.object({ permanent: zBool.optional() }), body: z.object({ confirm: z.string().max(40).optional() }),328  response: z.object({ ok: z.literal(true), permanent: z.boolean() }),329  handler: async ({ principal, params, query, body }) => {330    const { mb, email } = await loadEmail(principal, params.id, LIST_PROPS, false)331    if (query.permanent) {332      requireScope(principal, "mail.delete")333      if (body?.confirm !== "permanently-delete") throw bad("confirmation_required", 400, 'Permanent deletion requires the body {"confirm":"permanently-delete"}')334      const [r] = await jmapOk(mb, [["Email/set", { destroy: [email.id] }]])335      if (!(r.destroyed ?? []).includes(email.id)) throw bad("mail_server_error", 502, "not destroyed")336      return { ok: true as const, permanent: true }337    }338    const trash = await roleFolder(mb, "trash", true)339    await moveEmail(mb, email.id, trash!)340    return { ok: true as const, permanent: false }341  },342})343344// ------------------------------------------------------------------ pièces jointes345route({346  method: "GET", path: "/messages/{id}/attachments", tag: "Attachments", summary: "Attachment metadata of a message", scopes: ["mail.attachments.read"],347  params: zIdParam, response: z.object({ data: z.array(zAttachment) }),348  handler: async ({ principal, params }) => {349    const { mb, email } = await loadEmail(principal, params.id, [...LIST_PROPS, "attachments"], false)350    return { data: presentMessage(mb, email, []).attachments }351  },352})353route({354  method: "GET", path: "/messages/{id}/attachments/{attachment_id}", tag: "Attachments", summary: "Download one attachment", scopes: ["mail.attachments.read"],355  description: "Always served as `Content-Disposition: attachment` with `Content-Security-Policy: sandbox`. The attachment id is verified against the message.",356  params: z.object({ id: z.string().max(400), attachment_id: z.string().max(700) }), response: null,357  handler: async ({ principal, params, reply }) => {358    const { mb, email } = await loadEmail(principal, params.id, [...LIST_PROPS, "attachments"], false)359    const blobId = parseAttachmentId(params.attachment_id)360    const att = ((email.attachments ?? []) as any[]).find((a) => a.blobId === blobId)361    if (!att) throw bad("not_found", 404, "Unknown attachment")362    const r = await downloadBlob(mb, blobId, att.name ?? "attachment", att.type ?? "application/octet-stream")363    const safeName = String(att.name ?? "attachment").replace(/[^\w.\- ()À-ɏ]/g, "_").slice(0, 150) || "attachment"364    reply.header("content-type", "application/octet-stream").header("content-disposition", `attachment; filename*=UTF-8''${encodeURIComponent(safeName)}`)365      .header("content-security-policy", "sandbox; default-src 'none'").header("x-content-type-options", "nosniff")366    const len = r.headers.get("content-length")367    if (len) reply.header("content-length", len)368    reply.send(Readable.fromWeb(r.body as never))369    return undefined370  },371})372373// ------------------------------------------------------------------ dossiers374const zFolder = z.object({ id: z.string(), mailbox: z.string(), name: z.string(), role: z.string().nullable(), parent_id: z.string().nullable(), total: z.number().nullable(), unread: z.number().nullable() })375const presentFolder = (mb: Mbx, f: Folder, counts: boolean) => ({ id: folderId(mb.id, f.id), mailbox: mb.address, name: f.name, role: f.role ?? null, parent_id: f.parentId ? folderId(mb.id, f.parentId) : null, total: counts ? f.totalEmails : null, unread: counts ? f.unreadEmails : null })376route({377  method: "GET", path: "/folders", tag: "Folders", summary: "Folders of the readable mailboxes", scopes: ["mail.read"],378  description: "Counts are null for address-restricted views (they would reveal the volume of the whole mailbox).",379  query: z.object({ address: zList.optional() }), response: z.object({ data: z.array(zFolder) }),380  handler: async ({ principal, query }) => {381    const views = await readViews(principal, query.address?.length ? query.address : undefined)382    const data = []383    for (const v of views) for (const f of await folders(v.mailbox, true)) data.push(presentFolder(v.mailbox, f, !v.restrict))384    return { data }385  },386})387route({388  method: "POST", path: "/folders", tag: "Folders", summary: "Create a folder in a mailbox", scopes: ["mail.modify"], idempotent: true, status: 201,389  body: z.object({ address: z.string().max(254).describe("Primary address of the mailbox"), name: z.string().trim().min(1).max(100).refine((s) => !/[\u0000-\u001f/]/.test(s), "invalid folder name"), parent_id: z.string().max(300).optional() }).strict(),390  response: zFolder,391  handler: async ({ principal, body }) => {392    const views = await readViews(principal, [body.address])393    const view = await fullViewOfMailbox(principal, views[0].mailbox.id)394    const mb = view.mailbox395    let parentId: string | null = null396    if (body.parent_id) {397      const pf = parseFolderId(body.parent_id)398      if (!pf || pf.mailboxId !== mb.id) throw bad("unknown_folder", 400, "Unknown parent folder")399      parentId = pf.jmapId400    }401    const [r] = await jmapOk(mb, [["Mailbox/set", { create: { n: { name: body.name, parentId } } }]])402    invalidateFolders(mb.id)403    if (!r.created?.n) throw bad("folder_not_created", 409, String(r.notCreated?.n?.description ?? r.notCreated?.n?.type ?? "refused"))404    const f = (await folders(mb, true)).find((x) => x.id === r.created.n.id)!405    return presentFolder(mb, f, true)406  },407})408export { hasScope }409
Files main
Menu

Theme