Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Storage Node8 * File : server/src/main.ts9 * Description : Entry point: gateway listener (HTTP behind the MacLustr10 * Tunnel), LAN listener (HTTPS, pinned certificate),11 * Bonjour, scheduler.12 * Module : server13 * Repository : https://git.spboucher.ai/maclustr-storage-ios14 * Project Website : https://storage.spboucher.ai15 * Created : 2026-12-0116 * Last Modified : 2026-12-0117 *18 * Author : Simon-Pierre Boucher19 * Position : Professor of Finance20 * Institution : Université du Québec en Outaouais (UQO)21 * Organization : SP Boucher22 * Website : https://spboucher.ai23 * Git : https://git.spboucher.ai24 *25 * Preferred Contact: admin@spboucher.ai26 * Technical Contact: dev@spboucher.ai27 * Security/Admin : admin@spboucher.ai28 *29 * Copyright (c) 202630 * Simon-Pierre Boucher31 * All rights reserved where applicable. This file is governed by the32 * applicable project license, copyright notices and relevant law.33 * Existing third-party rights and notices remain unaffected.34 *35 * License : None specified (no license file in this repository)36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445import { createServer, type IncomingMessage, type ServerResponse } from "node:http";46import { createServer as createTlsServer } from "node:https";47import { readFileSync } from "node:fs";48import { spawn, type ChildProcess } from "node:child_process";49import { config, loadSecrets, PROTOCOL, VERSION } from "./config.ts";50import { db, now, event, q1 } from "./db.ts";51import { tick } from "./coordinator.ts";52import { handleMsp, HttpError, json, type Ctx } from "./msp.ts";53import { handleAdmin } from "./admin.ts";5455const secrets = loadSecrets();5657function clientIp(req: IncomingMessage): string {58 const peer = (req.socket.remoteAddress ?? "").replace(/^::ffff:/, "");59 const fwd = String(req.headers["x-forwarded-for"] ?? "").split(",")[0].trim();60 return fwd && config.trustProxy.includes(peer) ? fwd : peer;61}6263function handler(via: "gateway" | "lan") {64 return async (req: IncomingMessage, res: ServerResponse) => {65 const url = new URL(req.url ?? "/", "http://x");66 const ctx: Ctx = { req, res, url, ip: clientIp(req), via, secrets };67 try {68 if (url.pathname === "/healthz") {69 const d = q1<{ n: number }>("SELECT COUNT(*) n FROM devices")!;70 return json(res, 200, { ok: true, service: "maclustr-storage-coordinator", version: VERSION, protocol: PROTOCOL, devices: d.n, time: now() });71 }72 if (await handleMsp(ctx)) return;73 if (via === "gateway" && await handleAdmin(ctx)) return; // the admin API is never served on the LAN listener74 if (url.pathname === "/" && req.method === "GET") {75 res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });76 return res.end("MacLustr Distributed Storage Fabric — Mobile Extension\nStorage gateway (MSP/1). Nothing to browse here.\n");77 }78 throw new HttpError(404, "not_found");79 } catch (e: any) {80 if (res.headersSent) { res.destroy(); return; }81 const status = e instanceof HttpError ? e.status : Number(e?.status) || 500;82 if (status >= 500) console.error(`[error] ${req.method} ${url.pathname}:`, e?.stack ?? e);83 if (!req.complete) req.resume();84 json(res, status, { error: e instanceof HttpError ? e.code : status >= 500 ? "internal_error" : String(e?.message ?? "error"), message: status >= 500 ? undefined : e?.message });85 }86 };87}8889const gateway = createServer(handler("gateway"));90gateway.requestTimeout = 0; gateway.headersTimeout = 30_000; gateway.keepAliveTimeout = 65_000;91gateway.listen(config.port, config.host, () => console.log(`[coordinator] ${VERSION} ${PROTOCOL} gateway listener ${config.host}:${config.port}`));9293let bonjour: ChildProcess | null = null;94let lan: ReturnType<typeof createTlsServer> | null = null;95if (config.lanPort) {96 lan = createTlsServer({ key: readFileSync(secrets.lanKeyPath), cert: readFileSync(secrets.lanCertPath), minVersion: "TLSv1.3" }, handler("lan"));97 lan.requestTimeout = 0;98 lan.listen(config.lanPort, "0.0.0.0", () => console.log(`[coordinator] LAN listener 0.0.0.0:${config.lanPort} (certificate pin ${secrets.lanPin.slice(0, 16)}…)`));99 if (config.bonjour) {100 // dns-sd is Apple's own binary: it registers the service without needing the Local Network permission third-party binaries need.101 const start = () => {102 bonjour = spawn("/usr/bin/dns-sd", ["-R", "MacLustr Storage", "_maclustr-msp._tcp", "local", String(config.lanPort), "v=1", `pin=${secrets.lanPin.slice(0, 16)}`], { stdio: "ignore" });103 bonjour.on("exit", () => { bonjour = null; if (!stopping) setTimeout(start, 5000); });104 bonjour.on("error", () => { /* dns-sd absent (Linux): LAN discovery is simply unavailable */ });105 };106 start();107 }108}109110let stopping = false;111const timer = setInterval(() => { try { tick(); } catch (e) { console.error("[tick]", e); } }, config.tickMs);112event("coordinator.started", null, { version: VERSION });113114function shutdown() {115 if (stopping) return; stopping = true;116 clearInterval(timer);117 bonjour?.kill();118 gateway.close(); lan?.close();119 gateway.closeAllConnections(); lan?.closeAllConnections();120 try { db.exec("PRAGMA wal_checkpoint(TRUNCATE)"); db.close(); } catch { /* closing anyway */ }121 process.exit(0);122}123process.on("SIGINT", shutdown); process.on("SIGTERM", shutdown);124