Repository Public
1// SP Mail Next — client APNs : jeton fournisseur ES256, HTTP/2 persistant, charge utile, heures calmes, classement des réponses.2// Aucune dépendance : node:http2 et node:crypto. Les fonctions pures (charge utile, heures calmes, expéditeurs prioritaires,3// niveaux d'aperçu, classement) sont exportées pour être testées sans réseau. Ni jeton ni charge utile ne sont journalisés.4import crypto from "node:crypto"5import fs from "node:fs"6import http2 from "node:http2"7import { config } from "../config.js"89// ------- types10export type Preview = "none" | "sender" | "full"11export type QuietHours = { start: string; end: string; tz: string }12export type PushKind = "new" | "badge" | "snooze" | "reminder" | "alert" | "test"13/** Ce que la file retient d'une notification : le texte déjà réduit au niveau d'aperçu choisi, jamais plus. */14export type Notice = { silent?: boolean; title?: string; subtitle?: string; body?: string; category?: string; sound?: boolean; timeSensitive?: boolean }15export type PushItem = { kind: PushKind; mailboxId?: string | null; emailId?: string | null; threadId?: string | null; notice: Notice; dedupKey?: string }16export type ApnsOutcome = "ok" | "retry" | "drop-token" | "fail"17export type ApnsResult = { outcome: ApnsOutcome; status: number; reason: string; apnsId: string | null }18export type ApnsDevice = { apns_token: string; environment: "production" | "sandbox"; bundle_id: string }1920export const APNS_HOSTS = { production: "api.push.apple.com", sandbox: "api.sandbox.push.apple.com" } as const21const TOKEN_TTL_MS = 50 * 60_000 // Apple refuse un jeton de plus d'une heure et sanctionne un renouvellement trop fréquent22const REQUEST_TIMEOUT_MS = 10_0002324// ------- heures calmes (fuseaux IANA par Intl)25export function isValidTimeZone(tz: string): boolean {26 try { new Intl.DateTimeFormat("en-US", { timeZone: tz }); return true } catch { return false }27}28const minutesOf = (hhmm: string): number | null => {29 const m = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(hhmm)30 return m ? Number(m[1]) * 60 + Number(m[2]) : null31}32/** Minute locale du jour (0–1439) dans un fuseau IANA. */33export function localMinutes(at: Date, tz: string): number {34 const parts = new Intl.DateTimeFormat("en-US", { timeZone: tz, hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).formatToParts(at)35 const get = (t: string) => Number(parts.find((p) => p.type === t)?.value ?? 0)36 return (get("hour") % 24) * 60 + get("minute")37}38/** Vrai si `at` tombe dans la plage [start, end[ du fuseau ; une plage peut enjamber minuit. Réglage invalide ou vide : jamais. */39export function inQuietHours(q: QuietHours | null | undefined, at: Date = new Date()): boolean {40 if (!q) return false41 const start = minutesOf(q.start), end = minutesOf(q.end)42 if (start === null || end === null || start === end || !isValidTimeZone(q.tz)) return false43 const now = localMinutes(at, q.tz)44 return start < end ? now >= start && now < end : now >= start || now < end45}4647// ------- expéditeurs prioritaires48/** `list` : adresses complètes ou « @domaine » (domaine exact). Comparaison insensible à la casse. */49export function isPrioritySender(list: readonly string[] | null | undefined, email: string | null | undefined): boolean {50 const e = (email ?? "").trim().toLowerCase()51 if (!e || !list?.length) return false52 const domain = e.slice(e.lastIndexOf("@"))53 return list.some((raw) => {54 const p = raw.trim().toLowerCase()55 return p !== "" && (p.startsWith("@") ? p === domain : p === e)56 })57}5859// ------- niveaux d'aperçu60const clip = (s: string, max: number) => { const t = s.replace(/\s+/g, " ").trim(); return t.length > max ? `${t.slice(0, max - 1)}…` : t }61const isFr = (locale?: string | null) => (locale ?? "").toLowerCase().startsWith("fr")62const GENERIC: Record<PushKind, [string, string]> = {63 new: ["New message", "Nouveau message"], badge: ["", ""], snooze: ["A snoozed message is back", "Un message mis en veille est de retour"],64 reminder: ["Follow-up reminder", "Rappel de suivi"], alert: ["SP Mail alert", "Alerte SP Mail"], test: ["Test notification", "Notification d'essai"],65}66export const genericText = (kind: PushKind, locale?: string | null) => GENERIC[kind][isFr(locale) ? 1 : 0]67/**68 * Texte d'une alerte de nouveau message selon la préférence : `none` (rien du message), `sender` (nom de l'expéditeur seulement),69 * `full` (expéditeur, objet, début du texte).70 */71export function previewText(level: Preview, msg: { fromName?: string | null; fromEmail?: string | null; subject?: string | null; preview?: string | null }, locale?: string | null, kind: PushKind = "new"): { title: string; subtitle?: string; body: string } {72 const generic = genericText(kind, locale)73 if (level === "none") return { title: "SP Mail", body: generic }74 const sender = clip(msg.fromName || msg.fromEmail || "SP Mail", 80)75 if (level === "sender") return { title: sender, body: generic }76 const subject = clip(msg.subject ?? "", 120), text = clip(msg.preview ?? "", 240)77 if (subject && text) return { title: sender, subtitle: subject, body: text }78 return { title: sender, body: subject || text || generic }79}8081// ------- charge utile et en-têtes82/** Charge utile APNs. `badge` nul : pastille non gérée (préférence « none ») ou total indisponible — la clé est alors omise. */83export function buildPayload(item: PushItem, badge: number | null): Record<string, unknown> {84 const n = item.notice85 if (item.kind === "badge" || n.silent) return { aps: { "content-available": 1, ...(badge === null ? {} : { badge }) }, kind: "badge" }86 const aps: Record<string, unknown> = {87 alert: { title: n.title ?? "SP Mail", ...(n.subtitle ? { subtitle: n.subtitle } : {}), body: n.body ?? "" },88 ...(badge === null ? {} : { badge }),89 ...(n.sound === false ? {} : { sound: "default" }),90 ...(item.mailboxId && item.threadId ? { "thread-id": `${item.mailboxId}:${item.threadId}` } : {}),91 category: n.category ?? (item.kind === "new" ? "MAIL_NEW" : item.kind === "snooze" || item.kind === "reminder" ? "MAIL_REMINDER" : "MAIL_ALERT"),92 "mutable-content": 1,93 "interruption-level": n.timeSensitive ? "time-sensitive" : "active",94 }95 return { aps, ...(item.mailboxId ? { mb: item.mailboxId } : {}), ...(item.emailId ? { email: item.emailId } : {}), ...(item.threadId ? { thread: item.threadId } : {}), kind: item.kind }96}97export const isSilent = (item: PushItem) => item.kind === "badge" || !!item.notice.silent98/** En-têtes APNs : sujet = identifiant de l'app ; une alerte part en priorité 10, une mise à jour silencieuse en priorité 5. */99export function buildHeaders(item: PushItem, bundleId: string, now: Date = new Date()): Record<string, string> {100 const silent = isSilent(item)101 const collapse = silent ? "badge" : crypto.createHash("sha256").update(item.dedupKey ?? `${item.kind}:${item.mailboxId ?? ""}:${item.emailId ?? ""}`).digest("hex").slice(0, 40)102 return {103 "apns-topic": bundleId,104 "apns-push-type": silent ? "background" : "alert",105 "apns-priority": silent ? "5" : "10",106 "apns-collapse-id": collapse,107 "apns-expiration": String(Math.floor(now.getTime() / 1000) + (silent ? 3600 : 86400)),108 }109}110111// ------- classement des réponses112const DEAD_TOKEN = new Set(["BadDeviceToken", "DeviceTokenNotForTopic", "Unregistered"])113/** ok · retry (429, 5xx, réseau, jeton fournisseur périmé) · drop-token (410, jeton d'appareil invalide) · fail (autre 4xx). */114export function classifyApns(status: number, reason = ""): ApnsOutcome {115 if (status === 200) return "ok"116 if (status === 410 || (status === 400 && DEAD_TOKEN.has(reason))) return "drop-token"117 if (status === 0 || status === 429 || status >= 500) return "retry"118 if (status === 403 && reason === "ExpiredProviderToken") return "retry"119 return "fail"120}121122// ------- jeton fournisseur (JWT ES256)123type KeyState = { key: crypto.KeyObject | null; error: string | null; at: number }124let keyState: KeyState | null = null125function loadKey(): KeyState {126 // Un fichier absent ou illisible est relu au plus une fois par minute ; une clé chargée est gardée.127 if (keyState && (keyState.key || Date.now() - keyState.at < 60_000)) return keyState128 let key: crypto.KeyObject | null = null, error: string | null = null129 if (!config.apnsKeyFile || !config.apnsKeyId || !config.apnsTeamId) error = "APNs is not configured (SPMAIL_APNS_KEY_FILE, SPMAIL_APNS_KEY_ID, SPMAIL_APNS_TEAM_ID)"130 else {131 try {132 const k = crypto.createPrivateKey(fs.readFileSync(config.apnsKeyFile, "utf8"))133 if (k.asymmetricKeyType !== "ec" || k.asymmetricKeyDetails?.namedCurve !== "prime256v1") error = "the APNs key is not a P-256 key"134 else key = k135 } catch {136 error = "the APNs key file cannot be read"137 }138 }139 keyState = { key, error, at: Date.now() }140 return keyState141}142/** Vrai si les trois réglages sont présents et la clé utilisable. Faux : rien n'est mis en file, rien n'est simulé. */143export const pushConfigured = (): boolean => loadKey().key !== null144export const pushConfigError = (): string | null => loadKey().error145146const b64u = (b: Buffer | string) => Buffer.from(b).toString("base64url")147/** Signe un jeton fournisseur (fonction pure, exportée pour les tests). */148export function signProviderToken(key: crypto.KeyObject, keyId: string, teamId: string, iat: number): string {149 const head = `${b64u(JSON.stringify({ alg: "ES256", kid: keyId }))}.${b64u(JSON.stringify({ iss: teamId, iat }))}`150 return `${head}.${b64u(crypto.sign("sha256", Buffer.from(head), { key, dsaEncoding: "ieee-p1363" }))}`151}152let cached: { token: string; at: number } | null = null153function providerToken(): string {154 const { key } = loadKey()155 if (!key) throw new Error("apns not configured")156 if (cached && Date.now() - cached.at < TOKEN_TTL_MS) return cached.token157 cached = { token: signProviderToken(key, config.apnsKeyId, config.apnsTeamId, Math.floor(Date.now() / 1000)), at: Date.now() }158 return cached.token159}160161// ------- HTTP/2 : une session persistante par hôte162export const apnsOrigin = (environment: "production" | "sandbox") => config.apnsHostOverride || `https://${APNS_HOSTS[environment]}`163const sessions = new Map<string, http2.ClientHttp2Session>()164function sessionFor(origin: string): http2.ClientHttp2Session {165 const s = sessions.get(origin)166 if (s && !s.closed && !s.destroyed) return s167 const n = http2.connect(origin)168 const forget = () => { if (sessions.get(origin) === n) sessions.delete(origin) }169 n.on("error", forget)170 n.on("close", forget)171 n.on("goaway", forget)172 n.unref() // une session inactive ne retient pas le processus à l'arrêt173 sessions.set(origin, n)174 return n175}176export function closeApns() {177 for (const s of sessions.values()) s.close()178 sessions.clear()179}180181/** Envoie une notification. Ne lève jamais : toute panne réseau est un résultat `retry` (status 0). */182export function sendApns(device: ApnsDevice, headers: Record<string, string>, payload: Record<string, unknown>): Promise<ApnsResult> {183 return new Promise((resolve) => {184 let settled = false185 const finish = (status: number, reason: string, apnsId: string | null = null) => {186 if (settled) return187 settled = true188 if (status === 403 && (reason === "ExpiredProviderToken" || reason === "InvalidProviderToken")) cached = null189 resolve({ outcome: classifyApns(status, reason), status, reason, apnsId })190 }191 try {192 const origin = apnsOrigin(device.environment)193 const req = sessionFor(origin).request({194 ":method": "POST", ":path": `/3/device/${device.apns_token}`, authorization: `bearer ${providerToken()}`, "content-type": "application/json", ...headers,195 })196 let status = 0, apnsId: string | null = null, body = ""197 req.setTimeout(REQUEST_TIMEOUT_MS, () => { req.close(http2.constants.NGHTTP2_CANCEL); finish(0, "timeout") })198 req.on("response", (h) => { status = Number(h[":status"] ?? 0); apnsId = typeof h["apns-id"] === "string" ? h["apns-id"] : null })199 req.on("data", (c: Buffer) => { if (body.length < 2000) body += c.toString("utf8") })200 req.on("end", () => {201 let reason = ""202 try { reason = String((JSON.parse(body) as { reason?: string }).reason ?? "") } catch { /* corps vide sur un succès */ }203 finish(status, reason.slice(0, 80), apnsId)204 })205 req.on("error", () => { sessions.delete(origin); finish(0, "network") })206 req.on("close", () => finish(0, "network")) // fermé sans réponse complète (connexion refusée ou coupée)207 req.end(JSON.stringify(payload))208 } catch {209 finish(0, "network")210 }211 })212}213