Repository Public
1import assert from "node:assert/strict"2import { test } from "node:test"3import type { ApiAddress } from "../mail/v1"4import {5 AVATAR_MAX_CHARS, addressState, avatarFits, buildCreatePayload, buildPatch, bytesToGb, convertibleKinds, countByFilter, dataUrlBytes, deleteRequest, editFormOf, emptyCreateForm,6 expiryInfo, fitWithin, gbToBytes, isoToLocalInput, keysForAddress, localInputToIso, matchesFilter, maxAvatarBytes, normaliseGrants, parseDays, parseDestinations, patchIsEmpty, pickAvatar, usageRatio,7} from "./addresses"89const NOW = Date.parse("2026-11-19T12:00:00Z")10const addr = (over: Partial<ApiAddress> = {}): ApiAddress => ({11 id: "a1", address: "ventes@stg.spboucher.ai", kind: "alias", mailbox: "contact@stg.spboucher.ai", mailbox_id: "m1", display_name: "Ventes", signature_text: "", signature_html: "", avatar: null,12 can_send: true, can_receive: true, status: "active", suspended_reason: null, expired: false, expires_at: null, retention_days: null, retention_trash_days: null, retention_junk_days: null,13 quota_bytes: null, reply_policy: "reject", protected: false, extra_destinations: [], inbound: "accept", created_at: "2026-11-01T00:00:00.000Z", updated_at: "2026-11-01T00:00:00.000Z", ...over,14})15const box = (over: Partial<ApiAddress> = {}) => addr({ id: "b1", address: "contact@stg.spboucher.ai", kind: "mailbox", ...over })16const value = <T,>(r: { ok: true; value: T } | { ok: false; error: string }): T => {17 assert.ok(r.ok, r.ok ? "" : `erreur inattendue : ${r.error}`)18 return (r as { value: T }).value19}20const error = (r: { ok: boolean; error?: string }) => {21 assert.equal(r.ok, false)22 return r.error23}2425test("filtre : boîtes, alias, partagées, temporaires, recherche", () => {26 const list = [box(), box({ address: "equipe@stg.spboucher.ai", kind: "shared" }), addr(), addr({ address: "tmp@stg.spboucher.ai", kind: "temporary", display_name: "" }), addr({ address: "bot@stg.spboucher.ai", kind: "send_only" })]27 assert.deepEqual(countByFilter(list), { all: 5, mailboxes: 2, aliases: 3, shared: 1, temporary: 1 })28 assert.equal(matchesFilter(list[2], "aliases", "VENT"), true)29 assert.equal(matchesFilter(list[2], "aliases", "contact@"), true, "la boîte cible est cherchée aussi")30 assert.equal(matchesFilter(list[2], "mailboxes"), false)31 assert.equal(matchesFilter(list[3], "all", "absent"), false)32})3334test("état affiché : l'expiration prime sur la suspension", () => {35 assert.equal(addressState(addr(), NOW), "active")36 assert.equal(addressState(addr({ status: "suspended" }), NOW), "suspended")37 assert.equal(addressState(addr({ status: "suspended", expired: true }), NOW), "expired")38 assert.equal(addressState(addr({ expires_at: "2026-11-19T11:59:59Z" }), NOW), "expired", "échéance passée avant le passage du robot")39 assert.equal(addressState(addr({ expires_at: "2026-11-20T00:00:00Z" }), NOW), "active")40})4142test("échéance : aucune, passée, proche, lointaine", () => {43 assert.deepEqual(expiryInfo(null, NOW), { kind: "none" })44 assert.deepEqual(expiryInfo("n'importe quoi", NOW), { kind: "none" })45 assert.deepEqual(expiryInfo("2026-11-19T12:00:00Z", NOW), { kind: "past" })46 assert.deepEqual(expiryInfo("2026-11-19T13:00:00Z", NOW), { kind: "soon", days: 1 })47 assert.deepEqual(expiryInfo("2026-11-26T12:00:00Z", NOW), { kind: "soon", days: 7 })48 assert.deepEqual(expiryInfo("2026-12-19T12:00:00Z", NOW), { kind: "later", days: 30 })49})5051test("dates : aller-retour datetime-local ↔ ISO", () => {52 const iso = localInputToIso("2026-12-24T18:30")53 assert.ok(iso)54 assert.equal(isoToLocalInput(iso), "2026-12-24T18:30")55 assert.equal(localInputToIso(""), null)56 assert.equal(localInputToIso("demain"), null)57 assert.equal(isoToLocalInput(null), "")58 assert.equal(isoToLocalInput("x"), "")59})6061test("destinations : découpage, normalisation, doublons, invalides", () => {62 assert.deepEqual(parseDestinations(" A@x.ca, b@x.ca;\na@x.ca pas-une-adresse "), { list: ["a@x.ca", "b@x.ca"], invalid: ["pas-une-adresse"] })63 assert.deepEqual(parseDestinations(""), { list: [], invalid: [] })64})6566test("création : boîte et boîte partagée (propriétaire facultatif, aucun champ d'alias)", () => {67 assert.deepEqual(value(buildCreatePayload({ ...emptyCreateForm("mailbox"), address: " Equipe@STG.spboucher.ai ", displayName: " Équipe ", mailbox: "x@y.ca", destinations: "z@y.ca", expiresLocal: "2027-01-01T00:00" }, null, NOW)), { address: "equipe@stg.spboucher.ai", kind: "mailbox", display_name: "Équipe" })68 assert.deepEqual(value(buildCreatePayload({ ...emptyCreateForm("shared"), address: "p@stg.spboucher.ai", ownerId: "u1" }, null, NOW)), { address: "p@stg.spboucher.ai", kind: "shared", user_id: "u1" })69})7071test("création : alias simple, multi-destinations, notification", () => {72 const base = { ...emptyCreateForm("alias"), address: "ventes@stg.spboucher.ai", mailbox: "Contact@stg.spboucher.ai" }73 assert.deepEqual(value(buildCreatePayload(base, null, NOW)), { address: "ventes@stg.spboucher.ai", kind: "alias", mailbox: "contact@stg.spboucher.ai" })74 const known = new Set(["a@stg.spboucher.ai", "b@stg.spboucher.ai"])75 assert.deepEqual(value(buildCreatePayload({ ...base, destinations: "a@stg.spboucher.ai, b@stg.spboucher.ai" }, known, NOW)).extra_destinations, ["a@stg.spboucher.ai", "b@stg.spboucher.ai"])76 assert.equal(value(buildCreatePayload({ ...base, kind: "notification" }, null, NOW)).kind, "notification")77})7879test("création : refus locaux (adresse, boîte cible, destinations)", () => {80 const base = { ...emptyCreateForm("alias"), address: "ventes@stg.spboucher.ai", mailbox: "contact@stg.spboucher.ai" }81 assert.equal(error(buildCreatePayload({ ...base, address: "ventes" }, null, NOW)), "address_invalid")82 assert.equal(error(buildCreatePayload({ ...base, mailbox: " " }, null, NOW)), "mailbox_required")83 assert.equal(error(buildCreatePayload({ ...base, displayName: "x".repeat(81) }, null, NOW)), "name_too_long")84 assert.equal(error(buildCreatePayload({ ...base, destinations: "oups" }, null, NOW)), "destinations_invalid")85 assert.equal(error(buildCreatePayload({ ...base, destinations: "contact@stg.spboucher.ai" }, null, NOW)), "destination_self")86 assert.equal(error(buildCreatePayload({ ...base, destinations: "ventes@stg.spboucher.ai" }, null, NOW)), "destination_self")87 assert.equal(error(buildCreatePayload({ ...base, destinations: "dehors@example.org" }, new Set(["a@stg.spboucher.ai"]), NOW)), "destination_unknown")88 assert.equal(error(buildCreatePayload({ ...base, destinations: Array.from({ length: 21 }, (_, i) => `d${i}@stg.spboucher.ai`).join(" ") }, null, NOW)), "destinations_too_many")89})9091test("création : envoi seul (politique de réponse, pas de destinations), réception seule", () => {92 const base = { ...emptyCreateForm("send_only"), address: "bot@stg.spboucher.ai", mailbox: "contact@stg.spboucher.ai", replyPolicy: "discard" as const, destinations: "a@stg.spboucher.ai" }93 assert.deepEqual(value(buildCreatePayload(base, null, NOW)), { address: "bot@stg.spboucher.ai", kind: "send_only", mailbox: "contact@stg.spboucher.ai", reply_policy: "discard" })94 const ro = value(buildCreatePayload({ ...base, kind: "receive_only" }, null, NOW))95 assert.equal(ro.reply_policy, undefined)96 assert.deepEqual(ro.extra_destinations, ["a@stg.spboucher.ai"])97})9899test("création : adresse temporaire — échéance obligatoire, future, envoyée en ISO", () => {100 const base = { ...emptyCreateForm("temporary"), address: "tmp@stg.spboucher.ai", mailbox: "contact@stg.spboucher.ai" }101 assert.equal(error(buildCreatePayload(base, null, NOW)), "expires_required")102 assert.equal(error(buildCreatePayload({ ...base, expiresLocal: "2020-01-01T00:00" }, null, NOW)), "expires_past")103 assert.equal(error(buildCreatePayload({ ...base, expiresLocal: "bientôt" }, null, NOW)), "expires_invalid")104 const p = value(buildCreatePayload({ ...base, expiresLocal: "2027-01-01T08:00" }, null, NOW))105 assert.equal(p.expires_at, new Date("2027-01-01T08:00").toISOString())106 // l'échéance reste facultative sur les autres natures de type alias107 assert.equal(value(buildCreatePayload({ ...base, kind: "alias", expiresLocal: "2027-01-01T08:00" }, null, NOW)).expires_at, p.expires_at)108})109110test("modification : rien de changé → corps vide", () => {111 for (const a of [addr(), box({ quota_bytes: 5_000_000_000, retention_trash_days: 30 }), addr({ kind: "temporary", expires_at: "2027-01-01T08:00:00.000Z", extra_destinations: ["a@stg.spboucher.ai"] })]) {112 assert.equal(patchIsEmpty(value(buildPatch(a, editFormOf(a)))), true, a.kind)113 }114})115116test("modification : nom, signatures, avatar, suspension", () => {117 const a = addr()118 const f = { ...editFormOf(a), displayName: " Service des ventes ", signatureText: "—\nVentes", signatureHtml: "<p><b>Ventes</b></p>", avatar: "data:image/png;base64,AAAA", status: "suspended" as const }119 assert.deepEqual(value(buildPatch(a, f)), { display_name: "Service des ventes", signature_text: "—\nVentes", signature_html: "<p><b>Ventes</b></p>", avatar: "data:image/png;base64,AAAA", status: "suspended" })120 assert.deepEqual(value(buildPatch(addr({ avatar: "data:image/png;base64,AAAA" }), { ...editFormOf(addr({ avatar: "data:image/png;base64,AAAA" })), avatar: null })), { avatar: null })121 assert.equal(error(buildPatch(a, { ...f, signatureText: "x".repeat(4001) })), "signature_too_long")122 assert.equal(error(buildPatch(a, { ...f, signatureHtml: "x".repeat(20_001) })), "html_too_long")123})124125test("modification : boîte — quota et conservation ; jamais de destinations", () => {126 const a = box()127 const f = { ...editFormOf(a), quotaGb: "2,5", retentionTrashDays: "30", retentionJunkDays: "14", retentionDays: "", destinations: "a@stg.spboucher.ai" }128 assert.deepEqual(value(buildPatch(a, f)), { retention_trash_days: 30, retention_junk_days: 14, quota_bytes: 2_500_000_000 })129 const b = box({ quota_bytes: 2_500_000_000, retention_days: 365 })130 assert.deepEqual(value(buildPatch(b, { ...editFormOf(b), quotaGb: "", retentionDays: "" })), { retention_days: null, quota_bytes: null })131 assert.equal(error(buildPatch(a, { ...f, retentionDays: "0" })), "days_invalid")132 assert.equal(error(buildPatch(a, { ...f, quotaGb: "beaucoup" })), "quota_invalid")133 assert.equal(error(buildPatch(a, { ...f, quotaGb: "0.0001" })), "quota_invalid")134})135136test("modification : alias — jamais de quota ni de conservation ; destinations et échéance", () => {137 const a = addr()138 const f = { ...editFormOf(a), quotaGb: "3", retentionDays: "10", destinations: "b@stg.spboucher.ai a@stg.spboucher.ai", expiresLocal: "2027-03-01T09:00" }139 assert.deepEqual(value(buildPatch(a, f)), { extra_destinations: ["b@stg.spboucher.ai", "a@stg.spboucher.ai"], expires_at: new Date("2027-03-01T09:00").toISOString() })140 const withExpiry = addr({ expires_at: "2027-03-01T09:00:00.000Z" })141 assert.deepEqual(value(buildPatch(withExpiry, { ...editFormOf(withExpiry), expiresLocal: "" })), { expires_at: null })142 assert.equal(error(buildPatch(a, { ...f, canReceive: false })), "destinations_need_receive")143 assert.equal(error(buildPatch(a, { ...f, destinations: "ventes@stg.spboucher.ai" })), "destination_self")144 assert.equal(error(buildPatch(a, { ...f, destinations: "x@example.org" }, new Set(["a@stg.spboucher.ai"]))), "destination_unknown")145})146147test("modification : conversion entre natures de type alias ; permissions imposées non envoyées", () => {148 const a = addr()149 assert.deepEqual(value(buildPatch(a, { ...editFormOf(a), kind: "send_only", canSend: false, canReceive: true, replyPolicy: "accept" })), { kind: "send_only", reply_policy: "accept" })150 assert.deepEqual(value(buildPatch(a, { ...editFormOf(a), kind: "receive_only", canSend: false })), { kind: "receive_only" })151 assert.equal(error(buildPatch(a, { ...editFormOf(a), kind: "temporary" })), "expires_required")152 assert.equal(error(buildPatch(a, { ...editFormOf(a), kind: "send_only", destinations: "a@stg.spboucher.ai" })), "destinations_need_receive")153 assert.deepEqual(value(buildPatch(a, { ...editFormOf(a), canSend: false })), { can_send: false })154 // une boîte ne change jamais de nature, quoi que dise le formulaire155 assert.equal(patchIsEmpty(value(buildPatch(box(), { ...editFormOf(box()), kind: "alias" }))), true)156 assert.deepEqual(convertibleKinds("mailbox"), ["mailbox"])157 assert.deepEqual(convertibleKinds("alias"), ["alias", "notification", "send_only", "receive_only", "temporary"])158})159160test("quota : gigaoctets ↔ octets, jours", () => {161 assert.equal(gbToBytes(""), null)162 assert.equal(gbToBytes("1"), 1_000_000_000)163 assert.equal(gbToBytes("0,5"), 500_000_000)164 assert.ok(Number.isNaN(gbToBytes("-1")))165 assert.ok(Number.isNaN(gbToBytes("1001")))166 assert.equal(bytesToGb(null), "")167 assert.equal(bytesToGb(2_500_000_000), "2.5")168 assert.equal(parseDays(""), null)169 assert.equal(parseDays("30"), 30)170 assert.ok(Number.isNaN(parseDays("1.5")))171 assert.ok(Number.isNaN(parseDays("36501")))172 assert.equal(usageRatio(500, 1000), 0.5)173 assert.equal(usageRatio(5000, 1000), 1)174 assert.equal(usageRatio(null, 1000), null)175 assert.equal(usageRatio(10, null), null)176})177178test("suppression : alias ou détachement sans corps ; purge avec confirmation explicite", () => {179 assert.deepEqual(deleteRequest("a1", "alias"), { path: "/addresses/a1" })180 assert.deepEqual(deleteRequest("b1", "detach"), { path: "/addresses/b1" })181 assert.deepEqual(deleteRequest("b 1", "purge"), { path: "/addresses/b%201?purge=delete-all-mail", json: { confirm: "delete-all-mail" } })182})183184test("avatar : borne de 90 000 caractères, formats, tailles", () => {185 const png = (n: number) => `data:image/png;base64,${"A".repeat(n)}`186 assert.equal(avatarFits(png(100)), true)187 assert.equal(avatarFits(png(AVATAR_MAX_CHARS - 22)), true, "pile à la borne")188 assert.equal(avatarFits(png(AVATAR_MAX_CHARS - 21)), false)189 assert.equal(avatarFits("data:image/gif;base64,AAAA"), false)190 assert.equal(avatarFits("data:image/svg+xml;base64,AAAA"), false)191 assert.equal(avatarFits("https://exemple.org/a.png"), false)192 assert.equal(dataUrlBytes("data:image/png;base64,AAAA"), 3)193 assert.equal(dataUrlBytes("data:image/png;base64,AAA="), 2)194 assert.equal(dataUrlBytes("data:image/png;base64,AA=="), 1)195 assert.equal(dataUrlBytes("rien"), 0)196 // le plus gros fichier admis, encodé, tient exactement sous la borne197 const max = maxAvatarBytes("image/jpeg")198 assert.ok(`data:image/jpeg;base64,`.length + Math.ceil(max / 3) * 4 <= AVATAR_MAX_CHARS)199 assert.ok(`data:image/jpeg;base64,`.length + Math.ceil((max + 3) / 3) * 4 > AVATAR_MAX_CHARS)200 assert.deepEqual(fitWithin(1024, 512, 256), { width: 256, height: 128 })201 assert.deepEqual(fitWithin(100, 50, 256), { width: 100, height: 50 }, "jamais d'agrandissement")202 assert.deepEqual(fitWithin(4000, 1, 256), { width: 256, height: 1 })203 assert.deepEqual(fitWithin(0, 10, 256), { width: 0, height: 0 })204})205206test("avatar : on réduit jusqu'au premier rendu qui tient", () => {207 const tried: number[] = []208 const url = pickAvatar(({ size }) => {209 tried.push(size)210 return `data:image/webp;base64,${"A".repeat(size * 500)}`211 })212 assert.deepEqual(tried, [256, 192, 128])213 assert.equal(url?.length, "data:image/webp;base64,".length + 64_000)214 assert.equal(pickAvatar(() => null), null)215 assert.equal(pickAvatar(() => "data:image/gif;base64,AAAA"), null)216})217218test("clés autorisées pour une adresse ; accès partagés normalisés", () => {219 const keys = [{ id: "k1", address_ids: ["a1"], all_addresses: false }, { id: "k2", address_ids: [], all_addresses: true }, { id: "k3", address_ids: ["zz"], all_addresses: false }]220 assert.deepEqual(keysForAddress(keys, "a1").map((k) => k.id), ["k1", "k2"])221 assert.deepEqual(222 normaliseGrants([{ user_id: "owner", can_read: true, can_send: true }, { user_id: "u1", can_read: true, can_send: false }, { user_id: "u1", can_read: true, can_send: true }, { user_id: "u2", can_read: false, can_send: false }], "owner"),223 [{ user_id: "u1", can_read: true, can_send: false }],224 )225})226