#!/usr/bin/env node
import{execFileSync as a}from"node:child_process";import{readFileSync as b,readdirSync as c}from"node:fs";let d=process.env.MADARX_ENV_FILE||new URL("../.env.local",import.meta.url).pathname;try{for(let a of b(d,"utf8").split("\n")){let b=a.trim();if(!b||b.startsWith("#"))continue;let c=b.indexOf("=");if(c<0)continue;let d=b.slice(0,c).trim(),e=b.slice(c+1).trim().replace(/^["']|["']$/g,"");!d||d in process.env||(process.env[d]=e)}}catch{}(async function(){let d=process.platform,e=function(d){if("darwin"===d)try{let b=a("fdesetup",["status"],{stdio:["ignore","pipe","ignore"],timeout:5e3}).toString().trim();return{detected_state:/FileVault is On\./i.test(b)?"on":"off",tool:"fdesetup",raw:b.slice(0,200)}}catch(a){return{detected_state:"unknown",tool:"fdesetup",error:a?.message?.slice(0,100)||String(a)}}if("linux"===d){try{if(a("lsblk",["-o","TYPE,MOUNTPOINT,FSTYPE","--noheadings","--raw"],{stdio:["ignore","pipe","ignore"],timeout:5e3}).toString().split("\n").some(a=>a.trim().startsWith("crypt")))return{detected_state:"on",tool:"lsblk",detail:"crypt device found"}}catch{}try{for(let a of c("/sys/class/block",{withFileTypes:!0}))try{let c=`/sys/class/block/${a.name}/dm/uuid`;if(b(c,"utf8").trim().startsWith("CRYPT-LUKS"))return{detected_state:"on",tool:"sysfs-dm-uuid",device:a.name}}catch{}}catch{}return{detected_state:"off",tool:"lsblk+sysfs",detail:"no crypt/LUKS devices detected"}}if("win32"===d)try{let b=a("manage-bde",["-status","C:"],{stdio:["ignore","pipe","ignore"],timeout:1e4}).toString();return{detected_state:/Protection\s+On/i.test(b)?"on":"off",tool:"manage-bde",raw:b.slice(0,200)}}catch(a){return{detected_state:"unknown",tool:"manage-bde",error:a?.message?.slice(0,100)||String(a)}}return{detected_state:"unknown",detail:"unsupported platform"}}(d),{detected_state:f}=e,g="on"===f?"enabled":"off"===f?"disabled":"unknown",h=`Disk encryption check: ${g} (${d})`,i="on"===f?"ok":"off"===f?"warning":"unknown",j=!1;try{let{appendAudit:a}=await import("../lib/runtime.js");a({type:"disk_encryption.health",summary:h,status:i,meta:{os:d,detected_state:f,...e}}),j=!0}catch{try{let{getDb:a,newId:b,nowIso:c}=await import("../lib/db.js"),g=a(),k=b("audit"),l=c();g.prepare("INSERT INTO audit_logs (id, at, type, summary, status, meta) VALUES (?, ?, ?, ?, ?, ?)").run(k,l,"disk_encryption.health",h,i,JSON.stringify({os:d,detected_state:f,...e})),j=!0}catch(a){console.error("[check-disk-enc] Could not write audit row:",a?.message||a)}}let k="on"===f?"[OK]":"off"===f?"[WARN]":"[?]";console.log(`${k} ${h}`),j&&console.log("     Audit row written to audit_logs."),"on"!==f&&process.stderr.write("\n[SECURITY WARNING] Full-disk encryption appears to be "+g+" on this host. In production, enable FileVault (macOS), BitLocker (Windows), or LUKS (Linux) to protect artifact data at rest.\n\n"),process.exit(0)})().catch(a=>{console.error("[check-disk-enc] Unexpected error:",a?.message||a),process.exit(0)});