Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Vision8 * File : server/src/storage.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// Stockage : identité du volume d'archive, mesures d'espace, suppressions bornées au périmètre géré.43import crypto from 'node:crypto';44import fs from 'node:fs';45import path from 'node:path';46import type { Config } from './config.ts';4748const MARKER = '.vision-volume';4950export type VolumeCheck = { ok: boolean; reason?: string };5152/** Crée le marqueur d'identité (setup). Ne remplace jamais un marqueur existant différent. */53export function initVolume(cfg: Config): string {54 fs.mkdirSync(cfg.archiveDir, { recursive: true, mode: 0o700 });55 const idFile = path.join(cfg.configDir, 'volume-id');56 const markerFile = path.join(cfg.archiveDir, MARKER);57 let expected = fs.existsSync(idFile) ? fs.readFileSync(idFile, 'utf8').trim() : '';58 const present = fs.existsSync(markerFile) ? String(JSON.parse(fs.readFileSync(markerFile, 'utf8')).volumeId || '') : '';59 if (expected && present && expected !== present) throw new Error('le marqueur du volume ne correspond pas à volume-id : intervention manuelle requise');60 if (!expected) expected = present || crypto.randomBytes(16).toString('hex');61 if (!fs.existsSync(idFile)) fs.writeFileSync(idFile, expected + '\n', { mode: 0o600 });62 if (!present) fs.writeFileSync(markerFile, JSON.stringify({ volumeId: expected, createdAt: new Date().toISOString(), app: 'maclustr-vision' }) + '\n', { mode: 0o600 });63 return expected;64}6566/** Vérifie que le dossier d'archive est bien le volume attendu avant toute écriture ou suppression. */67export function verifyVolume(cfg: Config): VolumeCheck {68 try {69 const expected = fs.readFileSync(path.join(cfg.configDir, 'volume-id'), 'utf8').trim();70 if (!expected) return { ok: false, reason: 'volume-id vide' };71 const marker = JSON.parse(fs.readFileSync(path.join(cfg.archiveDir, MARKER), 'utf8'));72 if (marker.volumeId !== expected) return { ok: false, reason: 'identité du volume inattendue' };73 return { ok: true };74 } catch (e: any) {75 return { ok: false, reason: e?.code === 'ENOENT' ? 'volume d’archive absent ou non identifié' : String(e?.message || e) };76 }77}7879export type DiskStats = { totalBytes: number; freeBytes: number; usedPct: number };8081export function diskStats(dir: string): DiskStats {82 const s = fs.statfsSync(dir);83 const total = Number(s.blocks) * Number(s.bsize);84 const free = Number(s.bavail) * Number(s.bsize);85 return { totalBytes: total, freeBytes: free, usedPct: total > 0 ? ((total - free) / total) * 100 : 0 };86}8788/** Résout un chemin relatif du catalogue en chemin absolu, en refusant toute sortie du dossier d'archive. */89export function resolveArchivePath(cfg: Config, relPath: string): string {90 if (!/^[a-z0-9][a-z0-9-]*\/\d{4}\/\d{2}\/\d{2}\/\d{8}T\d{6}Z\.mkv$/.test(relPath)) throw new Error('chemin de segment invalide');91 const abs = path.resolve(cfg.archiveDir, relPath);92 if (!abs.startsWith(cfg.archiveDir + path.sep)) throw new Error('chemin hors du périmètre géré');93 return abs;94}9596/** Supprime un segment d'archive. Refuse tout ce qui n'est pas un fichier .mkv sous le dossier géré. */97export function deleteArchiveFile(cfg: Config, relPath: string): boolean {98 const abs = resolveArchivePath(cfg, relPath);99 try {100 const real = fs.realpathSync(abs);101 const realRoot = fs.realpathSync(cfg.archiveDir);102 if (!real.startsWith(realRoot + path.sep)) throw new Error('lien symbolique hors périmètre');103 fs.unlinkSync(real);104 return true;105 } catch (e: any) {106 if (e?.code === 'ENOENT') return false;107 throw e;108 }109}110111export function dirSizeBytes(dir: string): number {112 let total = 0;113 let entries: fs.Dirent[] = [];114 try {115 entries = fs.readdirSync(dir, { withFileTypes: true });116 } catch {117 return 0;118 }119 for (const e of entries) {120 const p = path.join(dir, e.name);121 if (e.isDirectory()) total += dirSizeBytes(p);122 else if (e.isFile()) {123 try {124 total += fs.statSync(p).size;125 } catch {126 /* fichier disparu */127 }128 }129 }130 return total;131}132133export function relPathFor(cameraId: string, startMs: number): string {134 const d = new Date(startMs);135 const p = (n: number, l = 2) => String(n).padStart(l, '0');136 const stamp = `${d.getUTCFullYear()}${p(d.getUTCMonth() + 1)}${p(d.getUTCDate())}T${p(d.getUTCHours())}${p(d.getUTCMinutes())}${p(d.getUTCSeconds())}Z`;137 return `${cameraId}/${d.getUTCFullYear()}/${p(d.getUTCMonth() + 1)}/${p(d.getUTCDate())}/${stamp}.mkv`;138}139140export function parseStamp(name: string): number | null {141 const m = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z/.exec(name);142 if (!m) return null;143 return Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]);144}145