Repository Public
1// Commandes d'exploitation, lancées sur le nœud qui héberge SP Mail.2import { config } from "./config.js"3import { migrate, sql } from "./db.js"4import { dnsReport } from "./admin.js"5import { createAccount, getAll, listDomains, rotateSecret, seal, setAliases } from "./stalwart.js"6import { randomToken, sha256 } from "./util.js"7import { syncAddresses } from "./addresses.js"8import { createKey, SCOPES } from "./keys.js"910const [cmd, ...args] = process.argv.slice(2)11const flag = (name: string, d?: string) => {12 const i = args.indexOf(`--${name}`)13 return i >= 0 ? args[i + 1] : d14}15async function issue(purpose: "bootstrap" | "recover" | "invite", userId: string | null, ttl: number) {16 const token = randomToken(32)17 await sql`delete from enrollment_tokens where used_at is null and purpose = ${purpose} and user_id is not distinct from ${userId}`18 await sql`insert into enrollment_tokens (token_hash, purpose, user_id, expires_at) values (${sha256(token)}, ${purpose}, ${userId}, now() + make_interval(mins => ${ttl}))`19 await sql`insert into audit_log (action, target, meta) values (${"enroll.issue"}, ${userId}, ${sql.json({ purpose, ttl })})`20 return `${config.origin}/enroll#${token}`21}2223async function main() {24 await migrate()25 const ttl = Math.min(24 * 60, Math.max(1, Number(flag("ttl", "30"))))26 switch (cmd) {27 case "bootstrap": {28 // Création unique du premier administrateur ; refusée dès qu'il en existe un.29 const [{ n }] = await sql`select count(*)::int as n from users where role = 'admin' and status = 'active'`30 if (n > 0) throw new Error("An administrator already exists. Use: recover <handle>")31 console.log(`Lien administrateur à usage unique (valide ${ttl} min) :\n\n ${await issue("bootstrap", null, ttl)}\n`)32 break33 }34 case "recover": {35 // Appareil perdu : ajoute une nouvelle clé d'accès à un compte existant. Les sessions actives sont révoquées.36 const [u] = await sql`select id from users where handle = ${args[0] ?? ""}`37 if (!u) throw new Error("usage: recover <handle>")38 if (args.includes("--revoke-passkeys")) await sql`delete from passkeys where user_id = ${u.id}`39 await sql`update sessions set revoked_at = now() where user_id = ${u.id} and revoked_at is null`40 console.log(`Lien de récupération à usage unique (valide ${ttl} min) :\n\n ${await issue("recover", u.id, ttl)}\n`)41 break42 }43 case "invite": {44 console.log(`Lien d'invitation à usage unique (valide ${ttl} min) :\n\n ${await issue("invite", null, ttl)}\n`)45 break46 }47 case "mailbox-add": {48 // mailbox-add <adresse> <handle> [--name "Nom affiché"] : crée (ou adopte avec --adopt) le compte Stalwart et le rattache.49 const [address, handle] = args50 const [u] = await sql`select id from users where handle = ${handle ?? ""}`51 if (!address || !u) throw new Error('usage: mailbox-add <address> <handle> [--name "…"] [--adopt]')52 const name = flag("name", "")!53 let id: string, secret: string54 if (args.includes("--adopt")) {55 const acct = (await getAll("Account", ["emailAddress"])).find((x) => x.emailAddress === address.toLowerCase())56 if (!acct) throw new Error("no such account on the mail server")57 id = acct.id58 secret = await rotateSecret(id)59 } else ({ id, secret } = await createAccount(address, name || address))60 const [{ n }] = await sql`select count(*)::int as n from mailboxes where user_id = ${u.id}`61 await sql`insert into mailboxes (user_id, address, display_name, stalwart_id, secret_enc, position) values (${u.id}, ${address.toLowerCase()}, ${name}, ${id}, ${seal(secret)}, ${n})62 on conflict (address) do update set secret_enc = excluded.secret_enc, user_id = excluded.user_id`63 const [box] = await sql`select id from mailboxes where address = ${address.toLowerCase()}`64 await syncAddresses(box.id) // adresse de première classe + état de départ du veilleur de réception65 await sql`insert into audit_log (action, target) values ('mailbox.create-cli', ${address})`66 console.log(`boîte ${address} rattachée à ${handle}`)67 break68 }69 case "aliases-set": {70 // aliases-set <boîte> <alias1,alias2,…> : remplace la liste d'alias de la boîte (les adresses reçoivent dans cette boîte).71 const [box, list] = args72 const [mb] = await sql`select stalwart_id from mailboxes where address = ${(box ?? "").toLowerCase()}`73 if (!mb || list === undefined) throw new Error("usage: aliases-set <mailbox> <alias1,alias2,…>")74 const aliases = list.split(",").map((a) => a.trim().toLowerCase()).filter(Boolean)75 await setAliases(mb.stalwart_id, aliases)76 await sql`insert into audit_log (action, target, meta) values ('mailbox.aliases-cli', ${box}, ${sql.json({ aliases })})`77 console.log(`${box} ← ${aliases.join(", ") || "(aucun alias)"}`)78 break79 }80 case "status": {81 console.table(await sql`select u.handle, u.role, u.status, (select count(*)::int from passkeys p where p.user_id = u.id) as passkeys,82 (select string_agg(address, ', ') from mailboxes m where m.user_id = u.id) as mailboxes from users u order by u.created_at`)83 break84 }85 case "dns": {86 for (const d of await listDomains()) console.log(JSON.stringify(await dnsReport(d.name), null, 1))87 break88 }89 case "revoke-sessions": {90 const r = await sql`update sessions set revoked_at = now() where revoked_at is null and user_id = (select id from users where handle = ${args[0] ?? ""}) returning 1`91 console.log(`${r.length} session(s) révoquée(s)`)92 break93 }94 case "dev-token": {95 // Développement seulement : émet un jeton de session native pour tester les apps contre une pile locale.96 if (config.secureCookies) throw new Error("dev-token is refused on an https origin")97 const [u] = await sql`select id from users where handle = ${args[0] ?? ""}`98 if (!u) throw new Error("usage: dev-token <handle>")99 const token = randomToken(32)100 await sql`insert into sessions (token_hash, user_id, kind, device_name, platform, expires_at) values (${sha256(token)}, ${u.id}, 'native', 'dev-token', 'dev', now() + interval '30 days')`101 console.log(token)102 break103 }104 case "addresses-sync": {105 // Reprise idempotente : une adresse par boîte, une par alias Stalwart. N'écrit rien dans Stalwart, ne supprime rien.106 const r = await syncAddresses()107 await sql`insert into audit_log (action, meta) values ('addresses.sync-cli', ${sql.json({ created: r.created.length } as never)})`108 console.log(`${r.mailboxes} boîte(s) examinée(s) ; ${r.created.length} adresse(s) ajoutée(s)${r.created.length ? ` : ${r.created.join(", ")}` : ""}`)109 console.log(`adresses protégées : ${r.protected.join(", ") || "(aucune nouvelle)"}`)110 const [{ n }] = await sql`select count(*)::int as n from addresses`111 console.log(`total : ${n} adresse(s)`)112 break113 }114 case "key-create": {115 // key-create <nom> --scopes a,b --addresses x@d,y@d [--all-addresses] [--external allow|approval|deny] [--rate N] [--daily N] [--expires ISO] [--description "…"]116 const name = args[0]117 const scopes = (flag("scopes", "") ?? "").split(",").map((x) => x.trim()).filter(Boolean)118 const emails = (flag("addresses", "") ?? "").split(",").map((x) => x.trim().toLowerCase()).filter(Boolean)119 if (!name || name.startsWith("--") || !scopes.length) throw new Error(`usage: key-create <name> --scopes ${SCOPES.slice(0, 2).join(",")},… --addresses a@d,b@d [--all-addresses] [--external allow|approval|deny] [--rate N] [--daily N] [--expires ISO]`)120 const rows = emails.length ? await sql`select id, address from addresses where address = any(${emails})` : []121 const missing = emails.filter((e) => !rows.some((r) => r.address === e))122 if (missing.length) throw new Error(`unknown address(es): ${missing.join(", ")} (run addresses-sync first)`)123 const ext = flag("external", "approval") as "allow" | "approval" | "deny"124 if (!["allow", "approval", "deny"].includes(ext)) throw new Error("--external must be allow, approval or deny")125 const [owner] = await sql`select id from users where role = 'admin' and status = 'active' order by created_at limit 1`126 const { row, token } = await createKey({127 name, description: flag("description", "") ?? "", scopes, address_ids: rows.map((r) => r.id), all_addresses: args.includes("--all-addresses"),128 rate_per_minute: Number(flag("rate", "60")), daily_send_limit: Number(flag("daily", "200")), external_send_policy: ext, expires_at: flag("expires") ?? null,129 }, owner?.id ?? null)130 await sql`insert into audit_log (action, target, meta) values ('apikey.create-cli', ${row.id}, ${sql.json({ name, scopes, addresses: emails.length } as never)})`131 console.log(`clé ${row.id} (« ${name} ») créée — jeton affiché UNE SEULE fois :\n\n ${token}\n`)132 break133 }134 case "template-import": {135 // template-import <handle> <fichier.json> [--replace] : ajoute un modèle à la bibliothèque d'un utilisateur (assaini comme à l'enregistrement).136 // Avec --replace, un modèle actif du même nom reçoit une nouvelle version au lieu d'un doublon.137 const [handle, file] = args138 const [u] = await sql`select id from users where handle = ${handle ?? ""}`139 if (!u || !file) throw new Error("usage: template-import <handle> <file.json> [--replace]")140 const { saveNew, zTemplateContent } = await import("./templates.js")141 const raw = JSON.parse((await import("node:fs")).readFileSync(file, "utf8"))142 const c = zTemplateContent.parse({ name: raw.name, category: raw.category, subject: raw.subject, preheader: raw.preheader, html: raw.html, text: raw.text, variables: raw.variables, brand: raw.brand ?? {} })143 if (args.includes("--replace")) await sql`update templates set archived_at = now() where user_id = ${u.id} and name = ${c.name} and archived_at is null`144 const row = await saveNew(u.id, c, { source: raw.design_notes ? "ai" : "manual", ai_model: raw.ai_model, design_notes: raw.design_notes })145 await sql`insert into audit_log (action, target) values ('template.import-cli', ${row.id})`146 console.log(`modèle ${row.id} (« ${row.name} ») importé pour ${handle}`)147 break148 }149 case "key-revoke": {150 // key-revoke <id | préfixe spm_xxxxxxxxxx> : révocation immédiate.151 const ref = (args[0] ?? "").replace(/^spm_/, "").split("_")[0]152 if (!ref) throw new Error("usage: key-revoke <key id | spm_prefix>")153 const isUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(args[0] ?? "")154 const r = isUuid ? await sql`update api_keys set revoked_at = now(), updated_at = now() where id = ${args[0]} returning id, name`155 : await sql`update api_keys set revoked_at = now(), updated_at = now() where prefix = ${ref} returning id, name`156 if (!r.length) throw new Error("no such key")157 await sql`delete from explorer_tokens where key_id = ${r[0].id}`158 await sql`insert into audit_log (action, target) values ('apikey.revoke-cli', ${r[0].id})`159 console.log(`clé ${r[0].id} (« ${r[0].name} ») révoquée`)160 break161 }162 case "migrate":163 console.log("migrations à jour")164 break165 default:166 console.log("usage: cli <bootstrap | recover <handle> [--revoke-passkeys] | invite | mailbox-add <address> <handle> [--name …] [--adopt] | status | dns | revoke-sessions <handle> | addresses-sync | key-create <name> --scopes … --addresses … | key-revoke <id|prefix> | migrate> [--ttl min]")167 }168 await sql.end()169}170main().catch(async (e) => {171 console.error(String(e.message ?? e))172 await sql.end()173 process.exit(1)174})175