Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Storage Node8 * File : server/src/admin.ts9 * Description : Admin API (/admin/v1, bearer token): overview for the10 * dashboard, pairing codes, node actions, objects, events.11 * Module : server12 * Repository : https://git.spboucher.ai/maclustr-storage-ios13 * Project Website : https://storage.spboucher.ai14 * Created : 2026-12-0115 * Last Modified : 2026-12-0116 *17 * Author : Simon-Pierre Boucher18 * Position : Professor of Finance19 * Institution : Université du Québec en Outaouais (UQO)20 * Organization : SP Boucher21 * Website : https://spboucher.ai22 * Git : https://git.spboucher.ai23 *24 * Preferred Contact: admin@spboucher.ai25 * Technical Contact: dev@spboucher.ai26 * Security/Admin : admin@spboucher.ai27 *28 * Copyright (c) 202629 * Simon-Pierre Boucher30 * All rights reserved where applicable. This file is governed by the31 * applicable project license, copyright notices and relevant law.32 * Existing third-party rights and notices remain unaffected.33 *34 * License : None specified (no license file in this repository)35 *36 * Do not embed credentials, private keys, access tokens,37 * certificates or confidential personal information.38 *39 * =============================================================================40 * END OF SP BOUCHER SOURCE HEADER41 * =============================================================================42 */4344import { createHash, timingSafeEqual } from "node:crypto";45import { config, PROTOCOL, VERSION } from "./config.ts";46import { q, q1, run, now, event } from "./db.ts";47import { normalizeCode, pairingCode, sha256hex } from "./crypto.ts";48import { availability, drainStatus, isOnline, purgeFragments, requestRetrieve, requestVerify, revoke, startDrain, type Device } from "./coordinator.ts";49import { deleteObject, diskFree, ingestObject, readObject, stableExists } from "./store.ts";50import { HttpError, json, readBody, type Ctx } from "./msp.ts";5152const started = now();53const failures = new Map<string, { n: number; reset: number }>();5455function authorize(ctx: Ctx) {56 const f = failures.get(ctx.ip);57 if (f && f.reset > Date.now() && f.n >= 20) throw new HttpError(429, "too_many_attempts");58 const m = /^Bearer ([a-f0-9]{64})$/.exec(String(ctx.req.headers.authorization ?? ""));59 const ok = !!m && timingSafeEqual(createHash("sha256").update(m[1]).digest(), ctx.secrets.adminTokenHash);60 if (!ok) {61 const e = f && f.reset > Date.now() ? f : { n: 0, reset: Date.now() + 600_000 };62 e.n++; failures.set(ctx.ip, e);63 throw new HttpError(401, "unauthorized");64 }65}6667function nodeView(d: Device) {68 let rep: any = {}; try { rep = JSON.parse(d.reported); } catch { /* empty */ }69 const stored = q1<{ n: number; b: number }>("SELECT COUNT(*) n, COALESCE(SUM(size),0) b FROM placements WHERE device_id=? AND state='stored'", d.id)!;70 const assigned = q1<{ n: number; b: number }>("SELECT COUNT(*) n, COALESCE(SUM(size),0) b FROM placements WHERE device_id=? AND state='assigned'", d.id)!;71 const online = isOnline(d) && !["revoked", "removed"].includes(d.status);72 const quota = d.quota_bytes;73 const writable = Number(rep?.capacity?.writable ?? 0);74 // What the cluster can really still put on the node now: bounded by the quota AND by what the device says it can write.75 const available = online && d.status === "active" && d.accepting ? Math.max(0, Math.min(quota - stored.b - assigned.b, writable)) : 0;76 const checks = d.verify_ok + d.verify_fail;77 const health = ["revoked", "removed"].includes(d.status) ? d.status78 : !online ? "offline"79 : d.verify_fail > 0 && d.verify_fail / checks > 0.02 ? "degraded"80 : rep?.thermal === "serious" || rep?.thermal === "critical" ? "hot"81 : d.status !== "active" ? d.status82 : d.accepting ? "healthy" : "paused";83 return {84 id: d.id, name: d.name, model: d.model, os_version: d.os_version, app_version: d.app_version, status: d.status, online, health,85 accepting: !!d.accepting, accepting_reason: d.accepting_reason, paired_at: d.paired_at, last_seen: d.last_seen, last_via: d.last_via,86 capacity: { allocated: quota, used: stored.b, pending: assigned.b, available, device_total: rep?.capacity?.total ?? null, device_free: rep?.capacity?.free ?? null, device_reserve: rep?.capacity?.reserve ?? null, device_reported_used: rep?.capacity?.used ?? null },87 fragments: stored.n, fragments_pending: assigned.n,88 rates: rep?.rates ?? null, power: rep?.power ?? null, thermal: rep?.thermal || null, network: rep?.network || null, mode: rep?.mode || null, policy: rep?.policy ?? null,89 transferred: { to_device: d.rx_bytes, from_device: d.tx_bytes },90 integrity: { ok: d.verify_ok, failed: d.verify_fail, rate: checks ? d.verify_ok / checks : null },91 availability: { h24: availability(d.id, d.paired_at, 1440), d7: availability(d.id, d.paired_at, 7 * 1440) },92 drain: d.status === "draining" ? drainStatus(d.id) : null, key_rotated_at: d.key_rotated_at,93 bench: d.bench ? JSON.parse(d.bench) : null,94 };95}9697export function overview() {98 const devices = q<Device>("SELECT * FROM devices WHERE status NOT IN ('removed') ORDER BY paired_at").map(nodeView);99 const live = devices.filter(d => d.status !== "revoked");100 const sum = (xs: number[]) => xs.reduce((a, b) => a + b, 0);101 const frag = q1<{ n: number; b: number }>("SELECT COUNT(*) n, COALESCE(SUM(size),0) b FROM fragments WHERE refs>0")!;102 const bad = q1<{ n: number }>("SELECT COUNT(*) n FROM fragments WHERE refs>0 AND stable_state!='ok'")!.n;103 const covered = q1<{ n: number; b: number }>("SELECT COUNT(*) n, COALESCE(SUM(size),0) b FROM fragments f WHERE refs>0 AND EXISTS (SELECT 1 FROM placements p WHERE p.fragment_id=f.id AND p.state='stored')")!;104 // Fragments whose stable copy is unusable right now while a mobile node still holds them (being repaired). Must stay 0 at rest.105 const mobileOnly = q1<{ n: number }>("SELECT COUNT(*) n FROM fragments f WHERE refs>0 AND stable_state!='ok' AND EXISTS (SELECT 1 FROM placements p WHERE p.fragment_id=f.id AND p.state='stored')")!.n;106 const obj = q1<{ n: number; b: number }>("SELECT COUNT(*) n, COALESCE(SUM(size),0) b FROM objects")!;107 const ok = sum(live.map(d => d.integrity.ok)), failed = sum(live.map(d => d.integrity.failed));108 const av = live.map(d => d.availability.h24).filter((x): x is number => x !== null);109 const disk = diskFree();110 return {111 coordinator: { version: VERSION, protocol: PROTOCOL, host: config.publicHost, uptime_seconds: now() - started, fragment_size: config.fragmentSize, mobile_replicas_target: config.mobileReplicas, server_time: now(), storage_class: "mobile_opportunistic" },112 totals: {113 nodes: live.length, nodes_online: live.filter(d => d.online).length,114 capacity_registered: sum(live.map(d => d.capacity.allocated)), // quotas chosen on the devices115 capacity_accessible: sum(live.filter(d => d.online).map(d => d.capacity.allocated)), // quotas of nodes reachable now116 capacity_offline: sum(live.filter(d => !d.online).map(d => d.capacity.allocated)),117 capacity_available_now: sum(live.map(d => d.capacity.available)), // what could be written right now118 used: sum(live.map(d => d.capacity.used)),119 redundant_bytes: covered.b, redundant_fragments: covered.n, // distinct stable fragments that also live on ≥1 mobile node120 fragments_on_mobile: sum(live.map(d => d.fragments)),121 transferred_to_devices: sum(devices.map(d => d.transferred.to_device)), transferred_from_devices: sum(devices.map(d => d.transferred.from_device)),122 availability_24h: av.length ? sum(av) / av.length : null,123 integrity_rate: ok + failed ? ok / (ok + failed) : null, integrity_checks: ok + failed,124 },125 stable: { objects: obj.n, object_bytes: obj.b, fragments: frag.n, fragment_bytes: frag.b, fragments_unhealthy: bad, fragments_only_on_mobile: mobileOnly, disk_free: disk.free, disk_total: disk.total },126 nodes: devices,127 };128}129130function device(id: string): Device {131 const d = q1<Device>("SELECT * FROM devices WHERE id=? OR name=?", id, id);132 if (!d) throw new HttpError(404, "node_not_found");133 return d;134}135136export async function handleAdmin(ctx: Ctx): Promise<boolean> {137 const { req, res, url } = ctx;138 if (!url.pathname.startsWith("/admin/v1/")) return false;139 authorize(ctx);140 const route = url.pathname.slice(10);141 const method = req.method ?? "GET";142 const body = async () => { const b = await readBody(req, 64 * 1024); try { return JSON.parse(b.toString("utf8") || "{}"); } catch { throw new HttpError(400, "invalid_json"); } };143 let m: RegExpExecArray | null;144145 if (route === "overview" && method === "GET") { json(res, 200, overview()); return true; }146147 if (route === "pairing" && method === "POST") {148 const b = await body();149 const ttl = Math.max(60, Math.min(Number(b.ttl_seconds) || config.pairingTtlSeconds, 3600));150 const code = pairingCode(); const t = now();151 run("INSERT INTO pairing_codes (code_hash,label,created_at,expires_at) VALUES (?,?,?,?)", sha256hex(normalizeCode(code)), String(b.label ?? "").slice(0, 80), t, t + ttl);152 event("pairing.created", null, { label: String(b.label ?? "").slice(0, 80), ttl });153 json(res, 201, { code, expires_at: t + ttl, ttl_seconds: ttl, qr_payload: `msp1://pair?h=${config.publicHost}&c=${code}`, id: sha256hex(normalizeCode(code)).slice(0, 16) });154 return true;155 }156 if (route === "pairing" && method === "GET") {157 json(res, 200, { codes: q<any>("SELECT substr(code_hash,1,16) id, label, created_at, expires_at, used_at, device_id, revoked_at FROM pairing_codes ORDER BY created_at DESC LIMIT 50")158 .map(c => ({ ...c, state: c.used_at ? "used" : c.revoked_at ? "revoked" : c.expires_at < now() ? "expired" : "pending" })) });159 return true;160 }161 if ((m = /^pairing\/([a-f0-9]{16})$/.exec(route)) && method === "DELETE") {162 const r = run("UPDATE pairing_codes SET revoked_at=? WHERE substr(code_hash,1,16)=? AND used_at IS NULL AND revoked_at IS NULL", now(), m[1]);163 json(res, 200, { revoked: r.changes === 1 }); return true;164 }165166 if ((m = /^nodes\/([^/]+)$/.exec(route)) && method === "GET") {167 const d = device(decodeURIComponent(m[1]));168 json(res, 200, { node: nodeView(d),169 events: q("SELECT ts, kind, detail FROM events WHERE device_id=? ORDER BY id DESC LIMIT 100", d.id).map((e: any) => ({ ...e, detail: JSON.parse(e.detail) })),170 transfers: q("SELECT ts, fragment_id, direction, bytes, ms, ok, via, resumed_from FROM transfers WHERE device_id=? ORDER BY id DESC LIMIT 100", d.id),171 tasks: q("SELECT id, op, fragment_id, size, state, attempts, reason, error, created_at, updated_at FROM tasks WHERE device_id=? ORDER BY created_at DESC LIMIT 100", d.id) });172 return true;173 }174 if ((m = /^nodes\/([^/]+)$/.exec(route)) && method === "DELETE") {175 // Forgets a node that no longer takes part (revoked or drained): it leaves the list; its history stays in the journal.176 const d = device(decodeURIComponent(m[1]));177 if (!["revoked", "drained"].includes(d.status)) throw new HttpError(409, "node_still_in_service", "revoke or drain the node first");178 run("DELETE FROM placements WHERE device_id=?", d.id);179 run("UPDATE devices SET status='removed', accepting=0 WHERE id=?", d.id);180 event("node.forgotten", d.id, { by: "admin" });181 json(res, 200, { removed: true }); return true;182 }183 if ((m = /^nodes\/([^/]+)\/(revoke|suspend|resume|drain|verify|retrieve)$/.exec(route)) && method === "POST") {184 const d = device(decodeURIComponent(m[1])); const b = await body();185 const action = m[2];186 if (action === "revoke") revoke(d, "admin");187 else if (action === "suspend") { if (d.status !== "active") throw new HttpError(409, "not_active"); run("UPDATE devices SET status='suspended' WHERE id=?", d.id); event("node.suspended", d.id, { by: "admin" }); }188 else if (action === "resume") { if (!["suspended", "drained", "draining"].includes(d.status)) throw new HttpError(409, "not_suspended"); run("UPDATE devices SET status='active', drain_mode=NULL WHERE id=?", d.id); event("node.resumed", d.id, { by: "admin" }); }189 else if (action === "drain") { if (!["active", "suspended"].includes(d.status)) throw new HttpError(409, "not_active"); startDrain(d, "graceful", b.remove === true, "admin"); }190 else if (action === "verify") { json(res, 200, { queued: requestVerify(d) }); return true; }191 else if (action === "retrieve") {192 const ids: string[] = Array.isArray(b.fragments) ? b.fragments : q<{ fragment_id: string }>("SELECT fragment_id FROM placements WHERE device_id=? AND state='stored' LIMIT ?", d.id, Math.min(Number(b.count) || 1, 64)).map(r => r.fragment_id);193 json(res, 200, { tasks: ids.map(id => ({ fragment: id, task: requestRetrieve(d, id, "requested") })) }); return true;194 }195 json(res, 200, { node: nodeView(device(d.id)) });196 return true;197 }198199 if (route === "objects" && method === "PUT") {200 const name = (url.searchParams.get("name") ?? "").slice(0, 200) || "unnamed";201 const klass = (url.searchParams.get("class") ?? "archive").slice(0, 40);202 const o = await ingestObject(ctx.secrets, req, name, klass);203 json(res, 201, o); return true;204 }205 if (route === "objects" && method === "GET") {206 json(res, 200, { objects: q<any>("SELECT * FROM objects ORDER BY created_at DESC LIMIT 500").map(o => ({ ...o,207 mobile: q1<any>(`SELECT COUNT(DISTINCT p.fragment_id) covered, COUNT(*) copies FROM placements p JOIN object_fragments of ON of.fragment_id=p.fragment_id WHERE of.object_id=? AND p.state='stored'`, o.id) })) });208 return true;209 }210 if ((m = /^objects\/([a-f0-9]{24})$/.exec(route)) && method === "GET") {211 const o = q1<any>("SELECT * FROM objects WHERE id=?", m[1]);212 if (!o) throw new HttpError(404, "object_not_found");213 const parts = q<any>("SELECT of.idx, of.fragment_id, of.plain_size, f.size, f.stable_state FROM object_fragments of JOIN fragments f ON f.id=of.fragment_id WHERE of.object_id=? ORDER BY of.idx", o.id)214 .map(p => ({ ...p, stable_present: stableExists(p.fragment_id, p.size), mobile: q<any>("SELECT p.device_id, d.name, p.state, p.verified_at FROM placements p JOIN devices d ON d.id=p.device_id WHERE p.fragment_id=?", p.fragment_id) }));215 json(res, 200, { object: o, fragments: parts }); return true;216 }217 if ((m = /^objects\/([a-f0-9]{24})\/content$/.exec(route)) && method === "GET") {218 const o = q1<any>("SELECT * FROM objects WHERE id=?", m[1]);219 if (!o) throw new HttpError(404, "object_not_found");220 const missing = q<{ fragment_id: string; size: number }>("SELECT of.fragment_id, f.size FROM object_fragments of JOIN fragments f ON f.id=of.fragment_id WHERE of.object_id=?", o.id).filter(p => !stableExists(p.fragment_id, p.size));221 if (missing.length) {222 for (const p of missing) run("UPDATE fragments SET stable_state='missing' WHERE id=?", p.fragment_id);223 json(res, 503, { error: "stable_copy_unavailable", fragments: missing.map(p => p.fragment_id), detail: "recovery from mobile nodes is scheduled; retry when the fragments are restored" }); return true;224 }225 res.writeHead(200, { "Content-Type": "application/octet-stream", "Content-Length": o.size, "X-Object-SHA256": o.sha256, "Content-Disposition": `attachment; filename="${encodeURIComponent(o.name)}"` });226 try { const r = await readObject(ctx.secrets, o.id, res); if (!r.ok) res.destroy(); else res.end(); } catch (e) { event("object.read_failed", null, { object: o.id, error: String(e) }); res.destroy(); }227 return true;228 }229 if ((m = /^objects\/([a-f0-9]{24})$/.exec(route)) && method === "DELETE") {230 const r = deleteObject(m[1]); purgeFragments(r.released);231 json(res, 200, { deleted: true, fragments_released: r.released.length }); return true;232 }233 if (route === "events" && method === "GET") {234 const limit = Math.min(Number(url.searchParams.get("limit")) || 100, 1000);235 json(res, 200, { events: q<any>("SELECT e.id, e.ts, e.device_id, d.name device_name, e.kind, e.detail FROM events e LEFT JOIN devices d ON d.id=e.device_id ORDER BY e.id DESC LIMIT ?", limit).map(e => ({ ...e, detail: JSON.parse(e.detail) })) });236 return true;237 }238 if (route === "transfers" && method === "GET") {239 const limit = Math.min(Number(url.searchParams.get("limit")) || 100, 1000);240 json(res, 200, { transfers: q("SELECT t.ts, t.device_id, d.name device_name, t.fragment_id, t.direction, t.bytes, t.ms, t.ok, t.via, t.resumed_from FROM transfers t LEFT JOIN devices d ON d.id=t.device_id ORDER BY t.id DESC LIMIT ?", limit) });241 return true;242 }243 throw new HttpError(404, "not_found");244}245