SPB Git

Repository Public

send.ts 37.7 KB 469 lines typescript

1// /api/v1 — envoi, lots, réponse, transfert, brouillons, fichiers, suivi d'envoi et messages programmés.2import { renderForSend } from "./templates.js"3import type { Readable } from "node:stream"4import { z } from "zod"5import { type AddressRow } from "../addresses.js"6import { config } from "../config.js"7import { sql } from "../db.js"8import { requireScope, type Principal } from "../keys.js"9import { folders, jmapOk, roleFolder, uploadBlob, type Mbx } from "../mailjmap.js"10import { assertDailyLimit, cancelOutbound, createOutbound, isExternal, outboundById, presentOutbound, type OutboundRow } from "../outbound.js"11import { htmlToText, sanitizeHtml, escapeHtml } from "../sanitize.js"12import { emitEvent } from "../webhooks.js"13import { bad, HttpError } from "../util.js"14import { accessMap, deliveredTo, findAllowed, readViews, sendAddress, type Access } from "./context.js"15import { validateCustomHeaders, zEmail, zMessageIdHeader, zRecipient, zSubject, type Recipient } from "./headers.js"16import { decodeCursor, encodeCursor, msgId, newFileId, threadId } from "./ids.js"17import { FULL_PROPS, LIST_PROPS, listMessages, loadEmail, presentMessage, presentSummary, zListQuery, zMessage, zMessageSummary, zOk, type JEmail } from "./messages.js"18import { errorBody, respond, route } from "./registry.js"1920// ------------------------------------------------------------------ schémas21const zAttachmentRef = z.object({22  file_id: z.string().regex(/^file_[A-Za-z0-9_-]{10,60}$/), filename: z.string().max(200).refine((s) => !/[\u0000-\u001f]/.test(s), "invalid filename").optional(),23  inline: z.boolean().optional().describe("Inline image referenced from the HTML as cid:<cid>"), cid: z.string().regex(/^[A-Za-z0-9._@-]{1,100}$/).optional(),24}).strict()25const zCompose = z.object({26  from: zEmail.describe("Sender address; must be in the caller's allowlist, active and allowed to send"),27  to: z.array(zRecipient).max(100).default([]), cc: z.array(zRecipient).max(100).default([]), bcc: z.array(zRecipient).max(100).default([]),28  subject: zSubject.default(""),29  text: z.string().max(2_000_000).optional(), html: z.string().max(2_000_000).optional().describe("Sanitised server-side with a strict allowlist before being stored or sent"),30  attachments: z.array(zAttachmentRef).max(30).default([]),31  reply_to_message_id: z.string().max(400).optional().describe("Message (msg_…) being answered: sets In-Reply-To / References from it"),32  in_reply_to: zMessageIdHeader.optional(), references: z.array(zMessageIdHeader).max(50).optional(),33  headers: z.record(z.string().max(64), z.string().max(900)).optional().describe("Only X-*, Reply-To, List-Unsubscribe, List-Unsubscribe-Post"),34  priority: z.enum(["high", "normal", "low"]).optional(),35})36// SP Mail Next (§4.7) : champs optionnels communs à l'envoi, à la réponse et au transfert. Absents, rien ne change.37const zSendOptions = {38  undo_seconds: z.number().int().min(0).max(120).optional().describe("Undo send: hold the message this many seconds before it is submitted (status `scheduled`, response carries `undo_until`); cancel with DELETE /messages/scheduled/{id}. Ignored with a future `send_at`, `draft`, or when the message awaits approval"),39  remind_at: z.string().refine((s) => !Number.isNaN(Date.parse(s)), "invalid date").optional().describe("ISO 8601; creates a follow-up reminder on the sent message once it has been submitted (session callers only)"),40  remind_if_no_reply: z.boolean().optional().describe("With `remind_at`: the reminder resolves silently if somebody replied in the meantime"),41  confirm_sensitive: z.boolean().optional().describe("Session callers: confirms sending to recipients listed as sensitive in the compose preferences (otherwise `409 confirmation_required`)"),42}43export const zSendBody = zCompose.extend({44  send_at: z.string().refine((s) => !Number.isNaN(Date.parse(s)), "invalid date").optional().describe("ISO 8601; future = scheduled (max 30 days ahead)"),45  draft: z.boolean().optional().describe("Save as a draft only; nothing is sent"),46  template_id: z.string().uuid().optional().describe("Send a stored template (see /templates): its rendered subject, HTML and text are used; `html` and `text` must then be omitted, `subject` is optional and overrides the template's"),47  variables: z.record(z.string().regex(/^[a-z][a-z0-9_]{0,39}$/), z.string().max(20_000)).optional().describe("Values for the template's {{variables}}; every required variable must be present"),48  ...zSendOptions,49}).strict()50export type SendBody = z.infer<typeof zSendBody>51const zRecipientStatus = z.object({ address: z.string(), status: z.string(), smtp_reply: z.string().nullable() })52export const zOutbound = z.object({53  id: z.string().describe("msg_out_… (or the draft's msg_… id when status is draft)"),54  status: z.enum(["queued", "scheduled", "pending_approval", "sent", "delivered", "deferred", "bounced", "failed", "cancelled", "draft"]),55  from: z.string(), message_id: z.string().nullable(), recipients: z.array(zRecipientStatus), external: z.boolean(), send_at: z.string().nullable(),56  attempts: z.number(), last_error: z.string().nullable(), submitted_at: z.string().nullable(), final_at: z.string().nullable(), created_at: z.string(), updated_at: z.string(),57  approval_id: z.string().optional(), thread_id: z.string().nullable().optional(),58  undo_until: z.string().nullable().optional().describe("Undo send: the message is held until this instant and can still be cancelled"),59})6061// ------------------------------------------------------------------ composition62type Threading = { inReplyTo?: string[]; references?: string[] }63type ExtraPart = { blobId: string; type: string; name: string | null; disposition: string; cid?: string | null }64const jAddr = (r: Recipient) => ({ email: r.email, name: r.name ?? null })65const strip = (id: string) => id.replace(/^<|>$/g, "")6667async function resolveFiles(p: Principal, mb: Mbx, refs: z.infer<typeof zAttachmentRef>[]): Promise<ExtraPart[]> {68  const out: ExtraPart[] = []69  for (const ref of refs) {70    const [f] = await sql`select * from files where id = ${ref.file_id} and expires_at > now()71      and ${p.type === "key" ? sql`key_id = ${p.keyId}` : sql`user_id = ${p.userId}`}`72    if (!f) throw bad("unknown_file", 400, `Unknown or expired file ${ref.file_id}`, { file_id: ref.file_id })73    if (f.mailbox_id !== mb.id) throw bad("file_wrong_mailbox", 400, "This file was uploaded for another mailbox than the sender's", { file_id: ref.file_id })74    if (ref.inline && !/^image\/(png|jpeg|gif|webp)$/.test(f.type)) throw bad("invalid_inline_image", 400, "Inline attachments must be PNG, JPEG, GIF or WebP images", { file_id: ref.file_id })75    out.push({ blobId: f.blob_id, type: f.type, name: ref.filename ?? f.name, disposition: ref.inline ? "inline" : "attachment", cid: ref.inline ? (ref.cid ?? ref.file_id) : null })76  }77  return out78}7980/** Crée le message comme brouillon dans la boîte (toujours : c'est lui qui sera soumis, approuvé, programmé ou gardé). */81async function createDraft(mb: Mbx, from: AddressRow, b: z.infer<typeof zCompose>, parts: ExtraPart[], th: Threading, templateHtml?: string): Promise<{ emailId: string; threadId: string }> {82  const custom = validateCustomHeaders(b.headers)83  const drafts = await roleFolder(mb, "drafts", true)84  // Un modèle stocké a déjà été assaini à l'enregistrement (assainisseur de modèles, qui garde la mise en page) et ses valeurs échappées au rendu ;85  // tout autre HTML d'appelant passe par la liste blanche stricte.86  const html = templateHtml ?? (b.html !== undefined ? sanitizeHtml(b.html) : undefined)87  const text = b.text ?? (html !== undefined ? htmlToText(html) : "")88  const email: Record<string, unknown> = {89    mailboxIds: { [drafts!]: true }, keywords: { $draft: true, $seen: true },90    from: [{ email: from.address, name: from.display_name || mb.display_name || null }],91    to: b.to.map(jAddr), cc: b.cc.map(jAddr), bcc: b.bcc.map(jAddr), subject: b.subject,92    bodyValues: { t: { value: text }, ...(html !== undefined ? { h: { value: html } } : {}) },93    textBody: [{ partId: "t", type: "text/plain" }], ...(html !== undefined ? { htmlBody: [{ partId: "h", type: "text/html" }] } : {}),94    ...(parts.length ? { attachments: parts.map((a) => ({ blobId: a.blobId, type: a.type, name: a.name, disposition: a.disposition, ...(a.cid ? { cid: a.cid } : {}) })) } : {}),95    ...(th.inReplyTo?.length ? { inReplyTo: th.inReplyTo } : {}), ...(th.references?.length ? { references: th.references } : {}),96  }97  for (const h of custom) {98    if (h.name.toLowerCase() === "reply-to") email.replyTo = h.value.split(",").map((a) => ({ email: a.trim().toLowerCase() }))99    // List-Unsubscribe est une liste d'URL : la forme asURLs la garde lisible quelle que soit sa longueur (asText la découpait en mots encodés RFC 2047 au-delà de 76 caractères).100    else if (h.name.toLowerCase() === "list-unsubscribe") {101      const urls = [...h.value.matchAll(/<([^<>\s]+)>/g)].map((m) => m[1])102      if (!urls.length || urls.some((u) => !/^(https?:\/\/|mailto:)/i.test(u))) throw bad("invalid_header", 400, "List-Unsubscribe must be one or more <http(s)://…> or <mailto:…> entries")103      email["header:List-Unsubscribe:asURLs"] = urls104    }105    else email[`header:${h.name}:asText`] = h.value106  }107  if (b.priority && b.priority !== "normal") {108    email["header:X-Priority:asText"] = b.priority === "high" ? "1" : "5"109    email["header:Importance:asText"] = b.priority110  }111  const [r] = await jmapOk(mb, [["Email/set", { create: { e: email } }]])112  const created = r.created?.e113  if (!created) {114    const err = r.notCreated?.e ?? {}115    if (err.type === "blobNotFound" || /blob/i.test(String(err.description ?? ""))) throw bad("file_expired", 400, "An attached file is no longer available on the mail server; upload it again")116    throw bad("message_rejected", 400, `The mail server refused this message: ${err.type ?? "unknown"}${err.description ? ` (${err.description})` : ""}`)117  }118  return { emailId: created.id, threadId: created.threadId }119}120121async function threadingOf(p: Principal, b: z.infer<typeof zCompose>): Promise<Threading> {122  if (b.reply_to_message_id) {123    const { email } = await loadEmail(p, b.reply_to_message_id, ["messageId", "references", "from", "to", "cc", "bcc", "header:Delivered-To:asText:all"], false)124    const mid = (email.messageId ?? []) as string[]125    return { inReplyTo: mid, references: [...((email.references ?? []) as string[]), ...mid].slice(-50) }126  }127  return { inReplyTo: b.in_reply_to ? [strip(b.in_reply_to)] : undefined, references: b.references?.map(strip) ?? (b.in_reply_to ? [strip(b.in_reply_to)] : undefined) }128}129130type Decision = { mode: "now" | "scheduled" | "pending_approval"; external: boolean; externalRecipients: string[]; sendAt: Date | null }131/** Politique d'envoi : destinataires, domaines permis, envois externes (approbation humaine par défaut), programmation, limite quotidienne. */132async function decide(p: Principal, recipients: string[], sendAtRaw: string | undefined, checkLimit = true): Promise<Decision> {133  if (!recipients.length) throw bad("no_recipients", 400, "At least one recipient (to, cc or bcc) is required")134  if (recipients.length > 100) throw bad("too_many_recipients", 400, "At most 100 recipients per message")135  const externalRecipients: string[] = []136  for (const r of recipients) if (await isExternal(r)) externalRecipients.push(r)137  let mode: Decision["mode"] = "now"138  if (p.type === "key") {139    if (p.allowedDomains.length) {140      const refused = recipients.filter((r) => !p.allowedDomains.includes(r.split("@")[1]))141      if (refused.length) throw bad("recipient_domain_not_allowed", 403, "This key may only write to its allowed recipient domains", { recipients: refused })142    }143    if (externalRecipients.length) {144      if (p.externalPolicy === "deny") throw bad("external_send_denied", 403, "This key is not allowed to send outside the hosted domains", { recipients: externalRecipients })145      if (p.externalPolicy === "approval") mode = "pending_approval"146    }147    if (checkLimit) await assertDailyLimit(p)148  }149  let sendAt: Date | null = null150  if (sendAtRaw) {151    sendAt = new Date(sendAtRaw)152    if (sendAt.getTime() > Date.now() + 30 * 86400_000) throw bad("send_at_too_far", 400, "send_at may be at most 30 days ahead")153    if (sendAt.getTime() <= Date.now() + 1000) sendAt = null154    else if (mode === "now") mode = "scheduled"155  }156  return { mode, external: externalRecipients.length > 0, externalRecipients, sendAt }157}158159const draftResult = (mb: Mbx, from: AddressRow, emailId: string, thread: string, recipients: string[]) => ({160  id: msgId(mb.id, emailId), status: "draft" as const, from: from.address, message_id: msgId(mb.id, emailId), thread_id: threadId(mb.id, thread),161  recipients: recipients.map((address) => ({ address, status: "draft", smtp_reply: null })), external: false, send_at: null, attempts: 0, last_error: null,162  submitted_at: null, final_at: null, created_at: new Date().toISOString(), updated_at: new Date().toISOString(),163})164165/** Destinataires « sensibles » (préférences de rédaction de l'utilisateur : adresses ou @domaine) parmi ceux du message. */166async function sensitiveRecipients(userId: string, recipients: string[]): Promise<string[]> {167  const [r] = await sql`select prefs->'sensitive' as list from compose_prefs where user_id = ${userId}`168  const list = new Set(Array.isArray(r?.list) ? (r.list as unknown[]).map((x) => String(x).toLowerCase()) : [])169  return list.size ? recipients.filter((a) => list.has(a) || list.has(`@${a.split("@")[1]}`)) : []170}171172/** Chemin commun de tout envoi : autorisation de l'adresse, politique, création du brouillon, puis envoi / programmation / approbation. */173export async function sendMessage(p: Principal, b: SendBody, extraParts: ExtraPart[] = [], threading?: Threading) {174  requireScope(p, b.draft ? "mail.drafts" : "mail.send")175  const { address: from, access } = await sendAddress(p, b.from)176  const mb = access.mailbox177  const recipients = [...new Set([...b.to, ...b.cc, ...b.bcc].map((r) => r.email))]178  let templateHtml: string | undefined179  if (b.template_id) {180    if (b.html !== undefined || b.text !== undefined) throw bad("template_conflict", 400, "With `template_id`, omit `html` and `text`")181    const r = await renderForSend(p, b.template_id, b.variables ?? {})182    templateHtml = r.html183    b = { ...b, subject: b.subject || r.subject, text: r.text }184  } else if (b.variables) throw bad("template_conflict", 400, "`variables` requires `template_id`")185  if (b.text === undefined && b.html === undefined && !templateHtml && !b.draft) throw bad("empty_message", 400, "Provide `text` and/or `html`, or a `template_id`")186  // SP Mail Next : confirmation des destinataires sensibles (sessions seulement ; les clés d'API ne sont pas concernées), avant toute mise en file.187  if (!b.draft && p.type === "user" && !b.confirm_sensitive) {188    const sensitive = await sensitiveRecipients(p.userId, recipients)189    if (sensitive.length) throw bad("confirmation_required", 409, "Some recipients are marked as sensitive: resend with `confirm_sensitive: true` to confirm", { recipients: sensitive })190  }191  let remindAt: Date | null = null192  if (!b.draft && b.remind_at) {193    if (p.type !== "user") throw bad("session_required", 403, "`remind_at` creates a personal reminder and is only available to signed-in users")194    remindAt = new Date(b.remind_at)195    if (remindAt.getTime() > Date.now() + 366 * 86400_000) throw bad("remind_at_too_far", 400, "remind_at may be at most one year ahead")196  }197  let decision = b.draft ? null : await decide(p, recipients, b.send_at)198  // Annulation d'envoi : une vraie retenue côté serveur. Le message est programmé à maintenant + undo_seconds ; rien n'atteint la file du serveur de courrier avant.199  let undoUntil: Date | null = null200  if (decision && decision.mode === "now" && b.undo_seconds) {201    undoUntil = new Date(Date.now() + b.undo_seconds * 1000)202    decision = { ...decision, mode: "scheduled", sendAt: undoUntil }203  }204  if (b.attachments.length) requireScope(p, "mail.attachments.write")205  const parts = [...(await resolveFiles(p, mb, b.attachments)), ...extraParts]206  const th = threading ?? (await threadingOf(p, b))207  const draft = await createDraft(mb, from, b, parts, th, templateHtml)208  if (!decision) {209    await emitEvent({ type: "draft.created", addressId: from.id, address: from.address, mailboxId: mb.id, data: { message_id: msgId(mb.id, draft.emailId), from: from.address, to: recipients } })210    return respond(201, draftResult(mb, from, draft.emailId, draft.threadId, recipients))211  }212  const { row, approvalId } = await createOutbound({ principal: p, address: from, mailbox: mb, emailId: draft.emailId, recipients, external: decision.external, mode: decision.mode, sendAt: decision.sendAt, externalRecipients: decision.externalRecipients, undoUntil, remindAt, remindIfNoReply: b.remind_if_no_reply })213  const body = presentOutbound(row, { thread_id: threadId(mb.id, draft.threadId), ...(approvalId ? { approval_id: approvalId } : {}) })214  return respond(row.status === "pending_approval" || row.status === "scheduled" || row.status === "queued" ? 202 : 200, body)215}216217// ------------------------------------------------------------------ envoi218route({219  method: "POST", path: "/messages/send", bodyLimit: 6 * 1024 * 1024, tag: "Sending", summary: "Send a message (or schedule it, or save it as a draft)", scopes: ["mail.send", "mail.drafts"], idempotent: true,220  description: "200 = handed to the mail server (`sent`) or refused by it (`failed`). 202 = accepted but not yet handed over: `scheduled`, `pending_approval` (external recipients with key policy `approval`) or `queued` (mail server unreachable, will retry). 201 = `draft: true`.",221  body: zSendBody, response: zOutbound, otherStatuses: { 201: "Draft saved", 202: "Accepted: scheduled, pending approval or queued" },222  handler: async ({ principal, body }) => sendMessage(principal, body),223})224225route({226  method: "POST", path: "/messages/send-batch", bodyLimit: 6 * 1024 * 1024, tag: "Sending", summary: "Send up to 50 messages; each item is validated and limited independently", scopes: ["mail.send"], idempotent: true,227  body: z.object({ messages: z.array(z.unknown()).min(1).max(50) }).strict(),228  response: z.object({ results: z.array(z.object({ index: z.number(), ok: z.boolean(), status: z.number(), message: zOutbound.optional(), error: z.object({ code: z.string(), message: z.string(), details: z.unknown().optional() }).optional() })) }),229  handler: async ({ principal, body }) => {230    const results = []231    for (const [index, raw] of (body.messages as unknown[]).entries()) {232      try {233        const parsed = zSendBody.safeParse(raw)234        if (!parsed.success) throw bad("invalid_request", 400, parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ").slice(0, 500))235        const r = await sendMessage(principal, parsed.data)236        results.push({ index, ok: true, status: r.status, message: r.body as z.infer<typeof zOutbound> })237      } catch (e) {238        if (!(e instanceof HttpError)) throw e239        results.push({ index, ok: false, status: e.status, error: errorBody(e.code, e.message, e.details).error })240      }241    }242    return { results }243  },244})245246// ------------------------------------------------------------------ réponse et transfert247const zReplyBody = z.object({248  from: zEmail.optional().describe("Defaults to the allowed address the message was delivered to, else the mailbox's primary address"),249  reply_all: z.boolean().default(false), text: z.string().max(2_000_000).optional(), html: z.string().max(2_000_000).optional(),250  cc: z.array(zRecipient).max(100).default([]), bcc: z.array(zRecipient).max(100).default([]), attachments: z.array(zAttachmentRef).max(30).default([]),251  headers: z.record(z.string().max(64), z.string().max(900)).optional(), send_at: z.string().optional(), draft: z.boolean().optional(),252  ...zSendOptions,253}).strict()254255/** Adresse d'expédition par défaut d'une réponse : celle (permise) à laquelle le message a été remis. */256async function defaultFrom(p: Principal, mb: Mbx, e: JEmail): Promise<string> {257  const acc = (await accessMap(p)).get(mb.id) as Access258  const mine = new Set(acc.addresses.map((a) => a.address))259  const candidates = [...deliveredTo(e), ...[...(e.to ?? []), ...(e.cc ?? [])].map((a: { email: string }) => String(a.email).toLowerCase())]260  return candidates.find((a) => mine.has(a)) ?? (mine.has(mb.address) ? mb.address : (acc.addresses[0]?.address ?? mb.address))261}262const reSubject = (prefix: string, s: string) => (new RegExp(`^\\s*${prefix}\\s*:`, "i").test(s) ? s : `${prefix}: ${s}`).replace(/[\r\n]+/g, " ").slice(0, 990)263264route({265  method: "POST", path: "/messages/{id}/reply", bodyLimit: 6 * 1024 * 1024, tag: "Sending", summary: "Reply (or reply-all) to a message, keeping the thread", scopes: ["mail.send"], idempotent: true,266  description: "Recipients, subject (`Re:`), In-Reply-To and References come from the original. Same outcomes and status codes as POST /messages/send.",267  params: z.object({ id: z.string().max(400) }), body: zReplyBody, response: zOutbound, otherStatuses: { 201: "Draft saved", 202: "Accepted" },268  handler: async ({ principal, params, body }) => {269    const { mb, email } = await loadEmail(principal, params.id, LIST_PROPS.concat(["replyTo", "messageId", "references"]), false)270    const from = body.from ?? (await defaultFrom(principal, mb, email))271    const acc = (await accessMap(principal)).get(mb.id)!272    const own = new Set([...acc.addresses.map((a) => a.address), from])273    const target = ((email.replyTo?.length ? email.replyTo : email.from) ?? []) as { email: string; name: string | null }[]274    const to = target.map((a) => ({ email: a.email.toLowerCase(), name: a.name ?? undefined }))275    const cc = [...body.cc]276    if (body.reply_all) for (const a of [...(email.to ?? []), ...(email.cc ?? [])] as { email: string; name: string | null }[]) {277      const em = a.email.toLowerCase()278      if (!own.has(em) && !to.some((x) => x.email === em) && !cc.some((x) => x.email === em)) cc.push({ email: em, name: a.name ?? undefined })279    }280    const mid = (email.messageId ?? []) as string[]281    const res = await sendMessage(principal, {282      from, to, cc, bcc: body.bcc, subject: reSubject("Re", email.subject ?? ""), text: body.text, html: body.html, attachments: body.attachments, headers: body.headers,283      send_at: body.send_at, draft: body.draft, undo_seconds: body.undo_seconds, remind_at: body.remind_at, remind_if_no_reply: body.remind_if_no_reply, confirm_sensitive: body.confirm_sensitive,284    }, [], { inReplyTo: mid, references: [...((email.references ?? []) as string[]), ...mid].slice(-50) })285    if (!body.draft) await jmapOk(mb, [["Email/set", { update: { [email.id]: { "keywords/$answered": true } } }]]).catch(() => {})286    return res287  },288})289290route({291  method: "POST", path: "/messages/{id}/forward", bodyLimit: 6 * 1024 * 1024, tag: "Sending", summary: "Forward a message, keeping its attachments", scopes: ["mail.send"], idempotent: true,292  description: "Requires `mail.send` AND `mail.read` (forwarding re-reads the content). The original's attachments are re-attached; its text is quoted below yours. The sender must belong to the same mailbox as the original.",293  params: z.object({ id: z.string().max(400) }),294  body: z.object({295    from: zEmail.optional(), to: z.array(zRecipient).min(1).max(100), cc: z.array(zRecipient).max(100).default([]), bcc: z.array(zRecipient).max(100).default([]),296    text: z.string().max(2_000_000).default(""), include_attachments: z.boolean().default(true), send_at: z.string().optional(), draft: z.boolean().optional(),297    ...zSendOptions,298  }).strict(),299  response: zOutbound, otherStatuses: { 201: "Draft saved", 202: "Accepted" },300  handler: async ({ principal, params, body }) => {301    requireScope(principal, "mail.read") // transférer, c'est relire le contenu : une clé d'envoi seul ne peut pas s'en servir pour exfiltrer302    const { mb, email } = await loadEmail(principal, params.id)303    const from = body.from ?? (await defaultFrom(principal, mb, email))304    const hit = await findAllowed(principal, from)305    if (hit && hit.access.mailbox.id !== mb.id) throw bad("cross_mailbox_forward_unsupported", 400, "Forward from an address of the mailbox that holds the message")306    const orig = presentMessage(mb, email, await folders(mb))307    const who = (l: { email: string; name: string | null }[]) => l.map((a) => (a.name ? `${a.name} <${a.email}>` : a.email)).join(", ")308    const head = [`---------- Forwarded message ----------`, `From: ${who(orig.from)}`, `Date: ${orig.sent_at ?? orig.received_at}`, `Subject: ${orig.subject}`, `To: ${who(orig.to)}`]309    const text = `${body.text}\n\n${head.join("\n")}\n\n${orig.text ?? ""}`310    const html = orig.html !== null ? `<div>${escapeHtml(body.text).replace(/\n/g, "<br>")}</div><br><div>${head.map(escapeHtml).join("<br>")}</div><br><blockquote>${orig.html}</blockquote>` : undefined311    const parts = body.include_attachments ? ((email.attachments ?? []) as any[]).map((a) => ({ blobId: a.blobId, type: a.type ?? "application/octet-stream", name: a.name ?? null, disposition: a.disposition === "inline" ? "inline" : "attachment", cid: a.cid ?? null })) : []312    const res = await sendMessage(principal, { from, to: body.to, cc: body.cc, bcc: body.bcc, subject: reSubject("Fwd", orig.subject), text, html, attachments: [], send_at: body.send_at, draft: body.draft, undo_seconds: body.undo_seconds, remind_at: body.remind_at, remind_if_no_reply: body.remind_if_no_reply, confirm_sensitive: body.confirm_sensitive }, parts, {})313    if (!body.draft) await jmapOk(mb, [["Email/set", { update: { [email.id]: { "keywords/$forwarded": true } } }]]).catch(() => {})314    return res315  },316})317318// ------------------------------------------------------------------ suivi d'envoi et messages programmés319async function ownOutbound(p: Principal, id: string): Promise<OutboundRow> {320  const o = /^msg_out_[A-Za-z0-9_-]{10,40}$/.test(id) ? await outboundById(id) : null321  if (!o) throw bad("not_found", 404, "Unknown outbound message")322  if (p.type === "key" ? o.key_id !== p.keyId && !(p.allAddresses && p.scopes.has("mail.admin")) : o.user_id !== p.userId && p.role !== "admin") {323    // d'autres appelants ne voient un envoi que s'ils peuvent agir au nom de son adresse d'expédition324    const hit = o.address_id ? await findAllowed(p, o.address_id) : null325    if (!hit) throw bad("not_found", 404, "Unknown outbound message")326  }327  return o328}329const zOutboundList = z.object({ data: z.array(zOutbound), next_cursor: z.string().nullable(), has_more: z.boolean() })330async function listOutbound(p: Principal, q: { status?: string; limit: number; cursor?: string }, onlyScheduled = false) {331  const c = decodeCursor<{ t: string; i: string }>(q.cursor, (x) => typeof x.t === "string" && typeof x.i === "string")332  const mine = (await accessMap(p)).values()333  const addressIds = [...mine].flatMap((a) => a.addresses.map((x) => x.id))334  const rows = (await sql`select * from outbound_messages335    where (${p.type === "key" ? sql`key_id = ${p.keyId}` : sql`user_id = ${p.userId}`} or address_id = any(${addressIds}::uuid[]))336      ${onlyScheduled ? sql`and status = 'scheduled'` : q.status ? sql`and status = ${q.status}` : sql``}337      ${c ? sql`and (date_trunc('milliseconds', created_at), id) < (${new Date(c.t)}, ${c.i})` : sql``}338    order by date_trunc('milliseconds', created_at) desc, id desc limit ${q.limit + 1}`) as unknown as OutboundRow[]339  const page = rows.slice(0, q.limit)340  const more = rows.length > q.limit341  return { data: page.map((o) => presentOutbound(o)), next_cursor: more ? encodeCursor({ t: new Date(page[page.length - 1].created_at).toISOString(), i: page[page.length - 1].id }) : null, has_more: more }342}343const zOutQuery = z.object({ status: z.enum(["queued", "scheduled", "pending_approval", "sent", "delivered", "deferred", "bounced", "failed", "cancelled"]).optional(), limit: z.coerce.number().int().min(1).max(100).default(25), cursor: z.string().max(2000).optional() })344route({345  method: "GET", path: "/messages/outbound", tag: "Sending", summary: "Messages sent through the API by this caller, with delivery status", scopes: ["mail.send", "mail.read"],346  query: zOutQuery, response: zOutboundList, handler: async ({ principal, query }) => listOutbound(principal, query),347})348route({349  method: "GET", path: "/messages/outbound/{id}", tag: "Sending", summary: "Delivery status of one sent message (per recipient, with SMTP replies)", scopes: ["mail.send", "mail.read"],350  params: z.object({ id: z.string().max(60) }), response: zOutbound, handler: async ({ principal, params }) => presentOutbound(await ownOutbound(principal, params.id)),351})352route({353  method: "GET", path: "/messages/scheduled", tag: "Sending", summary: "Scheduled messages not yet sent", scopes: ["mail.send"],354  query: zOutQuery.omit({ status: true }), response: zOutboundList, handler: async ({ principal, query }) => listOutbound(principal, query, true),355})356route({357  method: "DELETE", path: "/messages/scheduled/{id}", tag: "Sending", summary: "Cancel a scheduled message (nothing is sent, the stored draft is destroyed)", scopes: ["mail.send"],358  params: z.object({ id: z.string().max(60) }), response: zOutbound, otherStatuses: { 409: "not_cancellable" },359  handler: async ({ principal, params }) => {360    const o = await ownOutbound(principal, params.id)361    if (o.status !== "scheduled") throw bad("not_cancellable", 409, "Only scheduled messages can be cancelled")362    return presentOutbound(await cancelOutbound(o, "cancelled by the caller"))363  },364})365366// ------------------------------------------------------------------ brouillons367const zDraftBody = zCompose.partial({ from: true }).extend({ from: zEmail }).strict()368// Modification : seuls les champs fournis remplacent ceux du brouillon (aucune valeur par défaut ici).369const zDraftPatch = zCompose.partial().extend({370  to: z.array(zRecipient).max(100).optional(), cc: z.array(zRecipient).max(100).optional(), bcc: z.array(zRecipient).max(100).optional(),371  subject: zSubject.optional(), attachments: z.array(zAttachmentRef).max(30).optional(),372}).strict()373async function loadDraft(p: Principal, id: string) {374  const r = await loadEmail(p, id)375  if (!r.email.keywords?.$draft) throw bad("not_a_draft", 409, "This message is not a draft")376  return r377}378route({379  method: "POST", path: "/drafts", bodyLimit: 6 * 1024 * 1024, tag: "Drafts", summary: "Create a draft", scopes: ["mail.drafts"], idempotent: true, status: 201, body: zDraftBody, response: zOutbound,380  handler: async ({ principal, body }) => sendMessage(principal, { ...body, draft: true }),381})382route({383  method: "GET", path: "/drafts", tag: "Drafts", summary: "List drafts", scopes: ["mail.drafts"],384  query: zListQuery.pick({ address: true, limit: true, cursor: true }), response: z.object({ data: z.array(zMessageSummary), next_cursor: z.string().nullable(), has_more: z.boolean() }),385  handler: async ({ principal, query }) => {386    const r = await listMessages(principal, { ...query, folder: "drafts" } as z.infer<typeof zListQuery>)387    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 }388  },389})390route({391  method: "GET", path: "/drafts/{id}", tag: "Drafts", summary: "Read a draft", scopes: ["mail.drafts"], params: z.object({ id: z.string().max(400) }), response: zMessage,392  handler: async ({ principal, params }) => { const { mb, email } = await loadDraft(principal, params.id); return presentMessage(mb, email, await folders(mb)) },393})394route({395  method: "PATCH", path: "/drafts/{id}", bodyLimit: 6 * 1024 * 1024, tag: "Drafts", summary: "Replace fields of a draft", scopes: ["mail.drafts"],396  description: "Messages are immutable on the mail server: the draft is recreated with the merged fields and the response carries its NEW id. Attachments are kept unless `attachments` is given.",397  params: z.object({ id: z.string().max(400) }), body: zDraftPatch, response: zOutbound,398  handler: async ({ principal, params, body }) => {399    const { mb, email } = await loadDraft(principal, params.id)400    const cur = presentMessage(mb, email, [])401    const back = (l: { email: string; name: string | null }[]) => l.map((a) => ({ email: a.email.toLowerCase(), name: a.name ?? undefined }))402    const keep = body.attachments === undefined ? ((email.attachments ?? []) as any[]).map((a) => ({ blobId: a.blobId, type: a.type, name: a.name ?? null, disposition: a.disposition === "inline" ? "inline" : "attachment", cid: a.cid ?? null })) : []403    const merged = {404      from: body.from ?? cur.from[0]?.email.toLowerCase() ?? mb.address, to: body.to ?? back(cur.to), cc: body.cc ?? back(cur.cc), bcc: body.bcc ?? back(cur.bcc),405      subject: body.subject ?? cur.subject, text: body.text ?? (body.html === undefined ? (cur.text ?? "") : undefined), html: body.html ?? (body.text === undefined ? (cur.html ?? undefined) : undefined),406      attachments: body.attachments ?? [], headers: body.headers, priority: body.priority, draft: true,407    }408    const th = body.reply_to_message_id || body.in_reply_to ? undefined : { inReplyTo: email.inReplyTo ?? undefined, references: email.references ?? undefined }409    const res = await sendMessage(principal, merged as SendBody, keep, th)410    await jmapOk(mb, [["Email/set", { destroy: [email.id] }]])411    return respond(200, res.body)412  },413})414route({415  method: "DELETE", path: "/drafts/{id}", tag: "Drafts", summary: "Discard a draft (destroyed, not moved to trash)", scopes: ["mail.drafts"], params: z.object({ id: z.string().max(400) }), response: zOk,416  handler: async ({ principal, params }) => {417    const { mb, email } = await loadDraft(principal, params.id)418    const [pending] = await sql`select 1 from outbound_messages where mailbox_id = ${mb.id} and email_id = ${email.id} and status in ('scheduled','pending_approval','queued')`419    if (pending) throw bad("draft_in_use", 409, "This draft backs a scheduled or pending message; cancel that message instead")420    await jmapOk(mb, [["Email/set", { destroy: [email.id] }]])421    return { ok: true as const }422  },423})424route({425  method: "POST", path: "/drafts/{id}/send", tag: "Drafts", summary: "Send an existing draft", scopes: ["mail.send"], idempotent: true,426  description: "The draft's From must be an address the caller may send from; the same policy checks as POST /messages/send apply.",427  params: z.object({ id: z.string().max(400) }), body: z.object({ send_at: z.string().optional() }).strict(), response: zOutbound, otherStatuses: { 202: "Accepted" },428  handler: async ({ principal, params, body }) => {429    const { mb, email } = await loadDraft(principal, params.id)430    const [pending] = await sql`select id from outbound_messages where mailbox_id = ${mb.id} and email_id = ${email.id} and status not in ('failed','cancelled')`431    if (pending) throw bad("draft_in_use", 409, "This draft is already being sent")432    const fromEmail = String(email.from?.[0]?.email ?? "").toLowerCase()433    const { address: from, access } = await sendAddress(principal, fromEmail)434    if (access.mailbox.id !== mb.id) throw bad("from_not_allowed", 403, "The draft's sender does not belong to this mailbox")435    const recipients = [...new Set([...(email.to ?? []), ...(email.cc ?? []), ...(email.bcc ?? [])].map((a: { email: string }) => String(a.email).toLowerCase()))]436    const d = await decide(principal, recipients, body.send_at)437    const { row, approvalId } = await createOutbound({ principal, address: from, mailbox: mb, emailId: email.id, recipients, external: d.external, mode: d.mode, sendAt: d.sendAt, externalRecipients: d.externalRecipients })438    return respond(["pending_approval", "scheduled", "queued"].includes(row.status) ? 202 : 200, presentOutbound(row, { thread_id: threadId(mb.id, email.threadId), ...(approvalId ? { approval_id: approvalId } : {}) }))439  },440})441442// ------------------------------------------------------------------ fichiers (pièces jointes à venir)443const zFile = z.object({ id: z.string(), name: z.string(), type: z.string(), size: z.number(), mailbox: z.string(), expires_at: z.string() })444route({445  method: "POST", path: "/files", tag: "Attachments", summary: "Upload a file to attach later (raw body)", scopes: ["mail.attachments.write"], status: 201, binaryBody: true, bodyLimit: 50 * 1024 * 1024,446  description: "Send the bytes as the raw request body with the file's Content-Type (multipart/form-data is NOT parsed). `address` selects the mailbox the file is bound to: it can only be attached to messages sent from that mailbox, by the caller that uploaded it. Max 50 MB. Not idempotent.",447  query: z.object({ filename: z.string().max(200).refine((s) => !/[\u0000-\u001f]/.test(s), "invalid filename").default("file"), address: zEmail.optional().describe("An address the caller may send from (required when several mailboxes are allowed)") }),448  response: zFile, otherStatuses: { 413: "file_too_large" },449  handler: async ({ principal, query, req, body }) => {450    const type = String(req.headers["content-type"] ?? "application/octet-stream").split(";")[0].trim().toLowerCase()451    if (type.startsWith("multipart/")) throw bad("multipart_not_supported", 415, "Upload the raw bytes as the request body (multipart/form-data is not supported)")452    if (!/^[a-z0-9.+-]+\/[a-z0-9.+-]+$/.test(type)) throw bad("invalid_content_type", 400, "Invalid Content-Type")453    let mb: Mbx454    if (query.address) mb = (await sendAddress(principal, query.address)).access.mailbox455    else {456      const all = [...(await accessMap(principal)).values()].filter((a) => a.canSend)457      if (all.length !== 1) throw bad("address_required", 400, "Specify `address`: this caller can send from several mailboxes")458      mb = all[0].mailbox459    }460    const blob = await uploadBlob(mb, body as Readable, type)461    const id = newFileId()462    const expires = new Date(Date.now() + config.fileTtlMinutes * 60_000)463    await sql`insert into files (id, key_id, user_id, mailbox_id, blob_id, name, type, size, expires_at)464      values (${id}, ${principal.type === "key" ? principal.keyId : null}, ${principal.type === "user" ? principal.userId : null}, ${mb.id}, ${blob.blobId}, ${query.filename}, ${type}, ${blob.size}, ${expires})`465    return { id, name: query.filename, type, size: blob.size, mailbox: mb.address, expires_at: expires.toISOString() }466  },467})468export { readViews, FULL_PROPS }469
Files main
Menu

Theme