Repository Public
1// Script Sieve géré « spmail » : même nom et même format que le webmail (web/src/mail/sieve.ts), pour que les deux restent compatibles.2// Le serveur y ajoute un bloc délimité (« spmail-policy ») portant ce que seul le serveur connaît : politique de réponse3// « discard » d'une adresse et réexpédition. Le bloc est réinjecté après chaque sauvegarde faite par un client.4import { z } from "zod"56export const SIEVE_SCRIPT_NAME = "spmail"7const MARK = "# spmail-config:"8const POLICY_BEGIN = "# spmail-policy:begin"9const POLICY_END = "# spmail-policy:end"1011const zText = (max: number) => z.string().max(max)12export const zRuleCondition = z.object({ field: z.enum(["from", "to", "subject"]), op: z.enum(["contains", "is"]), value: zText(300) })13export const zRuleAction = z.union([14 z.object({ type: z.literal("move"), folder: zText(120) }),15 z.object({ type: z.literal("markRead") }), z.object({ type: z.literal("flag") }), z.object({ type: z.literal("trash") }),16])17export const zRule = z.object({18 id: zText(64), name: zText(120).default(""), enabled: z.boolean().default(true), match: z.enum(["all", "any"]).default("all"),19 conditions: z.array(zRuleCondition).max(20), actions: z.array(zRuleAction).max(6),20})21export const zVacation = z.object({22 enabled: z.boolean().default(false), subject: zText(200).default(""), text: zText(5000).default(""),23 from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).nullable().optional(), to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).nullable().optional(),24 days: z.number().int().min(1).max(30).optional(),25})26export type Rule = z.infer<typeof zRule>27export type Vacation = z.infer<typeof zVacation>28export type SieveConfig = { rules: Rule[]; vacation: Vacation }29export const emptySieveConfig = (): SieveConfig => ({ rules: [], vacation: { enabled: false, subject: "", text: "", from: null, to: null, days: 1 } })3031export function sieveQuote(s: string): string {32 return `"${s.replace(/\u0000/g, "").replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\r?\n/g, "\r\n")}"`33}34const conditionTest = (c: Rule["conditions"][number]) => {35 const match = c.op === "is" ? ":is" : ":contains"36 const v = sieveQuote(c.value.trim())37 return c.field === "from" ? `address ${match} "from" ${v}` : c.field === "to" ? `address ${match} ["to", "cc"] ${v}` : `header ${match} "subject" ${v}`38}39const ruleIsComplete = (r: Rule) => r.conditions.length > 0 && r.actions.length > 0 && r.conditions.every((c) => c.value.trim() !== "") && r.actions.every((a) => a.type !== "move" || a.folder.trim() !== "")4041/** Identique, à l'octet près, à generateSieve() du webmail. */42export function generateSieve(config: SieveConfig, trashFolder = "Deleted Items"): string {43 const rules = config.rules.filter((r) => r.enabled && ruleIsComplete(r))44 const vac = config.vacation45 const vacOn = vac.enabled && vac.text.trim() !== ""46 const req = new Set<string>()47 const body: string[] = []48 for (const r of rules) {49 const tests = r.conditions.map(conditionTest)50 const test = tests.length === 1 ? tests[0] : `${r.match === "any" ? "anyof" : "allof"} (${tests.join(", ")})`51 const lines: string[] = []52 for (const a of r.actions) {53 if (a.type === "markRead") { req.add("imap4flags"); lines.push(`addflag "\\\\Seen";`) }54 else if (a.type === "flag") { req.add("imap4flags"); lines.push(`addflag "\\\\Flagged";`) }55 }56 const filing = r.actions.find((a) => a.type === "trash") ?? r.actions.find((a) => a.type === "move")57 if (filing) {58 req.add("fileinto")59 if (filing.type === "trash") lines.push(`fileinto ${sieveQuote(trashFolder)};`)60 else if (filing.type === "move") { req.add("mailbox"); lines.push(`fileinto :create ${sieveQuote(filing.folder.trim())};`) }61 lines.push("stop;")62 }63 body.push(`# ${r.name.replace(/[\r\n]+/g, " ").trim() || "règle"}`, `if ${test} {`, ...lines.map((l) => ` ${l}`), "}", "")64 }65 if (vacOn) {66 req.add("vacation")67 const args = [`:days ${Math.min(30, Math.max(1, Math.round(vac.days ?? 1)))}`]68 if (vac.subject.trim()) args.push(`:subject ${sieveQuote(vac.subject.trim())}`)69 const action = `vacation ${args.join(" ")} ${sieveQuote(vac.text)};`70 const isDate = (d?: string | null): d is string => !!d && /^\d{4}-\d{2}-\d{2}$/.test(d)71 const bounds: string[] = []72 if (isDate(vac.from)) bounds.push(`currentdate :value "ge" "date" ${sieveQuote(vac.from)}`)73 if (isDate(vac.to)) bounds.push(`currentdate :value "le" "date" ${sieveQuote(vac.to)}`)74 body.push("# réponse automatique")75 if (bounds.length) {76 req.add("date"); req.add("relational")77 body.push(`if ${bounds.length === 1 ? bounds[0] : `allof (${bounds.join(", ")})`} {`, ` ${action}`, "}", "")78 } else body.push(action, "")79 }80 const head = ["# SP Mail — script généré. Les modifications manuelles seront remplacées à la prochaine sauvegarde des règles.", `${MARK} ${Buffer.from(JSON.stringify(config), "utf8").toString("base64")}`]81 if (req.size) head.push(`require [${[...req].sort().map((e) => `"${e}"`).join(", ")}];`)82 return [...head, "", ...body].join("\r\n").replace(/(\r\n)+$/, "\r\n")83}8485export function parseSieveConfig(script: string): SieveConfig | null {86 const line = script.split(/\r?\n/).find((l) => l.startsWith(MARK))87 if (!line) return null88 try {89 const raw = JSON.parse(Buffer.from(line.slice(MARK.length).trim(), "base64").toString("utf8")) as Partial<SieveConfig>90 const base = emptySieveConfig()91 const rules = Array.isArray(raw.rules) ? raw.rules.filter((r) => !!r && typeof r.id === "string" && Array.isArray(r.conditions) && Array.isArray(r.actions)) : []92 return { rules, vacation: { ...base.vacation, ...(raw.vacation ?? {}) } }93 } catch {94 return null95 }96}9798// ------------------------------------------------------------------ bloc de politique du serveur99export type MailboxPolicy = { discard: string[]; forwardTo?: string | null; forwardKeepCopy?: boolean }100101export function policyBlock(p: MailboxPolicy): string {102 const lines: string[] = []103 const req = new Set<string>()104 for (const a of [...p.discard].sort()) {105 req.add("envelope")106 lines.push(`if envelope :is "to" ${sieveQuote(a)} { discard; stop; }`)107 }108 if (p.forwardTo) {109 if (p.forwardKeepCopy !== false) { req.add("copy"); lines.push(`redirect :copy ${sieveQuote(p.forwardTo)};`) }110 else lines.push(`redirect ${sieveQuote(p.forwardTo)};`)111 }112 if (!lines.length) return ""113 return [POLICY_BEGIN, ...(req.size ? [`require [${[...req].sort().map((e) => `"${e}"`).join(", ")}];`] : []), ...lines, POLICY_END].join("\r\n") + "\r\n"114}115116export function stripPolicy(script: string): string {117 const b = script.indexOf(POLICY_BEGIN)118 if (b < 0) return script119 const e = script.indexOf(POLICY_END, b)120 if (e < 0) return script.slice(0, b)121 let end = e + POLICY_END.length122 if (script.startsWith("\r\n", end)) end += 2123 else if (script[end] === "\n") end += 1124 return script.slice(0, b) + script.slice(end)125}126127/** Position juste après les `require` de tête (seuls blancs et commentaires peuvent les précéder ou les séparer). */128export function afterRequires(script: string): number {129 let i = 0, last = 0130 const n = script.length131 for (;;) {132 while (i < n && /\s/.test(script[i])) i++133 if (script[i] === "#") { while (i < n && script[i] !== "\n") i++; continue }134 if (script.startsWith("/*", i)) { const e = script.indexOf("*/", i + 2); if (e < 0) return last; i = e + 2; continue }135 if (/^require\b/i.test(script.slice(i, i + 8))) {136 let quote = false137 while (i < n) {138 const ch = script[i]139 if (quote) { if (ch === "\\") i++; else if (ch === '"') quote = false }140 else if (ch === '"') quote = true141 else if (ch === ";") { i++; break }142 i++143 }144 if (script.startsWith("\r\n", i)) i += 2145 else if (script[i] === "\n") i += 1146 last = i147 continue148 }149 break150 }151 return last > 0 ? last : i152}153154/** Insère (ou remplace, ou retire) le bloc de politique dans un script, géré ou écrit à la main. */155export function applyPolicy(script: string, p: MailboxPolicy): string {156 const base = stripPolicy(script)157 const block = policyBlock(p)158 if (!block) return base159 const at = afterRequires(base)160 const head = base.slice(0, at)161 return head + (head && !head.endsWith("\n") ? "\r\n" : "") + block + base.slice(at)162}163