Repository Public
1// Règles de tri → script Sieve (RFC 5228). Un seul script « spmail » porte les règles ET la réponse automatique :2// sur Stalwart, VacationResponse/set crée un script « vacation » qui DÉSACTIVE le script de règles (un seul script actif).3// La configuration structurée voyage dans un commentaire d'en-tête du script, ce qui permet de la relire sans analyser du Sieve.45export type RuleField = "from" | "to" | "subject"6export type RuleOp = "contains" | "is"7export interface RuleCondition {8 field: RuleField9 op: RuleOp10 value: string11}12export type RuleAction = { type: "move"; folder: string } | { type: "markRead" } | { type: "flag" } | { type: "trash" }13export interface Rule {14 id: string15 name: string16 enabled: boolean17 match: "all" | "any"18 conditions: RuleCondition[]19 actions: RuleAction[]20}21export interface VacationConfig {22 enabled: boolean23 subject: string24 text: string25 /** dates locales AAAA-MM-JJ, bornes incluses */26 from?: string | null27 to?: string | null28 /** délai minimal, en jours, entre deux réponses au même expéditeur */29 days?: number30}31export interface SieveConfig {32 rules: Rule[]33 vacation: VacationConfig34}3536export const SIEVE_SCRIPT_NAME = "spmail"37const MARK = "# spmail-config:"3839export const emptySieveConfig = (): SieveConfig => ({ rules: [], vacation: { enabled: false, subject: "", text: "", from: null, to: null, days: 1 } })4041/** Chaîne Sieve entre guillemets : seuls \ et " s'échappent ; les retours de ligne sont permis mais normalisés en CRLF. */42export function sieveQuote(s: string): string {43 return `"${s.replace(/\u0000/g, "").replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\r?\n/g, "\r\n")}"`44}4546function b64encode(s: string): string {47 const bytes = new TextEncoder().encode(s)48 let bin = ""49 for (const b of bytes) bin += String.fromCharCode(b)50 return btoa(bin)51}52function b64decode(s: string): string {53 const bin = atob(s)54 const bytes = new Uint8Array(bin.length)55 for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)56 return new TextDecoder().decode(bytes)57}5859function conditionTest(c: RuleCondition): string {60 const match = c.op === "is" ? ":is" : ":contains"61 const v = sieveQuote(c.value.trim())62 switch (c.field) {63 case "from":64 return `address ${match} "from" ${v}`65 case "to":66 return `address ${match} ["to", "cc"] ${v}`67 case "subject":68 return `header ${match} "subject" ${v}`69 }70}7172export function ruleIsComplete(r: Rule): boolean {73 return 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() !== "")74}7576/**77 * Produit le script. `trashFolder` est le nom réel du dossier Corbeille de la boîte.78 * Les règles s'évaluent dans l'ordre ; la première qui déplace ou supprime arrête le traitement.79 */80export function generateSieve(config: SieveConfig, trashFolder = "Deleted Items"): string {81 const rules = config.rules.filter((r) => r.enabled && ruleIsComplete(r))82 const vac = config.vacation83 const vacOn = vac.enabled && vac.text.trim() !== ""84 const req = new Set<string>()85 const body: string[] = []8687 for (const r of rules) {88 const tests = r.conditions.map(conditionTest)89 const test = tests.length === 1 ? tests[0] : `${r.match === "any" ? "anyof" : "allof"} (${tests.join(", ")})`90 const lines: string[] = []91 let terminal = false92 // les drapeaux d'abord : ils s'appliquent au classement qui suit93 for (const a of r.actions) {94 if (a.type === "markRead") {95 req.add("imap4flags")96 lines.push(`addflag "\\\\Seen";`)97 } else if (a.type === "flag") {98 req.add("imap4flags")99 lines.push(`addflag "\\\\Flagged";`)100 }101 }102 const filing = r.actions.find((a) => a.type === "trash") ?? r.actions.find((a) => a.type === "move")103 if (filing) {104 req.add("fileinto")105 if (filing.type === "trash") lines.push(`fileinto ${sieveQuote(trashFolder)};`)106 else if (filing.type === "move") {107 req.add("mailbox")108 lines.push(`fileinto :create ${sieveQuote(filing.folder.trim())};`)109 }110 terminal = true111 }112 if (terminal) lines.push("stop;")113 body.push(`# ${r.name.replace(/[\r\n]+/g, " ").trim() || "règle"}`, `if ${test} {`, ...lines.map((l) => ` ${l}`), "}", "")114 }115116 if (vacOn) {117 req.add("vacation")118 const args = [`:days ${Math.min(30, Math.max(1, Math.round(vac.days ?? 1)))}`]119 if (vac.subject.trim()) args.push(`:subject ${sieveQuote(vac.subject.trim())}`)120 const action = `vacation ${args.join(" ")} ${sieveQuote(vac.text)};`121 const isDate = (d?: string | null): d is string => !!d && /^\d{4}-\d{2}-\d{2}$/.test(d)122 const bounds: string[] = []123 if (isDate(vac.from)) bounds.push(`currentdate :value "ge" "date" ${sieveQuote(vac.from)}`)124 if (isDate(vac.to)) bounds.push(`currentdate :value "le" "date" ${sieveQuote(vac.to)}`)125 body.push("# réponse automatique")126 if (bounds.length) {127 req.add("date")128 req.add("relational")129 body.push(`if ${bounds.length === 1 ? bounds[0] : `allof (${bounds.join(", ")})`} {`, ` ${action}`, "}", "")130 } else body.push(action, "")131 }132133 const head = ["# SP Mail — script généré. Les modifications manuelles seront remplacées à la prochaine sauvegarde des règles.", `${MARK} ${b64encode(JSON.stringify(config))}`]134 if (req.size) head.push(`require [${[...req].sort().map((e) => `"${e}"`).join(", ")}];`)135 return [...head, "", ...body].join("\r\n").replace(/(\r\n)+$/, "\r\n")136}137138/** Relit la configuration structurée d'un script généré ; null si le script a été écrit à la main. */139export function parseSieveConfig(script: string): SieveConfig | null {140 const line = script.split(/\r?\n/).find((l) => l.startsWith(MARK))141 if (!line) return null142 try {143 const raw = JSON.parse(b64decode(line.slice(MARK.length).trim())) as Partial<SieveConfig>144 const base = emptySieveConfig()145 const rules = Array.isArray(raw.rules) ? raw.rules.filter((r): r is Rule => !!r && typeof r.id === "string" && Array.isArray(r.conditions) && Array.isArray(r.actions)) : []146 return { rules, vacation: { ...base.vacation, ...(raw.vacation ?? {}) } }147 } catch {148 return null149 }150}151152export function newRule(id: string): Rule {153 return { id, name: "", enabled: true, match: "all", conditions: [{ field: "from", op: "contains", value: "" }], actions: [{ type: "move", folder: "" }] }154}155