SPB Git

Repository Public

api.ts 41.9 KB 746 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Vision8 * File             : server/src/api.ts9 * Module           : server10 * Repository       : https://git.spboucher.ai/maclustr-vision11 * Project Website  : https://camera.spboucher.ai12 * Created          : 2026-11-3013 * Last Modified    : 2026-11-3014 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// vision-api : API privée + interface web. Toute route privée (JSON, images, vidéo, HLS, WebSocket,43// exports) est autorisée côté serveur par la session ; il n'existe aucun lien public permanent.44import fs from 'node:fs';45import http from 'node:http';46import os from 'node:os';47import path from 'node:path';48import type { Duplex } from 'node:stream';49import { checkKey, clearCookie, consumeEnrollToken, COOKIE, createSession, findSession, hasActiveKey, listSessions, loadServerSecret, LoginLimiter, revokeSession, rotateKey, sessionCookie, type Session } from './auth.ts';50import { listCameras, loadRegistry, syncCameras, validateSchedule, type Camera } from './cameras.ts';51import { coverage } from './catalog.ts';52import { ensureDirs, gitCommit, loadConfig, resolveListen, type Config } from './config.ts';53import { addEvent, audit, getSetting, openAndMigrate, setSetting, type DB } from './db.ts';54import { applySecurity, HttpError, intParam, mimeFor, parseCookies, readJson, sendJson, serveFile } from './httpx.ts';55import { closeAllSockets, closeSessionSockets, hlsFile, hlsMaster, liveViewerCount, parseTarget, proxyWebSocket, snapshot } from './live.ts';56import { logger } from './log.ts';57import { coreCommand } from './control.ts';58import { motionImagePath } from './motion.ts';59import { Exporter, playbackFile, thumbnail } from './playback.ts';60import { apnsConfigured, sendPush } from './push.ts';61import { archiveBytes, pruneCache, retentionSettings } from './retention.ts';62import { dirSizeBytes, diskStats, verifyVolume } from './storage.ts';6364const log = logger('api');65const GB = 1024 ** 3;6667type Ctx = { req: http.IncomingMessage; res: http.ServerResponse; url: URL; ip: string; session: Session | null; params: Record<string, string> };68type Handler = (c: Ctx) => Promise<void> | void;69type Route = { method: string; re: RegExp; keys: string[]; handler: Handler; pub: boolean };7071export function createApp(cfg: Config, db: DB, registry = loadRegistry(cfg)) {72  const secret = loadServerSecret(cfg);73  const limiter = new LoginLimiter();74  const exporter = new Exporter(cfg, db);75  const origins = new Set([`https://${cfg.domain}`, ...cfg.extraOrigins]);76  const startedMs = Date.now();77  const routes: Route[] = [];78  const cameras = () => listCameras(db, registry);79  const camOr404 = (id: string): Camera => {80    const c = cameras().find((x) => x.id === id);81    if (!c) throw new HttpError(404, 'camera_not_found');82    return c;83  };8485  function route(method: string, pattern: string, handler: Handler, pub = false): void {86    const keys: string[] = [];87    const re = new RegExp('^' + pattern.replace(/:([a-zA-Z]+)/g, (_m, k) => (keys.push(k), '([A-Za-z0-9_.-]{1,200})')) + '$');88    routes.push({ method, re, keys, handler, pub });89  }9091  function clientIp(req: http.IncomingMessage): string {92    const remote = (req.socket.remoteAddress || '').replace(/^::ffff:/, '');93    if (cfg.trustedProxies.includes(remote)) {94      const xff = String(req.headers['x-forwarded-for'] || '').split(',').map((s) => s.trim()).filter(Boolean);95      if (xff.length) return xff[xff.length - 1].slice(0, 64);96    }97    return remote || 'unknown';98  }99100  function sessionOf(req: http.IncomingMessage): Session | null {101    return findSession(db, parseCookies(req.headers.cookie)[COOKIE]);102  }103104  /** Mutations : Origin exact + en-tête applicatif (défense CSRF en plus de SameSite=Strict). */105  function checkCsrf(req: http.IncomingMessage): void {106    const origin = String(req.headers.origin || '');107    if (!origins.has(origin)) throw new HttpError(403, 'bad_origin', 'origine refusée');108    if (req.headers['x-mlv'] !== '1') throw new HttpError(403, 'csrf', 'en-tête applicatif manquant');109  }110111  const camDto = (c: Camera) => {112    const st = db.prepare('SELECT * FROM camera_state WHERE camera_id = ?').get(c.id) as Record<string, any> | undefined;113    const now = Date.now();114    const lastEnd = st?.last_segment_end_ms || null;115    const caps = c.capabilities as any;116    return {117      id: c.id,118      name: c.name,119      model: c.model,120      firmware: c.firmware,121      capabilities: { ptz: !!caps.ptz, audio: !!caps.audio },122      profiles: (caps.profiles || []).slice(0, 2).map((p: any, i: number) => ({ role: i === 0 ? 'main' : 'sub', width: p.width, height: p.height, fps: p.fps, bitrateKbps: p.bitrateKbps })),123      settings: { recordEnabled: c.recordEnabled, recordAudio: c.recordAudio, liveAudio: c.liveAudio, ptzEnabled: c.ptzEnabled, schedule: c.schedule, motionEnabled: c.motionEnabled, motionSensitivity: c.motionSensitivity, motionCooldownS: c.motionCooldownS, motionIgnore: c.motionIgnore },124      status: {125        reachable: !!st?.reachable,126        reachableSinceMs: st?.reachable_since_ms || null,127        lastCheckMs: st?.last_check_ms || null,128        recorderState: st?.recorder_state || 'stopped',129        recorderRestarts: st?.recorder_restarts || 0,130        lastSegmentEndMs: lastEnd,131        // « REC » n'est affiché que si un segment valide a été archivé récemment132        recConfirmed: !!lastEnd && now - lastEnd < (cfg.recording.segmentSeconds * 2 + 45) * 1000 && st?.recorder_state === 'recording',133        bitrateBps: st?.last_bitrate_bps || null,134        lastError: st?.recorder_state === 'recording' ? null : st?.last_error || null,135        lastMotionMs: st?.last_motion_ms || null,136        motionState: st?.motion_state || 'stopped',137      },138    };139  };140141  // ───────────── Authentification ─────────────142  route('GET', '/api/health', (c) => sendJson(c.res, 200, { ok: true }), true);143144  route(145    'POST',146    '/api/auth/login',147    async (c) => {148      const wait = limiter.check(c.ip);149      if (wait > 0) throw new HttpError(429, 'rate_limited', 'trop de tentatives', { retryAfterS: Math.ceil(wait / 1000) });150      const body = await readJson(c.req, 2048);151      const ok = checkKey(db, secret, body.key);152      if (!ok) {153        limiter.fail(c.ip);154        audit(db, 'anonymous', c.ip, 'login_failed');155        await new Promise((r) => setTimeout(r, 350 + Math.random() * 250));156        throw new HttpError(401, 'invalid_key', 'clé refusée');157      }158      limiter.success(c.ip);159      const { token, session } = createSession(db, cfg, { ip: c.ip, userAgent: String(c.req.headers['user-agent'] || ''), trusted: body.trust === true });160      audit(db, session.id, c.ip, 'login');161      sendJson(c.res, 200, { ok: true, expiresMs: session.expiresMs, trusted: session.trusted }, { 'Set-Cookie': sessionCookie(token, (session.expiresMs - Date.now()) / 1000) });162    },163    true,164  );165166  // Activation par lien à usage unique : crée la clé d'accès (révoque l'ancienne et toutes les sessions),167  // ouvre la session de cet appareil et renvoie la clé une seule fois.168  route(169    'POST',170    '/api/auth/enroll',171    async (c) => {172      const wait = limiter.check(c.ip);173      if (wait > 0) throw new HttpError(429, 'rate_limited', 'trop de tentatives', { retryAfterS: Math.ceil(wait / 1000) });174      const body = await readJson(c.req, 2048);175      if (!consumeEnrollToken(db, body.token)) {176        limiter.fail(c.ip);177        audit(db, 'anonymous', c.ip, 'enroll_failed');178        await new Promise((r) => setTimeout(r, 350 + Math.random() * 250));179        throw new HttpError(401, 'invalid_link', 'lien invalide, expiré ou déjà utilisé');180      }181      const key = rotateKey(db, secret);182      closeAllSockets();183      const { token, session } = createSession(db, cfg, { ip: c.ip, userAgent: String(c.req.headers['user-agent'] || ''), trusted: body.trust !== false });184      audit(db, session.id, c.ip, 'enrolled');185      addEvent(db, { type: 'key_rotated', severity: 'warning', message: 'Clé d’accès créée par lien d’activation : les sessions précédentes ont été révoquées' });186      sendJson(c.res, 200, { key, expiresMs: session.expiresMs }, { 'Set-Cookie': sessionCookie(token, (session.expiresMs - Date.now()) / 1000) });187    },188    true,189  );190191  route(192    'GET',193    '/api/auth/session',194    (c) => {195      if (!c.session) return sendJson(c.res, 200, { authenticated: false, configured: hasActiveKey(db) });196      sendJson(c.res, 200, { authenticated: true, sessionId: c.session.id, expiresMs: c.session.expiresMs, trusted: c.session.trusted, timezone: cfg.timezone, version: cfg.version });197    },198    true,199  );200201  route('POST', '/api/auth/logout', (c) => {202    revokeSession(db, c.session!.id);203    closeSessionSockets(c.session!.id);204    audit(db, c.session!.id, c.ip, 'logout');205    sendJson(c.res, 200, { ok: true }, { 'Set-Cookie': clearCookie });206  });207208  route('GET', '/api/auth/sessions', (c) => {209    sendJson(c.res, 200, { sessions: listSessions(db).map((s) => ({ ...s, current: s.id === c.session!.id })) });210  });211212  route('DELETE', '/api/auth/sessions/:id', (c) => {213    const ok = revokeSession(db, c.params.id);214    if (!ok) throw new HttpError(404, 'session_not_found');215    closeSessionSockets(c.params.id);216    audit(db, c.session!.id, c.ip, 'session_revoked', { id: c.params.id });217    sendJson(c.res, 200, { ok: true }, c.params.id === c.session!.id ? { 'Set-Cookie': clearCookie } : {});218  });219220  route('POST', '/api/auth/rotate-key', async (c) => {221    const body = await readJson(c.req, 2048);222    const wait = limiter.check(c.ip);223    if (wait > 0) throw new HttpError(429, 'rate_limited', 'trop de tentatives', { retryAfterS: Math.ceil(wait / 1000) });224    if (!checkKey(db, secret, body.currentKey)) {225      limiter.fail(c.ip);226      throw new HttpError(401, 'invalid_key', 'clé actuelle refusée');227    }228    const key = rotateKey(db, secret);229    closeAllSockets();230    audit(db, c.session!.id, c.ip, 'key_rotated');231    addEvent(db, { type: 'key_rotated', severity: 'warning', message: 'Clé d’accès renouvelée : toutes les sessions ont été révoquées' });232    // La nouvelle clé n'est renvoyée qu'ici, une seule fois, sur le canal HTTPS de la session qui vient de prouver l'ancienne.233    sendJson(c.res, 200, { key }, { 'Set-Cookie': clearCookie });234  });235236  // ───────────── Caméras ─────────────237  route('GET', '/api/cameras', (c) => sendJson(c.res, 200, { cameras: cameras().map(camDto), serverTimeMs: Date.now() }));238  route('GET', '/api/cameras/:id/status', (c) => sendJson(c.res, 200, camDto(camOr404(c.params.id)).status));239240  route('GET', '/api/cameras/:id/live', (c) => {241    const cam = camOr404(c.params.id);242    const audioAllowed = cam.liveAudio && !!(cam.capabilities as any).audio;243    const q = (p: string, a: boolean) => `camera=${cam.id}&profile=${p}${a ? '&audio=1' : ''}`;244    sendJson(c.res, 200, {245      audioAllowed,246      mse: { main: `/api/live/ws?${q('main', false)}`, sub: `/api/live/ws?${q('sub', false)}`, mainAudio: audioAllowed ? `/api/live/ws?${q('main', true)}` : null, subAudio: audioAllowed ? `/api/live/ws?${q('sub', true)}` : null },247      hls: { main: `/api/live/hls/stream.m3u8?${q('main', false)}`, sub: `/api/live/hls/stream.m3u8?${q('sub', false)}`, mainAudio: audioAllowed ? `/api/live/hls/stream.m3u8?${q('main', true)}` : null, subAudio: audioAllowed ? `/api/live/hls/stream.m3u8?${q('sub', true)}` : null },248      webrtc: null,249    });250  });251252  route('GET', '/api/cameras/:id/snapshot', async (c) => {253    const q = new URLSearchParams({ camera: c.params.id, profile: c.url.searchParams.get('profile') === 'main' ? 'main' : 'sub' });254    const snap = await snapshot(cfg, parseTarget(cameras(), q));255    const headers: Record<string, string | number> = { 'Content-Type': 'image/jpeg', 'Content-Length': snap.data.length, 'Cache-Control': 'no-store', 'X-Captured-At': String(snap.atMs) };256    if (c.url.searchParams.get('download') === '1') headers['Content-Disposition'] = `attachment; filename="vision_${c.params.id}_${new Date(snap.atMs).toISOString().replace(/[:.]/g, '-')}.jpg"`;257    c.res.writeHead(200, headers);258    c.res.end(snap.data);259  });260261  route('PATCH', '/api/cameras/:id/settings', async (c) => {262    const cam = camOr404(c.params.id);263    const b = await readJson(c.req);264    const sets: string[] = [];265    const vals: any[] = [];266    const bool = (k: string, col: string) => {267      if (k in b) {268        if (typeof b[k] !== 'boolean') throw new HttpError(400, 'invalid_parameter', `${k} doit être booléen`);269        sets.push(`${col} = ?`);270        vals.push(b[k] ? 1 : 0);271      }272    };273    if ('name' in b) {274      const name = String(b.name).trim();275      if (name.length < 1 || name.length > 60 || /[\u0000-\u001f<>]/.test(name)) throw new HttpError(400, 'invalid_parameter', 'nom invalide');276      sets.push('name = ?');277      vals.push(name);278    }279    bool('recordEnabled', 'record_enabled');280    bool('recordAudio', 'record_audio');281    bool('liveAudio', 'live_audio');282    bool('ptzEnabled', 'ptz_enabled');283    bool('motionEnabled', 'motion_enabled');284    const int = (k: string, col: string, min: number, max: number) => {285      if (k in b) {286        if (!Number.isInteger(b[k]) || b[k] < min || b[k] > max) throw new HttpError(400, 'invalid_parameter', `${k} entre ${min} et ${max}`);287        sets.push(`${col} = ?`);288        vals.push(b[k]);289      }290    };291    int('motionSensitivity', 'motion_sensitivity', 1, 10);292    int('motionCooldownS', 'motion_cooldown_s', 10, 3600);293    if ('motionIgnore' in b) {294      if (!Array.isArray(b.motionIgnore) || b.motionIgnore.length > 144 || b.motionIgnore.some((x: unknown) => !Number.isInteger(x) || (x as number) < 0 || (x as number) > 143)) throw new HttpError(400, 'invalid_parameter', 'motionIgnore : cellules 0 à 143');295      sets.push('motion_ignore = ?');296      vals.push(JSON.stringify([...new Set(b.motionIgnore as number[])].sort((x, y) => x - y)));297    }298    if ('schedule' in b) {299      try {300        const s = validateSchedule(b.schedule);301        sets.push('schedule = ?');302        vals.push(s ? JSON.stringify(s) : null);303      } catch (e: any) {304        throw new HttpError(400, 'invalid_parameter', e.message);305      }306    }307    if (!sets.length) throw new HttpError(400, 'invalid_parameter', 'aucun réglage fourni');308    db.prepare(`UPDATE cameras SET ${sets.join(', ')}, updated_ms = ? WHERE id = ?`).run(...vals, Date.now(), cam.id);309    audit(db, c.session!.id, c.ip, 'camera_settings', { camera: cam.id, keys: Object.keys(b) });310    if ('liveAudio' in b && !b.liveAudio) closeAllSockets();311    sendJson(c.res, 200, camDto(camOr404(cam.id)));312  });313314  route('POST', '/api/cameras/:id/ptz', async (c) => {315    const cam = camOr404(c.params.id);316    const caps = cam.capabilities as any;317    if (!caps.ptz || !caps.ptzProfileToken) throw new HttpError(409, 'ptz_unsupported', 'cette caméra n’expose pas de PTZ');318    if (!cam.ptzEnabled) throw new HttpError(403, 'ptz_disabled', 'PTZ désactivé dans les réglages');319    const b = await readJson(c.req, 512);320    let body: Record<string, unknown>;321    if (b.action === 'stop') body = { cameraId: cam.id, action: 'stop' };322    else if (b.action === 'move') {323      const pan = Number(b.pan);324      const tilt = Number(b.tilt);325      if (!Number.isFinite(pan) || !Number.isFinite(tilt) || Math.abs(pan) > 1 || Math.abs(tilt) > 1 || (pan === 0 && tilt === 0)) throw new HttpError(400, 'invalid_parameter', 'pan/tilt entre -1 et 1');326      body = { cameraId: cam.id, action: 'move', pan, tilt, durationMs: Math.max(100, Math.min(3000, Number(b.durationMs) || 600)) };327    } else throw new HttpError(400, 'invalid_parameter', 'action inconnue');328    // exécuté par vision-core (seul service autorisé à joindre les caméras sur le réseau local)329    let r: { status: number; data: any };330    try {331      r = await coreCommand(cfg, '/ptz', body);332    } catch {333      throw new HttpError(503, 'core_unavailable', 'service d’enregistrement injoignable');334    }335    if (r.status !== 200) throw new HttpError(502, 'ptz_failed', 'la caméra n’a pas répondu à la commande');336    sendJson(c.res, 200, { ok: true });337  });338339  // ───────────── Enregistrements ─────────────340  const MAX_SPAN = 62 * 86400000;341  function rangeParams(q: URLSearchParams): { cam: Camera; fromMs: number; toMs: number } {342    const cam = camOr404(q.get('cameraId') || '');343    const fromMs = intParam(q.get('from'), 'from', { min: 0, max: 4102444800000 });344    const toMs = intParam(q.get('to'), 'to', { min: 0, max: 4102444800000 });345    if (toMs <= fromMs || toMs - fromMs > MAX_SPAN) throw new HttpError(400, 'invalid_parameter', 'période invalide (62 jours au plus)');346    return { cam, fromMs, toMs };347  }348349  route('GET', '/api/recordings', (c) => {350    const { cam, fromMs, toMs } = rangeParams(c.url.searchParams);351    const limit = intParam(c.url.searchParams.get('limit'), 'limit', { min: 1, max: 2000, def: 1500 });352    const cursor = intParam(c.url.searchParams.get('cursor'), 'cursor', { min: 0, def: 0 });353    const rows = db354      .prepare("SELECT id, start_ms, end_ms, duration_ms, size_bytes, codec, width, height, has_audio, state, protected, discontinuity FROM segments WHERE camera_id = ? AND end_ms > ? AND start_ms < ? AND start_ms >= ? AND state IN ('archived','recovered') ORDER BY start_ms LIMIT ?")355      .all(cam.id, fromMs, toMs, cursor, limit + 1) as Record<string, any>[];356    const more = rows.length > limit;357    const page = rows.slice(0, limit);358    sendJson(c.res, 200, {359      segments: page.map((r) => ({ id: r.id, startMs: r.start_ms, endMs: r.end_ms, durationMs: r.duration_ms, sizeBytes: r.size_bytes, codec: r.codec, width: r.width, height: r.height, hasAudio: !!r.has_audio, state: r.state, protected: !!r.protected, discontinuity: !!r.discontinuity })),360      nextCursor: more ? rows[limit].start_ms : null,361    });362  });363364  route('GET', '/api/recordings/timeline', (c) => {365    const { cam, fromMs, toMs } = rangeParams(c.url.searchParams);366    const cov = coverage(db, cam.id, fromMs, toMs);367    const prot = db.prepare('SELECT id, from_ms, to_ms, label FROM protections WHERE camera_id = ? AND to_ms > ? AND from_ms < ?').all(cam.id, fromMs, toMs) as Record<string, any>[];368    const mot = db.prepare("SELECT id, ts_ms, data FROM events WHERE type = 'motion' AND camera_id = ? AND ts_ms >= ? AND ts_ms < ? ORDER BY ts_ms LIMIT 3000").all(cam.id, fromMs - 5 * 60000, toMs) as Record<string, any>[];369    const motion = mot.map((m) => ({ eventId: m.id, fromMs: m.ts_ms, toMs: (safeParse(m.data) as any)?.toMs ?? null }));370    sendJson(c.res, 200, { ...cov, protections: prot.map((p) => ({ id: p.id, fromMs: p.from_ms, toMs: p.to_ms, label: p.label })), motion });371  });372373  route('GET', '/api/recordings/days', (c) => {374    const { cam, fromMs, toMs } = rangeParams(c.url.searchParams);375    const rows = db.prepare("SELECT start_ms, duration_ms, size_bytes FROM segments WHERE camera_id = ? AND end_ms > ? AND start_ms < ? AND state IN ('archived','recovered')").all(cam.id, fromMs, toMs) as { start_ms: number; duration_ms: number; size_bytes: number }[];376    const fmt = new Intl.DateTimeFormat('sv-SE', { timeZone: cfg.timezone, year: 'numeric', month: '2-digit', day: '2-digit' });377    const hourCache = new Map<number, string>();378    const days = new Map<string, { seconds: number; bytes: number; segments: number }>();379    for (const r of rows) {380      const h = Math.floor(r.start_ms / 3600000);381      let day = hourCache.get(h);382      if (!day) hourCache.set(h, (day = fmt.format(new Date(r.start_ms))));383      const d = days.get(day) || { seconds: 0, bytes: 0, segments: 0 };384      d.seconds += r.duration_ms / 1000;385      d.bytes += r.size_bytes;386      d.segments++;387      days.set(day, d);388    }389    sendJson(c.res, 200, { days: [...days.entries()].sort().map(([day, v]) => ({ day, seconds: Math.round(v.seconds), bytes: v.bytes, segments: v.segments })) });390  });391392  route('GET', '/api/recordings/thumbnail', async (c) => {393    const cam = camOr404(c.url.searchParams.get('cameraId') || '');394    const t = intParam(c.url.searchParams.get('t'), 't', { min: 0, max: 4102444800000 });395    let file: string;396    try {397      file = await thumbnail(cfg, db, cam.id, t);398    } catch (e) {399      // pas de vidéo à cet instant : réponse vide (l'interface n'affiche alors aucune image)400      if (e instanceof HttpError && e.status === 404) {401        c.res.writeHead(204, { 'Cache-Control': 'no-store' });402        c.res.end();403        return;404      }405      throw e;406    }407    serveFile(c.req, c.res, file, { contentType: 'image/jpeg', cacheControl: 'private, no-store' });408  });409410  route('GET', '/api/recordings/:id/playback', async (c) => {411    const id = intParam(c.params.id, 'id', { min: 1 });412    const file = await playbackFile(cfg, db, id, c.url.searchParams.get('compat') === '1');413    serveFile(c.req, c.res, file, { contentType: 'video/mp4', cacheControl: 'private, no-store' });414  });415416  route('POST', '/api/recordings/protect', async (c) => {417    const b = await readJson(c.req);418    const cam = camOr404(String(b.cameraId || ''));419    const fromMs = Number(b.fromMs);420    const toMs = Number(b.toMs);421    if (!Number.isSafeInteger(fromMs) || !Number.isSafeInteger(toMs) || toMs <= fromMs || toMs - fromMs > 7 * 86400000) throw new HttpError(400, 'invalid_parameter', 'période invalide (7 jours au plus)');422    const on = b.protected !== false;423    const label = typeof b.label === 'string' ? b.label.trim().slice(0, 80).replace(/[<>\u0000-\u001f]/g, '') : null;424    const r = db.prepare("UPDATE segments SET protected = ? WHERE camera_id = ? AND end_ms > ? AND start_ms < ?").run(on ? 1 : 0, cam.id, fromMs, toMs);425    if (on) db.prepare('INSERT INTO protections (camera_id, from_ms, to_ms, label, created_ms) VALUES (?, ?, ?, ?, ?)').run(cam.id, fromMs, toMs, label, Date.now());426    else db.prepare('DELETE FROM protections WHERE camera_id = ? AND from_ms >= ? AND to_ms <= ?').run(cam.id, fromMs, toMs);427    audit(db, c.session!.id, c.ip, on ? 'protect' : 'unprotect', { camera: cam.id, fromMs, toMs, segments: r.changes });428    sendJson(c.res, 200, { ok: true, segments: Number(r.changes) });429  });430431  // ───────────── Exports ─────────────432  const exportDto = (e: any) => ({ id: e.id, cameraId: e.camera_id, fromMs: e.from_ms, toMs: e.to_ms, state: e.state, progress: e.progress, sizeBytes: e.size_bytes, fileName: e.file_name, error: e.error, createdMs: e.created_ms, finishedMs: e.finished_ms, expiresMs: e.expires_ms });433  route('POST', '/api/exports', async (c) => {434    const b = await readJson(c.req);435    const cam = camOr404(String(b.cameraId || ''));436    const fromMs = Number(b.fromMs);437    const toMs = Number(b.toMs);438    if (!Number.isSafeInteger(fromMs) || !Number.isSafeInteger(toMs) || toMs <= fromMs) throw new HttpError(400, 'invalid_parameter', 'période invalide');439    if (toMs - fromMs > cfg.retention.exportMaxMinutes * 60000) throw new HttpError(400, 'invalid_parameter', `export limité à ${cfg.retention.exportMaxMinutes} minutes`);440    const id = exporter.create(cam.id, fromMs, toMs, cfg.timezone);441    audit(db, c.session!.id, c.ip, 'export_created', { id, camera: cam.id, fromMs, toMs });442    sendJson(c.res, 202, { id });443  });444  route('GET', '/api/exports', (c) => sendJson(c.res, 200, { exports: (db.prepare('SELECT * FROM exports ORDER BY created_ms DESC LIMIT 50').all() as any[]).map(exportDto) }));445  route('GET', '/api/exports/:id', (c) => {446    const e = db.prepare('SELECT * FROM exports WHERE id = ?').get(c.params.id);447    if (!e) throw new HttpError(404, 'export_not_found');448    sendJson(c.res, 200, exportDto(e));449  });450  route('GET', '/api/exports/:id/download', (c) => {451    const e = db.prepare("SELECT * FROM exports WHERE id = ? AND state = 'done'").get(c.params.id) as any;452    if (!e) throw new HttpError(404, 'export_not_found');453    audit(db, c.session!.id, c.ip, 'export_downloaded', { id: e.id });454    serveFile(c.req, c.res, exporter.filePath(e.id), { contentType: 'video/mp4', cacheControl: 'private, no-store', downloadName: e.file_name || `${e.id}.mp4` });455  });456  route('DELETE', '/api/exports/:id', (c) => {457    if (!exporter.remove(c.params.id)) throw new HttpError(404, 'export_not_found');458    sendJson(c.res, 200, { ok: true });459  });460461  // ───────────── Événements ─────────────462  route('GET', '/api/events', (c) => {463    const q = c.url.searchParams;464    const where: string[] = [];465    const vals: any[] = [];466    if (q.get('cameraId')) {467      where.push('camera_id = ?');468      vals.push(camOr404(q.get('cameraId')!).id);469    }470    if (q.get('type')) {471      if (!/^[a-z_]{1,40}$/.test(q.get('type')!)) throw new HttpError(400, 'invalid_parameter', 'type invalide');472      where.push('type = ?');473      vals.push(q.get('type'));474    }475    if (q.get('severity')) {476      if (!['info', 'warning', 'critical'].includes(q.get('severity')!)) throw new HttpError(400, 'invalid_parameter', 'gravité invalide');477      where.push('severity = ?');478      vals.push(q.get('severity'));479    }480    if (q.get('from')) {481      where.push('ts_ms >= ?');482      vals.push(intParam(q.get('from'), 'from', { min: 0 }));483    }484    if (q.get('to')) {485      where.push('ts_ms < ?');486      vals.push(intParam(q.get('to'), 'to', { min: 0 }));487    }488    const cursor = q.get('cursor');489    if (cursor) {490      where.push('id < ?');491      vals.push(intParam(cursor, 'cursor', { min: 1 }));492    }493    const limit = intParam(q.get('limit'), 'limit', { min: 1, max: 200, def: 50 });494    const rows = db.prepare(`SELECT * FROM events ${where.length ? 'WHERE ' + where.join(' AND ') : ''} ORDER BY id DESC LIMIT ?`).all(...vals, limit + 1) as Record<string, any>[];495    const page = rows.slice(0, limit);496    sendJson(c.res, 200, {497      events: page.map((r) => ({ id: r.id, tsMs: r.ts_ms, cameraId: r.camera_id, type: r.type, severity: r.severity, message: r.message, data: safeParse(r.data) })),498      nextCursor: rows.length > limit ? page[page.length - 1].id : null,499    });500  });501502  route('GET', '/api/events/:id/image', (c) => {503    const id = intParam(c.params.id, 'id', { min: 1 });504    const e = db.prepare("SELECT camera_id FROM events WHERE id = ? AND type = 'motion'").get(id) as { camera_id: string } | undefined;505    if (!e || !/^[a-z0-9][a-z0-9-]*$/.test(e.camera_id)) throw new HttpError(404, 'not_found');506    serveFile(c.req, c.res, motionImagePath(cfg, e.camera_id, id), { contentType: 'image/jpeg', cacheControl: 'private, no-store' });507  });508509  // ───────────── Notifications ─────────────510  route('GET', '/api/push/status', (c) => {511    const n = db.prepare('SELECT COUNT(*) AS n FROM push_devices d JOIN sessions s ON s.id = d.session_id WHERE s.revoked_ms IS NULL AND s.expires_ms > ?').get(Date.now()) as { n: number };512    const mine = db.prepare('SELECT motion, system, environment, name FROM push_devices WHERE session_id = ?').all(c.session!.id) as Record<string, any>[];513    sendJson(c.res, 200, { configured: apnsConfigured(cfg), devices: n.n, thisSession: mine.map((d) => ({ motion: !!d.motion, system: !!d.system, environment: d.environment, name: d.name })) });514  });515  route('POST', '/api/push/devices', async (c) => {516    const b = await readJson(c.req, 2048);517    const token = String(b.token || '').toLowerCase();518    if (!/^[0-9a-f]{64,200}$/.test(token)) throw new HttpError(400, 'invalid_parameter', 'jeton d’appareil invalide');519    const env = b.environment === 'sandbox' ? 'sandbox' : 'production';520    const name = typeof b.name === 'string' ? b.name.replace(/[\u0000-\u001f<>]/g, '').trim().slice(0, 60) || null : null;521    const now = Date.now();522    db.prepare(523      'INSERT INTO push_devices (token, session_id, environment, name, motion, system, created_ms, last_seen_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(token) DO UPDATE SET session_id = excluded.session_id, environment = excluded.environment, name = excluded.name, motion = excluded.motion, system = excluded.system, last_seen_ms = excluded.last_seen_ms, failures = 0',524    ).run(token, c.session!.id, env, name, b.motion === false ? 0 : 1, b.system === false ? 0 : 1, now, now);525    sendJson(c.res, 200, { ok: true });526  });527  route('DELETE', '/api/push/devices/:token', (c) => {528    db.prepare('DELETE FROM push_devices WHERE token = ? AND session_id = ?').run(c.params.token.toLowerCase(), c.session!.id);529    sendJson(c.res, 200, { ok: true });530  });531  route('POST', '/api/push/test', async (c) => {532    if (!apnsConfigured(cfg)) throw new HttpError(503, 'push_not_configured', 'notifications non configurées sur le serveur');533    const r = await sendPush(cfg, db, { kind: 'test', title: 'MacLustr Vision', body: 'Notification d’essai : tout fonctionne.', tsMs: Date.now() }, { sessionId: c.session!.id });534    sendJson(c.res, 200, r);535  });536537  // ───────────── Stockage et système ─────────────538  route('GET', '/api/storage/status', (c) => {539    const rs = retentionSettings(cfg, db);540    const vol = verifyVolume(cfg);541    let disk = { totalBytes: 0, freeBytes: 0, usedPct: 0 };542    try {543      disk = diskStats(cfg.dataDir);544    } catch {545      /* volume absent */546    }547    const perCam = db.prepare("SELECT camera_id, COUNT(*) AS n, COALESCE(SUM(size_bytes),0) AS bytes, MIN(start_ms) AS oldest, MAX(end_ms) AS newest, COALESCE(SUM(duration_ms),0) AS dur, COALESCE(SUM(protected),0) AS prot FROM segments WHERE state IN ('archived','recovered') GROUP BY camera_id").all() as Record<string, any>[];548    const used = archiveBytes(db);549    // débit réel : octets archivés sur les dernières 24 h (ou depuis le début si l'historique est plus court)550    const since = Date.now() - 86400000;551    const recent = db.prepare("SELECT COALESCE(SUM(size_bytes),0) AS bytes, MIN(start_ms) AS first, COALESCE(SUM(duration_ms),0) AS dur FROM segments WHERE start_ms >= ? AND state IN ('archived','recovered')").get(since) as Record<string, any>;552    const spanMs = recent.first ? Math.max(60000, Date.now() - recent.first) : 0;553    const bytesPerDay = spanMs ? (recent.bytes / spanMs) * 86400000 : 0;554    const quotaBytes = rs.maxArchiveGB * GB;555    const names = new Map(cameras().map((x) => [x.id, x.name]));556    sendJson(c.res, 200, {557      archive: { ok: vol.ok, reason: vol.reason || null, location: 'SSD interne du nœud (archive locale ; NAS non raccordé)', usedBytes: used, quotaBytes, usedPct: quotaBytes ? (used / quotaBytes) * 100 : 0, level: getSetting(db, 'storage_level', 'ok') },558      disk,559      spool: { bytes: dirSizeBytes(cfg.spoolDir), maxBytes: cfg.retention.spoolMaxGB * GB },560      exports: { bytes: dirSizeBytes(cfg.exportsDir) },561      cache: { bytes: dirSizeBytes(cfg.cacheDir), maxBytes: cfg.retention.playbackCacheGB * GB },562      retention: { days: rs.days, maxArchiveGB: rs.maxArchiveGB, minFreeGB: cfg.retention.minFreeGB, criticalFreeGB: cfg.retention.criticalFreeGB },563      suspended: getSetting(db, 'recording_suspended', false),564      estimate: {565        measuredOverMs: spanMs,566        bytesPerDay: Math.round(bytesPerDay),567        // jours d'historique que le quota permet au débit mesuré (borné par la rétention en jours)568        daysAtQuota: bytesPerDay > 0 ? Math.min(rs.days, quotaBytes / bytesPerDay) : null,569        daysUntilQuota: bytesPerDay > 0 ? Math.max(0, (quotaBytes - used) / bytesPerDay) : null,570      },571      cameras: perCam.map((r) => ({ cameraId: r.camera_id, name: names.get(r.camera_id) || r.camera_id, segments: r.n, bytes: r.bytes, oldestMs: r.oldest, newestMs: r.newest, recordedSeconds: Math.round(r.dur / 1000), protectedSegments: r.prot })),572    });573  });574575  route('GET', '/api/system/status', (c) => {576    const core = getSetting<Record<string, any>>(db, 'core_heartbeat', {});577    const now = Date.now();578    const series = (key: string, minutes: number) => (db.prepare('SELECT ts_ms, value FROM metrics WHERE key = ? AND ts_ms > ? ORDER BY ts_ms').all(key, now - minutes * 60000) as { ts_ms: number; value: number }[]).map((r) => [r.ts_ms, Math.round(r.value * 100) / 100]);579    const last = (key: string) => (db.prepare('SELECT value FROM metrics WHERE key = ? ORDER BY ts_ms DESC LIMIT 1').get(key) as { value: number } | undefined)?.value ?? null;580    const workers = db.prepare('SELECT * FROM camera_state').all() as Record<string, any>[];581    const errors = db.prepare("SELECT id, ts_ms, camera_id, type, severity, message FROM events WHERE severity IN ('warning','critical') ORDER BY id DESC LIMIT 15").all() as Record<string, any>[];582    sendJson(c.res, 200, {583      node: { hostname: os.hostname().split('.')[0], platform: `${os.type()} ${os.release()}`, arch: os.arch(), cpus: os.cpus().length, cpuModel: os.cpus()[0]?.model || null, totalMemBytes: os.totalmem(), uptimeS: Math.round(os.uptime()), load: os.loadavg() },584      core: { alive: !!core.tsMs && now - core.tsMs < 30000, lastBeatMs: core.tsMs || null, startedMs: core.startedMs || null, version: core.version || null, commit: core.commit || null, gateway: core.go2rtc || null, archiveOk: core.archiveOk ?? null, spoolFull: core.spoolFull ?? null },585      api: { startedMs, version: cfg.version, commit: gitCommit(), liveViewers: liveViewerCount(), node: process.version },586      current: { cpuPct: last('cpu_pct'), visionCpuPct: last('vision_cpu_pct'), visionRssMb: last('vision_rss_mb'), bitrateBps: last('bitrate_bps'), processes: last('vision_procs') },587      series: { cpuPct: series('cpu_pct', 180), visionRssMb: series('vision_rss_mb', 180), bitrateBps: series('bitrate_bps', 180) },588      workers: workers.map((w) => ({ cameraId: w.camera_id, reachable: !!w.reachable, recorderState: w.recorder_state, sinceMs: w.recorder_since_ms, restarts: w.recorder_restarts, lastSegmentEndMs: w.last_segment_end_ms, bitrateBps: w.last_bitrate_bps, lastError: w.last_error })),589      recentErrors: errors.map((e) => ({ id: e.id, tsMs: e.ts_ms, cameraId: e.camera_id, type: e.type, severity: e.severity, message: e.message })),590      serverTimeMs: now,591      timezone: cfg.timezone,592    });593  });594595  route('GET', '/api/settings', (c) => {596    sendJson(c.res, 200, { retention: retentionSettings(cfg, db), session: cfg.session, timezone: cfg.timezone, limits: { exportMaxMinutes: cfg.retention.exportMaxMinutes } });597  });598  route('PATCH', '/api/settings', async (c) => {599    const b = await readJson(c.req);600    if (!b.retention || typeof b.retention !== 'object') throw new HttpError(400, 'invalid_parameter', 'retention attendu');601    const cur = retentionSettings(cfg, db);602    const days = b.retention.days === undefined ? cur.days : Number(b.retention.days);603    const maxArchiveGB = b.retention.maxArchiveGB === undefined ? cur.maxArchiveGB : Number(b.retention.maxArchiveGB);604    if (!Number.isInteger(days) || days < 1 || days > 365) throw new HttpError(400, 'invalid_parameter', 'rétention entre 1 et 365 jours');605    let total = 0;606    try {607      total = diskStats(cfg.dataDir).totalBytes / GB;608    } catch {609      /* rien */610    }611    if (!Number.isFinite(maxArchiveGB) || maxArchiveGB < 5 || (total && maxArchiveGB > total - cfg.retention.minFreeGB)) throw new HttpError(400, 'invalid_parameter', `quota entre 5 Go et ${Math.floor(total - cfg.retention.minFreeGB)} Go`);612    setSetting(db, 'retention', { days, maxArchiveGB: Math.round(maxArchiveGB) });613    audit(db, c.session!.id, c.ip, 'retention_changed', { days, maxArchiveGB });614    sendJson(c.res, 200, { retention: retentionSettings(cfg, db) });615  });616617  // ───────────── Direct (HLS) ─────────────618  route('GET', '/api/live/hls/stream.m3u8', async (c) => hlsMaster(cfg, c.res, parseTarget(cameras(), c.url.searchParams)));619  route('GET', '/api/live/hls/hls/:file', async (c) => hlsFile(cfg, c.res, c.params.file, c.url.searchParams));620621  // ───────────── Fichiers statiques (interface) ─────────────622  function serveStatic(req: http.IncomingMessage, res: http.ServerResponse, pathname: string): void {623    let rel = decodeURIComponent(pathname);624    if (rel.includes('\0') || rel.includes('..')) throw new HttpError(400, 'bad_path');625    if (rel === '/' || !path.extname(rel)) rel = '/index.html';626    const file = path.resolve(cfg.webDir, '.' + rel);627    if (!file.startsWith(cfg.webDir + path.sep) || !fs.existsSync(file)) {628      if (path.extname(pathname)) throw new HttpError(404, 'not_found');629      return serveFile(req, res, path.join(cfg.webDir, 'index.html'), { cacheControl: 'no-cache', contentType: 'text/html; charset=utf-8' });630    }631    const immutable = rel.startsWith('/assets/');632    serveFile(req, res, file, { cacheControl: immutable ? 'public, max-age=31536000, immutable' : 'no-cache', contentType: mimeFor(file) });633  }634635  async function handle(req: http.IncomingMessage, res: http.ServerResponse): Promise<void> {636    applySecurity(res);637    const url = new URL(req.url || '/', 'http://local');638    const method = req.method || 'GET';639    try {640      if (!url.pathname.startsWith('/api/')) {641        if (method !== 'GET' && method !== 'HEAD') throw new HttpError(405, 'method_not_allowed');642        return serveStatic(req, res, url.pathname);643      }644      const m = method === 'HEAD' ? 'GET' : method;645      let allowed = false;646      for (const r of routes) {647        const match = r.re.exec(url.pathname);648        if (!match) continue;649        if (r.method !== m) {650          allowed = true;651          continue;652        }653        const ip = clientIp(req);654        const session = sessionOf(req);655        if (!r.pub && !session) throw new HttpError(401, 'unauthenticated', 'session requise');656        if (m !== 'GET') checkCsrf(req);657        const params: Record<string, string> = {};658        r.keys.forEach((k, i) => (params[k] = match[i + 1]));659        await r.handler({ req, res, url, ip, session, params });660        return;661      }662      throw allowed ? new HttpError(405, 'method_not_allowed') : new HttpError(404, 'not_found');663    } catch (e: any) {664      if (res.headersSent) {665        res.destroy();666        return;667      }668      if (e instanceof HttpError) {669        const headers: Record<string, string> = {};670        if (e.status === 429 && e.extra?.retryAfterS) headers['Retry-After'] = String(e.extra.retryAfterS);671        return sendJson(res, e.status, { error: e.code, message: e.message, ...(e.extra || {}) }, headers);672      }673      log.error('erreur interne', { path: url.pathname, err: String(e?.stack || e) });674      sendJson(res, 500, { error: 'internal_error', message: 'erreur interne' });675    }676  }677678  function handleUpgrade(req: http.IncomingMessage, socket: Duplex, head: Buffer): void {679    const deny = (status: number, text: string) => {680      socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);681      socket.destroy();682    };683    try {684      const url = new URL(req.url || '/', 'http://local');685      if (url.pathname !== '/api/live/ws') return deny(404, 'Not Found');686      if (!origins.has(String(req.headers.origin || ''))) return deny(403, 'Forbidden');687      const session = sessionOf(req);688      if (!session) return deny(401, 'Unauthorized');689      const target = parseTarget(cameras(), url.searchParams);690      proxyWebSocket(cfg, req, socket, head, target, session.id);691    } catch (e: any) {692      deny(e instanceof HttpError ? e.status : 500, 'Error');693    }694  }695696  const housekeeping = setInterval(() => {697    setSetting(db, 'api_heartbeat', { tsMs: Date.now(), pid: process.pid });698    pruneCache(cfg.cacheDir, cfg.retention.playbackCacheGB * GB);699  }, 60000);700  housekeeping.unref();701  setSetting(db, 'api_heartbeat', { tsMs: Date.now(), pid: process.pid });702703  return { handle, handleUpgrade, limiter, close: () => clearInterval(housekeeping) };704}705706function safeParse(s: string): unknown {707  try {708    return JSON.parse(s);709  } catch {710    return {};711  }712}713714export function startServer(cfg: Config, db: DB) {715  const app = createApp(cfg, db);716  const servers: http.Server[] = [];717  for (const host of resolveListen(cfg)) {718    const server = http.createServer({ requestTimeout: 0, headersTimeout: 20000, keepAliveTimeout: 65000 }, (req, res) => void app.handle(req, res));719    server.on('upgrade', app.handleUpgrade);720    server.on('clientError', (_e, socket) => socket.destroy());721    server.listen(cfg.port, host, () => log.info('écoute', { host, port: cfg.port }));722    servers.push(server);723  }724  return { app, servers };725}726727const isMain = process.argv[1] && path.resolve(process.argv[1]) === path.resolve(new URL(import.meta.url).pathname);728if (isMain) {729  const cfg = loadConfig();730  ensureDirs(cfg);731  const db = openAndMigrate(cfg);732  syncCameras(db, loadRegistry(cfg));733  if (!hasActiveKey(db)) log.warn('aucune clé d’accès active : exécuter scripts/rotate-key.sh');734  const { servers, app } = startServer(cfg, db);735  const stop = () => {736    app.close();737    closeAllSockets();738    for (const s of servers) s.close();739    setTimeout(() => process.exit(0), 300);740  };741  process.on('SIGTERM', stop);742  process.on('SIGINT', stop);743  process.on('uncaughtException', (e) => log.error('exception non interceptée', { err: String(e?.stack || e) }));744  process.on('unhandledRejection', (e: any) => log.error('rejet non intercepté', { err: String(e?.stack || e) }));745}746
Files main
Menu

Theme