@ejouan/lxray 0.0.0-stage → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,154 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Helpers for monitoring tools: thresholds (OK / WARNING / CRITICAL), comparison of two audits,
5
+ * Prometheus metrics, and saving reports to files.
6
+ */
7
+ const fs = require('node:fs/promises');
8
+ const path = require('node:path');
9
+ const { summarize, REPORT_FILES } = require('./report');
10
+
11
+ const SEV_RANK = { ok: 0, info: 1, warning: 2, critical: 3 };
12
+
13
+ /** Accepts an audit result, a parsed report or a summary, and returns a summary. */
14
+ function toSummary(x) {
15
+ if (!x || typeof x !== 'object') throw new TypeError('Expected an audit result, a report or a summary');
16
+ if (x.summary && x.report) return x.summary;
17
+ if (Array.isArray(x.findings)) return summarize(x);
18
+ if (x.counts && 'score' in x) return x;
19
+ throw new TypeError('Expected an audit result, a report or a summary');
20
+ }
21
+
22
+ function findingsOf(x) {
23
+ if (x && x.report && Array.isArray(x.report.findings)) return x.report.findings;
24
+ if (x && Array.isArray(x.findings)) return x.findings;
25
+ throw new TypeError('compare() needs audit results or parsed reports (with findings)');
26
+ }
27
+
28
+ /**
29
+ * Turns a report into a monitoring state, like a Nagios/Icinga/Zabbix check.
30
+ * @param {object} x audit result, report or summary
31
+ * @param {object} [rules]
32
+ * @param {number} [rules.minScore] CRITICAL below this score
33
+ * @param {number} [rules.warnScore] WARNING below this score
34
+ * @param {number} [rules.maxCritical=0] CRITICAL when more critical findings than this
35
+ * @param {number} [rules.maxWarning] WARNING when more warning findings than this
36
+ * @param {string[]} [rules.ignore] finding ids to ignore (accepted risks)
37
+ * @param {boolean} [rules.partialIsWarning=false] a partial (non-root) audit raises WARNING
38
+ * @returns {{ status: 'ok'|'warning'|'critical', exitCode: 0|1|2, message: string, reasons: string[], score: number|null }}
39
+ */
40
+ function evaluate(x, rules = {}) {
41
+ const s = toSummary(x);
42
+ const ignore = new Set(rules.ignore || []);
43
+ const issues = (s.issues || []).filter((i) => !ignore.has(i.id));
44
+ const critical = issues.filter((i) => i.severity === 'critical');
45
+ const warning = issues.filter((i) => i.severity === 'warning');
46
+ const crit = [];
47
+ const warn = [];
48
+ const maxCritical = rules.maxCritical ?? 0;
49
+ if (critical.length > maxCritical) crit.push(`${critical.length} critical finding(s): ${critical.map((i) => i.title).join('; ')}`);
50
+ if (rules.maxWarning !== undefined && warning.length > rules.maxWarning) warn.push(`${warning.length} warning(s) (max ${rules.maxWarning})`);
51
+ if (typeof s.score === 'number') {
52
+ if (rules.minScore !== undefined && s.score < rules.minScore) crit.push(`score ${s.score} < ${rules.minScore}`);
53
+ else if (rules.warnScore !== undefined && s.score < rules.warnScore) warn.push(`score ${s.score} < ${rules.warnScore}`);
54
+ }
55
+ if (rules.partialIsWarning && x && x.partial) warn.push('partial audit (not root): some checks were not evaluated');
56
+ const status = crit.length ? 'critical' : warn.length ? 'warning' : 'ok';
57
+ const reasons = [...crit, ...warn];
58
+ const head = `${status.toUpperCase()} - ${s.hostname || 'host'} ${s.score ?? '?'}/100 (${s.grade ?? '?'})`;
59
+ return { status, exitCode: status === 'critical' ? 2 : status === 'warning' ? 1 : 0, message: reasons.length ? `${head}: ${reasons.join(', ')}` : head, reasons, score: s.score ?? null };
60
+ }
61
+
62
+ /**
63
+ * What changed between two audits of the same machine (tracking over time).
64
+ * @returns {{ scoreBefore, scoreAfter, scoreDelta, newIssues, resolved, worse, better, persisting }}
65
+ */
66
+ function compare(previous, current) {
67
+ const before = new Map(findingsOf(previous).map((f) => [f.id, f]));
68
+ const after = new Map(findingsOf(current).map((f) => [f.id, f]));
69
+ const bad = (f) => f && f.severity !== 'ok';
70
+ const out = { newIssues: [], resolved: [], worse: [], better: [], persisting: [] };
71
+ for (const [id, f] of after) {
72
+ const p = before.get(id);
73
+ if (bad(f) && !bad(p)) out.newIssues.push(f);
74
+ else if (bad(f) && bad(p)) {
75
+ if (SEV_RANK[f.severity] > SEV_RANK[p.severity]) out.worse.push({ ...f, previousSeverity: p.severity });
76
+ else if (SEV_RANK[f.severity] < SEV_RANK[p.severity]) out.better.push({ ...f, previousSeverity: p.severity });
77
+ else out.persisting.push(f);
78
+ }
79
+ }
80
+ for (const [id, p] of before) if (bad(p) && !bad(after.get(id))) out.resolved.push(p);
81
+ const sb = toSummary(previous).score;
82
+ const sa = toSummary(current).score;
83
+ return { scoreBefore: sb, scoreAfter: sa, scoreDelta: typeof sb === 'number' && typeof sa === 'number' ? sa - sb : null, ...out };
84
+ }
85
+
86
+ function promLabel(v) {
87
+ return String(v ?? '').replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/"/g, '\\"');
88
+ }
89
+
90
+ /**
91
+ * Prometheus text exposition for one or many audits (an auditFleet() array works as is).
92
+ * @param {object|object[]} input audit result(s), fleet entries ({host, ok, result}) or reports
93
+ * @param {{ prefix?: string, labels?: Record<string,string> }} [options]
94
+ */
95
+ function toPrometheus(input, options = {}) {
96
+ const prefix = options.prefix || 'lxray';
97
+ if (!/^[a-zA-Z_:][a-zA-Z0-9_:]*$/.test(prefix)) throw new TypeError('prefix: invalid metric name');
98
+ const extra = Object.entries(options.labels || {});
99
+ for (const [k] of extra) if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(k)) throw new TypeError(`label "${k}": invalid name`);
100
+ const items = Array.isArray(input) ? input : [input];
101
+ const lines = {
102
+ up: [`# HELP ${prefix}_up 1 when the last audit of the host succeeded.`, `# TYPE ${prefix}_up gauge`],
103
+ score: [`# HELP ${prefix}_score Health score 0-100 of the host.`, `# TYPE ${prefix}_score gauge`],
104
+ findings: [`# HELP ${prefix}_findings Findings of the last audit by severity.`, `# TYPE ${prefix}_findings gauge`],
105
+ partial: [`# HELP ${prefix}_partial 1 when the audit was partial (not root).`, `# TYPE ${prefix}_partial gauge`],
106
+ duration: [`# HELP ${prefix}_audit_duration_seconds Duration of the last audit.`, `# TYPE ${prefix}_audit_duration_seconds gauge`],
107
+ generated: [`# HELP ${prefix}_report_timestamp_seconds When the report was generated (Unix time).`, `# TYPE ${prefix}_report_timestamp_seconds gauge`]
108
+ };
109
+ const lbl = (pairs) => `{${[...pairs, ...extra].map(([k, v]) => `${k}="${promLabel(v)}"`).join(',')}}`;
110
+ for (const it of items) {
111
+ const fleet = it && typeof it.ok === 'boolean' && 'host' in it;
112
+ const host = fleet ? it.host : null;
113
+ if (fleet && !it.ok) {
114
+ lines.up.push(`${prefix}_up${lbl([['host', host]])} 0`);
115
+ continue;
116
+ }
117
+ const r = fleet ? it.result : it;
118
+ const s = toSummary(r);
119
+ const h = host || s.hostname || 'unknown';
120
+ lines.up.push(`${prefix}_up${lbl([['host', h]])} 1`);
121
+ if (typeof s.score === 'number') lines.score.push(`${prefix}_score${lbl([['host', h], ['grade', s.grade || '']])} ${s.score}`);
122
+ for (const sev of ['critical', 'warning', 'info', 'ok']) lines.findings.push(`${prefix}_findings${lbl([['host', h], ['severity', sev]])} ${(s.counts && s.counts[sev]) || 0}`);
123
+ if (r && typeof r.partial === 'boolean') lines.partial.push(`${prefix}_partial${lbl([['host', h]])} ${r.partial ? 1 : 0}`);
124
+ if (r && typeof r.durationMs === 'number') lines.duration.push(`${prefix}_audit_duration_seconds${lbl([['host', h]])} ${(r.durationMs / 1000).toFixed(3)}`);
125
+ const t = Date.parse(s.generated || '');
126
+ if (!Number.isNaN(t)) lines.generated.push(`${prefix}_report_timestamp_seconds${lbl([['host', h]])} ${Math.floor(t / 1000)}`);
127
+ }
128
+ return `${Object.values(lines).filter((l) => l.length > 2).flat().join('\n')}\n`;
129
+ }
130
+
131
+ /**
132
+ * Writes the reports of an audit result to a folder (lxray-report.json, .html, .md, lxray-summary.txt).
133
+ * @returns {Promise<string[]>} written paths
134
+ */
135
+ async function saveReports(result, dir, options = {}) {
136
+ if (!result || !result.report) throw new TypeError('saveReports() needs an audit result');
137
+ const target = path.resolve(dir);
138
+ await fs.mkdir(target, { recursive: true, mode: 0o750 });
139
+ const prefix = options.prefix ? `${String(options.prefix).replace(/[^A-Za-z0-9._-]/g, '_')}-` : '';
140
+ const out = [];
141
+ const write = async (name, content) => {
142
+ const p = path.join(target, prefix + name);
143
+ await fs.writeFile(p, content, { mode: 0o640 });
144
+ out.push(p);
145
+ };
146
+ await write(REPORT_FILES.json, JSON.stringify(result.report, null, 2));
147
+ if (result.html) await write(REPORT_FILES.html, result.html);
148
+ if (result.markdown) await write(REPORT_FILES.md, result.markdown);
149
+ if (result.text) await write(REPORT_FILES.txt, result.text);
150
+ if (result.archive && Buffer.isBuffer(result.archive)) await write(result.archiveName || 'lxray-snapshot.tar.gz', result.archive);
151
+ return out;
152
+ }
153
+
154
+ module.exports = { evaluate, compare, toPrometheus, saveReports };
package/src/plugins.js ADDED
@@ -0,0 +1,56 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * The 13 collection plugins of LXRAY 1.2.0 (ids = file names in /opt/lxray/plugins).
5
+ * `--only` / `--exclude` take these ids; friendly aliases are accepted and translated.
6
+ */
7
+ const PLUGINS = Object.freeze([
8
+ { id: '00-system', alias: 'system', title: 'System, OS, uptime, time sync' },
9
+ { id: '05-raw', alias: 'raw', title: 'Raw command outputs (sosreport style)' },
10
+ { id: '10-cpu-memory', alias: 'cpu_memory', title: 'CPU, memory, load, pressure' },
11
+ { id: '20-storage', alias: 'storage', title: 'Disks, filesystems, RAID, LVM, I/O' },
12
+ { id: '30-network', alias: 'network', title: 'Interfaces, routes, DNS, listening ports, firewall' },
13
+ { id: '40-kernel', alias: 'kernel', title: 'Kernel, modules, sysctl, crashes' },
14
+ { id: '50-services', alias: 'services', title: 'systemd units, failed services, timers' },
15
+ { id: '60-packages', alias: 'packages', title: 'Packages, updates, repositories' },
16
+ { id: '70-security', alias: 'security', title: 'SSH, users, sudo, SELinux/AppArmor, firewall' },
17
+ { id: '80-logs', alias: 'logs', title: 'Journal and log errors' },
18
+ { id: '85-databases', alias: 'databases', title: 'MySQL, PostgreSQL, Redis...' },
19
+ { id: '90-containers', alias: 'containers', title: 'Docker, Podman, Kubernetes' },
20
+ { id: '95-appstack', alias: 'applications', title: 'Web servers, runtimes, application stack' }
21
+ ]);
22
+
23
+ /** Plugins the `quick` profile skips (heavy ones). */
24
+ const QUICK_SKIPPED = Object.freeze(['60-packages', '85-databases', '90-containers']);
25
+
26
+ const EXTRA_ALIASES = {
27
+ cpu: ['10-cpu-memory'], memory: ['10-cpu-memory'], 'cpu-memory': ['10-cpu-memory'],
28
+ storage_raid: ['20-storage'], disks: ['20-storage'], raid: ['20-storage'],
29
+ firewall: ['30-network', '70-security'], appstack: ['95-appstack'], apps: ['95-appstack']
30
+ };
31
+
32
+ /**
33
+ * Translates ids or aliases to plugin ids. Throws on unknown names (a typo would
34
+ * otherwise silently select nothing).
35
+ * @param {string[]|string|undefined} names
36
+ * @returns {string[]}
37
+ */
38
+ function resolvePlugins(names) {
39
+ if (names === undefined || names === null) return [];
40
+ const list = Array.isArray(names) ? names : String(names).split(',');
41
+ const out = [];
42
+ for (const raw of list) {
43
+ const n = String(raw).trim();
44
+ if (!n) continue;
45
+ const byId = PLUGINS.find((p) => p.id === n);
46
+ const byAlias = PLUGINS.find((p) => p.alias === n);
47
+ const ids = byId ? [byId.id] : byAlias ? [byAlias.id] : EXTRA_ALIASES[n];
48
+ if (!ids) {
49
+ throw new TypeError(`Unknown LXRAY plugin "${n}". Use one of: ${PLUGINS.map((p) => `${p.id} (${p.alias})`).join(', ')}`);
50
+ }
51
+ for (const id of ids) if (!out.includes(id)) out.push(id);
52
+ }
53
+ return out;
54
+ }
55
+
56
+ module.exports = { PLUGINS, QUICK_SKIPPED, resolvePlugins };
package/src/remote.js ADDED
@@ -0,0 +1,256 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Audits of other machines over SSH: the management server runs LXRAY on each target and
5
+ * brings the reports (and optionally the raw archive) back. Nothing is installed by this code on
6
+ * the targets: LXRAY must be there, plus the root wrapper for privileged audits.
7
+ *
8
+ * Every value placed in the remote command is validated against a strict character set, so the
9
+ * remote shell never receives anything it could interpret.
10
+ *
11
+ * remoteAudit(target, options) audit and reports options.mode: 'run' (default) | 'privileged' | 'latest'
12
+ * remoteCollect(target, options) raw .tar.gz snapshot (analyze it locally with analyze())
13
+ * auditFleet(targets, options) many machines in parallel, one result per machine
14
+ */
15
+ const fs = require('node:fs/promises');
16
+ const path = require('node:path');
17
+ const { execNoShell } = require('./executor');
18
+ const { resolvePlugins } = require('./plugins');
19
+ const { REPORT_FILES, FORMATS, summarize } = require('./report');
20
+
21
+ const SAFE_HOST = /^(?!-)[A-Za-z0-9._:-]{1,253}$/;
22
+ const SAFE_USER = /^[a-z_][a-z0-9_.-]{0,31}$/i;
23
+ const SAFE_PATH = /^\/[A-Za-z0-9._/-]{1,200}$/;
24
+ const SAFE_SSH_OPTION = /^[A-Za-z]+=[A-Za-z0-9._/@:,+-]{1,200}$/;
25
+ const PROFILES = ['quick', 'standard', 'full'];
26
+
27
+ function formatsOf(options) {
28
+ let f = options.formats ?? (options.format ? [options.format] : []);
29
+ if (typeof f === 'string') f = f.split(',');
30
+ f = f.map((x) => String(x).trim().toLowerCase());
31
+ for (const x of f) if (!FORMATS.includes(x)) throw new TypeError(`Unknown format "${x}"`);
32
+ if (!f.includes('json')) f.unshift('json');
33
+ return [...new Set(f)];
34
+ }
35
+
36
+ /** run / collect flags, validated. */
37
+ function collectorFlags(options) {
38
+ const flags = [];
39
+ const only = resolvePlugins(options.only);
40
+ const exclude = resolvePlugins(options.exclude);
41
+ if (only.length) flags.push('--only', only.join(','));
42
+ if (exclude.length) flags.push('--exclude', exclude.join(','));
43
+ if (options.profile !== undefined) {
44
+ if (!PROFILES.includes(options.profile)) throw new TypeError('profile: quick, standard or full');
45
+ flags.push('--profile', options.profile);
46
+ }
47
+ if (options.timeout !== undefined) {
48
+ const t = Number(options.timeout);
49
+ if (!Number.isInteger(t) || t < 1 || t > 3600) throw new TypeError('timeout: whole seconds between 1 and 3600');
50
+ flags.push('--timeout', String(t));
51
+ }
52
+ if (options.redactIps) flags.push('--redact-ips');
53
+ if (options.noRedact) flags.push('--no-redact');
54
+ return flags;
55
+ }
56
+
57
+ function lxrayPathOf(options) {
58
+ const lxray = options.lxrayPath || 'lxray';
59
+ if (!/^[A-Za-z0-9._/-]{1,200}$/.test(lxray)) throw new TypeError('lxrayPath: invalid characters');
60
+ return lxray;
61
+ }
62
+
63
+ const SEND_FILES = (files) => `for f in ${files}; do [ -f "$r/$f" ] || continue; echo "@@FILE@@ $f"; base64 "$r/$f" | tr -d '\\n'; echo; done`;
64
+ const SEND_ARCHIVE = 'a=$(ls -1 "$d"/lxray-*.tar.gz 2>/dev/null | tail -n 1); if [ -n "$a" ]; then echo "@@ARCHIVE@@ $(basename "$a")"; base64 "$a" | tr -d \'\\n\'; echo; fi';
65
+
66
+ /** POSIX sh script run on the target. Only validated tokens are interpolated. */
67
+ function remoteScript(options, formats) {
68
+ const mode = options.mode || (options.privileged ? 'privileged' : 'run');
69
+ const files = formats.map((f) => REPORT_FILES[f]).join(' ');
70
+ if (mode === 'privileged') {
71
+ const wrapper = options.wrapperPath || '/usr/local/sbin/lxray-audit';
72
+ if (!SAFE_PATH.test(wrapper)) throw new TypeError('wrapperPath: invalid characters');
73
+ if (options.profile !== undefined && !PROFILES.includes(options.profile)) throw new TypeError('profile: quick, standard or full');
74
+ return [
75
+ 'set -e',
76
+ 'e=$(mktemp)',
77
+ `r=$(sudo -n ${wrapper} ${options.profile || 'standard'} 2>"$e" | tail -n 1) || { echo "@@ERR@@"; tail -c 2000 "$e"; rm -f "$e"; exit 3; }`,
78
+ 'rm -f "$e"',
79
+ SEND_FILES(files)
80
+ ].join('\n');
81
+ }
82
+ if (mode === 'latest') {
83
+ const spool = options.spoolDir || '/var/lib/lxray/reports';
84
+ if (!SAFE_PATH.test(spool)) throw new TypeError('spoolDir: invalid characters');
85
+ return [
86
+ 'set -e',
87
+ `d=$(ls -1d ${spool}/*/ 2>/dev/null | sort | tail -n 1) || true`,
88
+ '[ -n "$d" ] || { echo "@@ERR@@"; echo "no report in the spool (is lxray-audit.timer active? is this account in group lxray?)"; exit 3; }',
89
+ 'r=$(ls -d "$d"lxray-*/report | tail -n 1)',
90
+ 'echo "@@AGE@@ $(( $(date +%s) - $(stat -c %Y "$r/lxray-report.json") ))"',
91
+ SEND_FILES(files)
92
+ ].join('\n');
93
+ }
94
+ if (mode !== 'run') throw new TypeError('mode: run, privileged or latest');
95
+ const lxray = lxrayPathOf(options);
96
+ const flags = collectorFlags(options);
97
+ return [
98
+ 'set -e',
99
+ 'd=$(mktemp -d)',
100
+ "trap 'rm -rf \"$d\"' EXIT",
101
+ // exit 3 = partial collection (report present)
102
+ `rc=0; ${lxray} run --outdir "$d" --format ${formats.join(',')} ${options.archive ? '' : '--no-tar '}--quiet ${flags.join(' ')} >/dev/null 2>"$d/.err" || rc=$?`,
103
+ 'if [ "$rc" != 0 ] && [ "$rc" != 3 ]; then echo "@@ERR@@"; tail -c 2000 "$d/.err"; exit 3; fi',
104
+ 'echo "@@RC@@ $rc"',
105
+ 'r=$(ls -d "$d"/lxray-*/report | tail -n 1)',
106
+ SEND_FILES(files),
107
+ options.archive ? SEND_ARCHIVE : ''
108
+ ].filter(Boolean).join('\n');
109
+ }
110
+
111
+ function collectScript(options) {
112
+ const lxray = lxrayPathOf(options);
113
+ const flags = collectorFlags(options);
114
+ return [
115
+ 'set -e',
116
+ 'd=$(mktemp -d)',
117
+ "trap 'rm -rf \"$d\"' EXIT",
118
+ `rc=0; ${lxray} collect --outdir "$d" --quiet ${flags.join(' ')} >/dev/null 2>"$d/.err" || rc=$?`,
119
+ 'if [ "$rc" != 0 ] && [ "$rc" != 3 ]; then echo "@@ERR@@"; tail -c 2000 "$d/.err"; exit 3; fi',
120
+ 'echo "@@RC@@ $rc"',
121
+ SEND_ARCHIVE
122
+ ].join('\n');
123
+ }
124
+
125
+ function parseOutput(stdout, formats, { needReport = true } = {}) {
126
+ if (stdout.includes('@@ERR@@')) throw new Error(`LXRAY failed on the target: ${stdout.split('@@ERR@@')[1].trim().slice(0, 2000)}`);
127
+ const out = {};
128
+ const rc = /@@RC@@ (\d+)/.exec(stdout);
129
+ if (rc) out.partial = rc[1] === '3';
130
+ const age = /@@AGE@@ (\d+)/.exec(stdout);
131
+ if (age) out.ageMinutes = Math.round(Number(age[1]) / 60);
132
+ for (const block of stdout.split(/@@(FILE|ARCHIVE)@@ /).slice(1).reduce((acc, part, i, arr) => (i % 2 === 0 ? acc.concat([[part, arr[i + 1]]]) : acc), [])) {
133
+ const [kind, body] = block;
134
+ const nl = body.indexOf('\n');
135
+ const name = body.slice(0, nl).trim();
136
+ const data = Buffer.from(body.slice(nl + 1).split('\n')[0].trim(), 'base64');
137
+ if (kind === 'ARCHIVE') {
138
+ out.archive = data;
139
+ out.archiveName = name;
140
+ continue;
141
+ }
142
+ const content = data.toString('utf8');
143
+ const f = Object.keys(REPORT_FILES).find((k) => REPORT_FILES[k] === name);
144
+ if (f === 'json') out.report = JSON.parse(content);
145
+ else if (f === 'html') out.html = content;
146
+ else if (f === 'md') out.markdown = content;
147
+ else if (f === 'txt') out.text = content;
148
+ }
149
+ if (needReport) {
150
+ if (!out.report) throw new Error('The target returned no JSON report');
151
+ for (const f of formats) if (f !== 'json' && !({ html: 'html', md: 'markdown', txt: 'text' }[f] in out)) throw new Error(`The target returned no ${f} report`);
152
+ }
153
+ return out;
154
+ }
155
+
156
+ function sshArgs(target) {
157
+ if (!target || !SAFE_HOST.test(String(target.host || ''))) throw new TypeError('target.host: missing or invalid');
158
+ if (target.user !== undefined && !SAFE_USER.test(target.user)) throw new TypeError('target.user: invalid');
159
+ const args = ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15', '-o', 'ServerAliveInterval=30',
160
+ '-o', `StrictHostKeyChecking=${target.acceptNewHostKeys ? 'accept-new' : 'yes'}`];
161
+ if (target.port !== undefined) {
162
+ const p = Number(target.port);
163
+ if (!Number.isInteger(p) || p < 1 || p > 65535) throw new TypeError('target.port: invalid');
164
+ args.push('-p', String(p));
165
+ }
166
+ if (target.identityFile) {
167
+ if (!SAFE_PATH.test(target.identityFile) && !/^[A-Za-z]:[\\/][\w .\\/-]{1,200}$/.test(target.identityFile)) throw new TypeError('target.identityFile: invalid path');
168
+ args.push('-i', target.identityFile, '-o', 'IdentitiesOnly=yes');
169
+ }
170
+ for (const o of target.sshOptions || []) {
171
+ if (!SAFE_SSH_OPTION.test(o)) throw new TypeError(`sshOptions: refused "${o}"`);
172
+ args.push('-o', o);
173
+ }
174
+ args.push('--', target.user ? `${target.user}@${target.host}` : target.host);
175
+ return args;
176
+ }
177
+
178
+ /**
179
+ * Audits one machine over SSH (key authentication, no password prompts).
180
+ * @param {object} target { host, user?, port?, identityFile?, sshOptions?, acceptNewHostKeys? }
181
+ * @param {object} [options] audit options (formats, profile, only, exclude, timeout, redactIps, noRedact),
182
+ * plus mode: 'run' | 'privileged' (root wrapper via sudo) | 'latest' (newest hourly root report),
183
+ * archive (bring the .tar.gz back as a Buffer, mode run), wrapperPath, spoolDir, lxrayPath, sshPath, processTimeout
184
+ */
185
+ async function remoteAudit(target, options = {}) {
186
+ const started = Date.now();
187
+ const formats = formatsOf(options);
188
+ const args = [...sshArgs(target), remoteScript(options, formats)];
189
+ const { stdout } = await execNoShell(options.sshPath || 'ssh', args, { timeout: options.processTimeout ?? 900000, maxBuffer: 256 * 1024 * 1024 });
190
+ const files = parseOutput(stdout, formats);
191
+ const mode = options.mode || (options.privileged ? 'privileged' : 'run');
192
+ return { host: target.host, mode, summary: summarize(files.report), ...files, partial: files.partial ?? false, durationMs: Date.now() - started, privileged: mode !== 'run' };
193
+ }
194
+
195
+ /**
196
+ * Collects a raw snapshot on a remote machine and brings the .tar.gz back
197
+ * (to analyze locally with analyze(), or to archive). Never runs the analysis remotely.
198
+ * @param {object} target
199
+ * @param {object} [options] only, exclude, profile, timeout, redactIps, noRedact, saveTo (folder), lxrayPath, processTimeout
200
+ * @returns {Promise<{ host: string, archive: Buffer, archiveName: string, savedTo?: string, partial: boolean }>}
201
+ */
202
+ async function remoteCollect(target, options = {}) {
203
+ const args = [...sshArgs(target), collectScript(options)];
204
+ const { stdout } = await execNoShell(options.sshPath || 'ssh', args, { timeout: options.processTimeout ?? 900000, maxBuffer: 512 * 1024 * 1024 });
205
+ const out = parseOutput(stdout, [], { needReport: false });
206
+ if (!out.archive) throw new Error('The target returned no archive');
207
+ const res = { host: target.host, archive: out.archive, archiveName: out.archiveName, partial: out.partial ?? false };
208
+ if (options.saveTo) {
209
+ await fs.mkdir(path.resolve(options.saveTo), { recursive: true, mode: 0o750 });
210
+ res.savedTo = path.join(path.resolve(options.saveTo), path.basename(out.archiveName));
211
+ await fs.writeFile(res.savedTo, out.archive, { mode: 0o640 });
212
+ }
213
+ return res;
214
+ }
215
+
216
+ /**
217
+ * Audits many machines in parallel (a few at a time). Never throws for one failing machine:
218
+ * each entry says ok: true with the result, or ok: false with the error.
219
+ * A target { local: true } audits this machine with audit() (or readLatest() / requestRootAudit() with mode).
220
+ * @param {Array<object>} targets each may carry its own `options`
221
+ * @param {object} [options] shared audit options, plus concurrency (default 4) and onResult(entry, index)
222
+ * @returns {Promise<Array<{ host: string, ok: boolean, result?: object, error?: string, code?: string|null }>>}
223
+ */
224
+ async function auditFleet(targets, options = {}) {
225
+ if (!Array.isArray(targets) || targets.length === 0) throw new TypeError('auditFleet() needs a non-empty array of targets');
226
+ const concurrency = Math.max(1, Math.min(Number(options.concurrency) || 4, 32));
227
+ const { concurrency: _c, onResult, ...shared } = options;
228
+ const results = new Array(targets.length);
229
+ let next = 0;
230
+ const local = (opts) => {
231
+ const lx = require('./index');
232
+ if (opts.mode === 'latest') return lx.readLatest(opts);
233
+ if (opts.mode === 'root') return lx.requestRootAudit(opts);
234
+ return lx.audit({ ...opts, privileged: opts.mode === 'privileged' || opts.privileged });
235
+ };
236
+ const worker = async () => {
237
+ while (next < targets.length) {
238
+ const i = next++;
239
+ const t = targets[i];
240
+ const host = t.local ? 'localhost' : t.host;
241
+ const opts = { ...shared, ...(t.options || {}) };
242
+ try {
243
+ results[i] = { host, ok: true, result: t.local ? await local(opts) : await remoteAudit(t, opts) };
244
+ } catch (e) {
245
+ results[i] = { host, ok: false, error: e.message, code: e.code ?? null };
246
+ }
247
+ if (typeof onResult === 'function') {
248
+ try { onResult(results[i], i); } catch { /* caller's callback errors are ignored */ }
249
+ }
250
+ }
251
+ };
252
+ await Promise.all(Array.from({ length: Math.min(concurrency, targets.length) }, worker));
253
+ return results;
254
+ }
255
+
256
+ module.exports = { remoteAudit, remoteCollect, auditFleet, remoteScript };
package/src/report.js ADDED
@@ -0,0 +1,118 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs/promises');
4
+ const path = require('node:path');
5
+
6
+ /** File names written by the LXRAY 1.2.0 analyzer. */
7
+ const REPORT_FILES = Object.freeze({
8
+ json: 'lxray-report.json',
9
+ html: 'lxray-report.html',
10
+ md: 'lxray-report.md',
11
+ txt: 'lxray-summary.txt'
12
+ });
13
+
14
+ const FORMATS = Object.freeze(Object.keys(REPORT_FILES));
15
+ const SEVERITY_ORDER = Object.freeze(['critical', 'warning', 'info', 'ok']);
16
+
17
+ /** Newest `lxray-<host>-<time>` snapshot folder directly under `outdir` (null if none). */
18
+ async function findSnapshotDir(outdir) {
19
+ let entries;
20
+ try {
21
+ entries = await fs.readdir(outdir, { withFileTypes: true });
22
+ } catch {
23
+ return null;
24
+ }
25
+ const dirs = entries.filter((d) => d.isDirectory() && /^(lxray|lxdiag)-/.test(d.name)).map((d) => d.name).sort();
26
+ return dirs.length ? path.join(outdir, dirs[dirs.length - 1]) : null;
27
+ }
28
+
29
+ /** Newest `lxray-<host>-<time>.tar.gz` directly under `outdir` (null if none). */
30
+ async function findArchive(outdir) {
31
+ try {
32
+ const files = (await fs.readdir(outdir)).filter((f) => /^(lxray|lxdiag)-.*\.tar\.gz$/.test(f)).sort();
33
+ return files.length ? path.join(outdir, files[files.length - 1]) : null;
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Folder holding the report files: `<snapshot>/report` after `lxray run`,
41
+ * or the `--outdir` itself after `lxray analyze --outdir`.
42
+ */
43
+ async function findReportDir(outdir) {
44
+ const candidates = [];
45
+ const snap = await findSnapshotDir(outdir);
46
+ if (snap) candidates.push(path.join(snap, 'report'), snap);
47
+ candidates.push(path.join(outdir, 'report'), outdir);
48
+ for (const dir of candidates) {
49
+ try {
50
+ const files = await fs.readdir(dir);
51
+ if (Object.values(REPORT_FILES).some((f) => files.includes(f))) return dir;
52
+ } catch {
53
+ // next candidate
54
+ }
55
+ }
56
+ return null;
57
+ }
58
+
59
+ /**
60
+ * Reads the requested report formats from a report folder.
61
+ * @param {string} dir
62
+ * @param {string[]} formats
63
+ */
64
+ async function readReports(dir, formats) {
65
+ const out = {};
66
+ for (const f of formats) {
67
+ const p = path.join(dir, REPORT_FILES[f]);
68
+ let content;
69
+ try {
70
+ content = await fs.readFile(p, 'utf8');
71
+ } catch (e) {
72
+ if (e.code === 'ENOENT') throw new Error(`LXRAY finished but ${REPORT_FILES[f]} is missing in ${dir}`);
73
+ throw e;
74
+ }
75
+ if (f === 'json') {
76
+ try {
77
+ out.report = JSON.parse(content);
78
+ } catch (e) {
79
+ throw new Error(`Invalid JSON in ${p}: ${e.message}`);
80
+ }
81
+ } else if (f === 'html') out.html = content;
82
+ else if (f === 'md') out.markdown = content;
83
+ else out.text = content;
84
+ }
85
+ return out;
86
+ }
87
+
88
+ /**
89
+ * Compact view of an LXRAY JSON report: score, grade, counts per severity and the
90
+ * findings to act on (severity order: critical, warning, info; "ok" checks left out).
91
+ * @param {object} report parsed lxray-report.json
92
+ */
93
+ function summarize(report) {
94
+ if (!report || typeof report !== 'object' || !Array.isArray(report.findings)) {
95
+ throw new TypeError('summarize() expects a parsed lxray-report.json (with a findings array)');
96
+ }
97
+ const facts = report.facts || {};
98
+ const host = report.host || {};
99
+ const counts = { critical: 0, warning: 0, info: 0, ok: 0 };
100
+ for (const f of report.findings) counts[f.severity] = (counts[f.severity] || 0) + 1;
101
+ const issues = report.findings
102
+ .filter((f) => f.severity !== 'ok')
103
+ .sort((a, b) => SEVERITY_ORDER.indexOf(a.severity) - SEVERITY_ORDER.indexOf(b.severity));
104
+ return {
105
+ hostname: host.hostname ?? null,
106
+ os: host.os_name ?? null,
107
+ kernel: host.kernel ?? null,
108
+ lxrayVersion: report.version ?? null,
109
+ generated: report.generated ?? null,
110
+ score: typeof facts.score === 'number' ? facts.score : null,
111
+ grade: facts.grade ?? null,
112
+ verdict: facts.verdict ?? null,
113
+ counts,
114
+ issues: issues.map((f) => ({ id: f.id, severity: f.severity, category: f.category, title: f.title, detail: f.detail, fix: f.fix, impact: f.impact }))
115
+ };
116
+ }
117
+
118
+ module.exports = { REPORT_FILES, FORMATS, SEVERITY_ORDER, findSnapshotDir, findArchive, findReportDir, readReports, summarize };