@ejouan/lxray 0.0.0-stage → 1.2.1

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.
package/LICENSE ADDED
@@ -0,0 +1,43 @@
1
+ LXRAY - FREE USE LICENSE
2
+
3
+ Copyright (c) 2026 El Mehdi Jouan. All rights reserved.
4
+
5
+ 1. GRANT
6
+ You may install and use LXRAY free of charge, for personal, educational and
7
+ commercial purposes, on any number of machines that you own or administer.
8
+
9
+ 2. RESTRICTIONS
10
+ You may not:
11
+ (a) modify, translate, adapt or create derivative works of LXRAY;
12
+ (b) reverse engineer, decompile, extract or publish the code of LXRAY, except
13
+ to the extent that applicable law expressly allows despite this restriction;
14
+ (c) sell, rent, lease, sublicense or redistribute LXRAY, except that you may
15
+ pass on the original, unmodified packages obtained from an official source
16
+ (https://jouan.us/upstream/ or https://github.com/eljouan/lxray), together
17
+ with this license;
18
+ (d) remove or alter any copyright notice or this license.
19
+
20
+ 3. SOURCE CODE
21
+ No source code is provided or licensed. The code of LXRAY remains the exclusive
22
+ property of the author.
23
+
24
+ 4. DATA
25
+ LXRAY runs locally. It does not contact the Internet and sends no data to the
26
+ author or to anyone else. Reports stay on the machine where they are created.
27
+
28
+ 5. OWNERSHIP
29
+ LXRAY is licensed, not sold. All rights not expressly granted in this license
30
+ are reserved by the author.
31
+
32
+ 6. NO WARRANTY
33
+ LXRAY IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
34
+ INCLUDING THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
35
+ AND NON-INFRINGEMENT.
36
+
37
+ 7. LIMITATION OF LIABILITY
38
+ IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
39
+ LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH LXRAY OR ITS USE.
40
+
41
+ 8. TERMINATION
42
+ This license ends automatically if you breach any of its terms. On termination
43
+ you must stop using LXRAY and delete your copies.
package/README.md CHANGED
@@ -1,3 +1,182 @@
1
- # Temporary Holding Version
1
+ # @ejouan/lxray
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Node.js SDK for **LXRAY**, the X-ray for Linux servers. Run LXRAY audits from your own application
4
+ (monitoring platform, management console, managed-services portal, internal tool) and get a scored
5
+ report with the evidence and the fix for every finding: on one machine, as root on demand without your
6
+ app being root, or over SSH across a whole fleet.
7
+
8
+ - Zero dependencies. Audits run on Linux (the package installs anywhere, so you can develop on Windows or macOS). Node.js 18 or later. Python 3.6+ on the audited machine (for the analysis).
9
+ - No shell is ever spawned with your values: no command injection, locally or over SSH.
10
+ - Reports stay on your infrastructure: LXRAY contacts nobody.
11
+
12
+ LXRAY itself is installed from the signed repositories at https://jouan.us/upstream/packages
13
+ (apt, dnf, zypper) or with `install()` (user-space copy, GPG-verified).
14
+
15
+ ```bash
16
+ npm install @ejouan/lxray
17
+ ```
18
+
19
+ ## Quick start
20
+
21
+ ```js
22
+ const lxray = require('@ejouan/lxray');
23
+
24
+ const { summary, html } = await lxray.audit({ profile: 'standard', formats: ['json', 'html'] });
25
+ console.log(`${summary.hostname}: ${summary.score}/100 (${summary.grade}) ${summary.verdict}`);
26
+ for (const f of summary.issues) console.log(`[${f.severity}] ${f.title} -> ${f.fix}`);
27
+ ```
28
+
29
+ `summary` is built from `lxray-report.json`:
30
+
31
+ | Field | Meaning |
32
+ |---|---|
33
+ | `score`, `grade`, `verdict` | health score 0-100, letter A-F, sentence |
34
+ | `counts` | `{ critical, warning, info, ok }` |
35
+ | `issues` | findings to act on, critical first (`ok` checks left out): `id, severity, category, title, detail, fix, impact` |
36
+
37
+ The full report is in `result.report` (`tool, version, generated, host, manifest, facts, findings`).
38
+ `result.html`, `result.markdown` and `result.text` hold the other formats when requested.
39
+
40
+ ## Root access: complete reports without giving root to your app
41
+
42
+ Without root, LXRAY reads what the account can read and lists the checks it could not evaluate
43
+ (`result.partial === true`, the report says how many). Installing an npm package can never grant root,
44
+ and it should not. An administrator grants it **once**, narrowly:
45
+
46
+ ```bash
47
+ npx lxray-setup-root <app-account> # prints the commands, runs nothing
48
+ ```
49
+
50
+ | Mode | Call | What the admin installs once | Your app's rights |
51
+ |---|---|---|---|
52
+ | Unprivileged (default) | `audit()` | nothing | its own account |
53
+ | Root on demand, no sudo | `requestRootAudit({ profile })` | root wrapper + systemd path unit; app account in group `lxray` | writes a request file, reads reports |
54
+ | Root every hour | `readLatest({ maxAgeMinutes: 90 })` | root wrapper + systemd timer | reads reports |
55
+ | Root through sudo | `audit({ privileged: true, profile })` | root wrapper + one sudoers line for that wrapper only | may run that wrapper only |
56
+
57
+ The root wrapper (`setup/lxray-audit`, about 30 lines, read it) accepts a profile and nothing else, writes
58
+ into `/var/lib/lxray/reports` (group `lxray`, no access for others) and keeps the 20 newest audits.
59
+
60
+ ## Fleets: many servers over SSH
61
+
62
+ ```js
63
+ const results = await lxray.auditFleet([
64
+ { host: 'web01.example', user: 'audit', identityFile: '/etc/myapp/keys/audit' },
65
+ { host: 'db01.example', user: 'audit', identityFile: '/etc/myapp/keys/audit', options: { profile: 'full' } },
66
+ { local: true }
67
+ ], { concurrency: 4, profile: 'standard', privileged: true, onResult: (e) => console.log(e.host, e.ok) });
68
+
69
+ for (const r of results) {
70
+ if (r.ok) console.log(r.host, r.result.summary.score);
71
+ else console.error(r.host, r.error);
72
+ }
73
+ ```
74
+
75
+ - Key authentication only (`BatchMode=yes`), host keys checked (`acceptNewHostKeys: true` to accept unknown hosts once).
76
+ - LXRAY must be installed on each target (and the root wrapper + sudo rule for `privileged: true`).
77
+ - One failing machine never fails the batch. `remoteAudit(target, options)` audits a single machine.
78
+
79
+ ## HTTP endpoint (Express, Connect, node:http)
80
+
81
+ ```js
82
+ app.use('/internal/lxray', lxray.createAuditHandler({
83
+ authorize: (req) => req.get('authorization') === `Bearer ${process.env.LXRAY_TOKEN}`, // required
84
+ source: 'latest', // 'audit' | 'privileged' | 'latest'
85
+ auditOptions: { maxAgeMinutes: 120 },
86
+ rateLimitMax: 3
87
+ }));
88
+ // GET ?format=summary | json | html | md | txt | status | archive
89
+ ```
90
+
91
+ `authorize` is mandatory. One audit runs at a time. The rate limit is keyed on the socket address
92
+ (set `trustProxy: true` behind a proxy you control). HTML reports are served with a sandbox CSP.
93
+ Raw archives (`?format=archive`) are off unless `allowArchive: true`: they contain raw system data.
94
+
95
+ ## Monitoring integration
96
+
97
+ Everything a monitoring or management tool needs, in code:
98
+
99
+ ```js
100
+ // thresholds -> OK / WARNING / CRITICAL (exit codes 0/1/2, Nagios, Icinga, Zabbix, Centreon...)
101
+ const check = lxray.evaluate(result, { minScore: 60, warnScore: 80, maxCritical: 0, ignore: ['SSH-ROOT'], partialIsWarning: true });
102
+ console.log(check.message); process.exitCode = check.exitCode;
103
+
104
+ // tracking over time: what changed since the previous audit
105
+ const diff = lxray.compare(previousResult, result);
106
+ // { scoreDelta, newIssues, resolved, worse, better, persisting }
107
+
108
+ // Prometheus / Grafana (one audit, or an auditFleet() array as is)
109
+ res.type('text/plain').send(lxray.toPrometheus(fleetResults, { labels: { env: 'prod' } }));
110
+ // lxray_up, lxray_score{host,grade}, lxray_findings{host,severity}, lxray_partial, lxray_audit_duration_seconds, lxray_report_timestamp_seconds
111
+
112
+ // live progress while LXRAY runs
113
+ await lxray.audit({ onLog: (line) => socket.emit('lxray', line) });
114
+
115
+ // keep the reports as files
116
+ await lxray.saveReports(result, '/srv/audits/web01', { prefix: '2026-11-25' });
117
+
118
+ // what LXRAY can use on this machine, and the packages to add (install: true needs root)
119
+ const { missingPackages, installCommand } = await lxray.deps();
120
+ ```
121
+
122
+ The HTTP handler also answers `?format=metrics` (Prometheus scrape target) and `?format=check`
123
+ (`checkRules`; with `checkHttpStatus: true` a CRITICAL state answers 503 for HTTP probes).
124
+
125
+ Remote machines:
126
+
127
+ ```js
128
+ await lxray.remoteAudit(target, { mode: 'latest' }); // newest hourly root report, instant
129
+ await lxray.remoteAudit(target, { mode: 'privileged', profile: 'full' }); // root wrapper via sudo
130
+ await lxray.remoteAudit(target, { archive: true }); // + result.archive (Buffer, .tar.gz)
131
+ const { savedTo } = await lxray.remoteCollect(target, { saveTo: '/srv/snapshots' });
132
+ await lxray.analyze(savedTo); // analyze on the management server
133
+ ```
134
+
135
+ ## API
136
+
137
+ | Function | Returns |
138
+ |---|---|
139
+ | `audit(options)` (alias `run`) | `{ summary, report, html?, markdown?, text?, partial, durationMs, warnings, outdir?, archivePath? }` |
140
+ | `requestRootAudit({ profile, waitMs })` | same, from a root audit run by systemd |
141
+ | `readLatest({ spoolDir, maxAgeMinutes })` | same, newest root report |
142
+ | `collect(options)` | `{ outdir, snapshotDir, archivePath, partial }` raw snapshot, yours to delete |
143
+ | `analyze(pathToSnapshotOrTarGz, options)` | same as `audit()`, for a snapshot from another machine |
144
+ | `remoteAudit(target, options)` / `auditFleet(targets, options)` | see Fleets |
145
+ | `plugins()`, `version()`, `deps()`, `checkEnvironment()` | installed plugins, version, tools present/missing, what this machine offers |
146
+ | `evaluate(result, rules)`, `compare(a, b)`, `toPrometheus(x)`, `saveReports(result, dir)` | monitoring helpers (see above) |
147
+ | `remoteCollect(target, options)` | raw snapshot of a remote machine, as a Buffer or saved to a folder |
148
+ | `install({ version, installDir })` | user-space LXRAY, GPG signature and key fingerprint checked |
149
+ | `summarize(report)`, `resolvePlugins(names)` | helpers |
150
+
151
+ Audit options:
152
+
153
+ | Option | Default | |
154
+ |---|---|---|
155
+ | `formats` | `['json']` | any of `json`, `html`, `md`, `txt` (JSON always included) |
156
+ | `profile` | LXRAY's `standard` | `quick` (skips packages, databases, containers), `standard`, `full` |
157
+ | `only`, `exclude` | all | plugin ids (`70-security`) or aliases (`security`, `firewall`, `storage`...) |
158
+ | `timeout` | profile's | per-command collector timeout, seconds |
159
+ | `redactIps` / `noRedact` | false / false | mask IPs / keep secrets unmasked (masked by default) |
160
+ | `archive`, `keepArtifacts`, `outdir` | off | keep the .tar.gz / the output folder |
161
+ | `privileged`, `wrapperPath` | off | root through sudo and the wrapper |
162
+ | `autoInstall`, `binaryPath`, `processTimeout` | off, auto, 600000 ms | |
163
+ | `onLog(line, stream)` | none | progress lines while LXRAY runs |
164
+
165
+ Plugins: `00-system` (system), `05-raw` (raw), `10-cpu-memory` (cpu_memory), `20-storage` (storage),
166
+ `30-network` (network), `40-kernel` (kernel), `50-services` (services), `60-packages` (packages),
167
+ `70-security` (security), `80-logs` (logs), `85-databases` (databases), `90-containers` (containers),
168
+ `95-appstack` (applications). `firewall` selects network + security.
169
+
170
+ Errors carry a `code`: `LXRAY_NOT_FOUND`, `LXRAY_EXIT`, `LXRAY_TIMEOUT`, `LXRAY_PRIVILEGE_DENIED`,
171
+ `LXRAY_NO_SPOOL`, `LXRAY_NO_REPORT`, `LXRAY_STALE`.
172
+
173
+ ## Tests
174
+
175
+ ```bash
176
+ npm test # SDK against a stand-in that reproduces LXRAY 1.2.0 exactly
177
+ npm run test:integration # against the real LXRAY installed on the machine
178
+ ```
179
+
180
+ ## License
181
+
182
+ Free use, all rights reserved: see LICENSE. Made by El Mehdi Jouan, https://jouan.us
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /**
4
+ * Prints (never runs) the commands an administrator runs ONCE so that an application can get
5
+ * complete root LXRAY reports without having root rights itself.
6
+ * npx lxray-setup-root [app-account]
7
+ */
8
+ const path = require('node:path');
9
+ const user = process.argv[2] || process.env.USER || '<app-account>';
10
+ if (!/^[a-z_][a-z0-9_.-]{0,31}$/i.test(user) && user !== '<app-account>') { console.error('invalid account name'); process.exit(2); }
11
+ const setup = path.join(__dirname, '..', 'setup');
12
+ console.log(`# Run as root, once. Read each file first: they are short.
13
+ # 1. LXRAY itself (if missing): https://jouan.us/upstream/packages (apt / dnf / zypper)
14
+ # 2. Group shared by the root audits and the application:
15
+ groupadd --system lxray 2>/dev/null || true
16
+ usermod -aG lxray ${user}
17
+ # 3. Root wrapper (only accepts a profile) and request handler:
18
+ install -m 755 -o root -g root ${setup}/lxray-audit /usr/local/sbin/lxray-audit
19
+ install -m 755 -o root -g root ${setup}/lxray-audit-requests /usr/local/sbin/lxray-audit-requests
20
+ install -d -m 2750 -o root -g lxray /var/lib/lxray /var/lib/lxray/reports
21
+ install -d -m 2770 -o root -g lxray /var/lib/lxray/requests
22
+ # 4. Choose one or more:
23
+ # (a) on demand, no sudo: lxray.requestRootAudit()
24
+ install -m 644 ${setup}/lxray-audit-request.path ${setup}/lxray-audit-request.service /etc/systemd/system/
25
+ # (b) every hour: lxray.readLatest()
26
+ install -m 644 ${setup}/lxray-audit.service ${setup}/lxray-audit.timer /etc/systemd/system/
27
+ systemctl daemon-reload
28
+ systemctl enable --now lxray-audit-request.path lxray-audit.timer
29
+ # (c) sudo instead of systemd: lxray.audit({ privileged: true })
30
+ # echo '${user} ALL=(root) NOPASSWD: /usr/local/sbin/lxray-audit' > /etc/sudoers.d/lxray-audit && chmod 440 /etc/sudoers.d/lxray-audit && visudo -cf /etc/sudoers.d/lxray-audit
31
+ # 5. Restart the application so that its account picks up the lxray group.`);
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@ejouan/lxray",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.2.1",
4
+ "description": "Node.js SDK for LXRAY, the X-ray for Linux servers: run audits from your application (local, root on demand, or over SSH across a fleet) and get scored reports with the fix for every finding.",
5
+ "main": "src/index.js",
6
+ "types": "types/index.d.ts",
7
+ "bin": {
8
+ "lxray-setup-root": "bin/lxray-setup-root.js"
9
+ },
10
+ "files": [
11
+ "src",
12
+ "types",
13
+ "bin",
14
+ "setup",
15
+ "README.md",
16
+ "LICENSE"
17
+ ],
18
+ "engines": {
19
+ "node": ">=18.0.0"
20
+ },
21
+ "scripts": {
22
+ "test": "node --test test/sdk.test.js test/monitoring.test.js",
23
+ "test:integration": "LXRAY_INTEGRATION=1 node --test test/integration.test.js"
24
+ },
25
+ "keywords": [
26
+ "linux",
27
+ "audit",
28
+ "diagnostics",
29
+ "server",
30
+ "monitoring",
31
+ "sosreport",
32
+ "infrastructure",
33
+ "security",
34
+ "health-check",
35
+ "sre",
36
+ "sysadmin",
37
+ "lxray"
38
+ ],
39
+ "author": "El Mehdi Jouan (https://jouan.us)",
40
+ "license": "SEE LICENSE IN LICENSE",
41
+ "homepage": "https://jouan.us/upstream/en/lxray/",
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "https://github.com/eljouan/lxray.git"
45
+ },
46
+ "bugs": {
47
+ "url": "https://github.com/eljouan/lxray/issues"
48
+ },
49
+ "readme": "README.md"
50
+ }
@@ -0,0 +1,26 @@
1
+ #!/bin/bash
2
+ # lxray-audit: complete (root) LXRAY audit for applications that must not have root rights.
3
+ # Installed once by an administrator in /usr/local/sbin, owned by root, mode 755.
4
+ # lxray-audit [quick|standard|full]
5
+ # Writes the reports into /var/lib/lxray/reports/<stamp>/ (group "lxray", no access for others),
6
+ # keeps the 20 newest audits, and prints the report folder on the last line.
7
+ set -euo pipefail
8
+ export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
9
+ PROFILE="${1:-standard}"
10
+ case "$PROFILE" in quick|standard|full) ;; *) echo "lxray-audit: profile must be quick, standard or full" >&2; exit 2 ;; esac
11
+ SPOOL=/var/lib/lxray/reports
12
+ GROUP=lxray
13
+ KEEP=20
14
+ [ "$(id -u)" = 0 ] || { echo "lxray-audit: must run as root" >&2; exit 1; }
15
+ getent group "$GROUP" >/dev/null || { echo "lxray-audit: group $GROUP missing" >&2; exit 1; }
16
+ umask 027
17
+ install -d -m 2750 -o root -g "$GROUP" /var/lib/lxray "$SPOOL"
18
+ OUT="$SPOOL/$(date -u +%Y%m%d-%H%M%S)-$$"
19
+ install -d -m 2750 -o root -g "$GROUP" "$OUT"
20
+ lxray run --outdir "$OUT" --profile "$PROFILE" --format html,md,json,txt --no-tar --quiet >/dev/null 2>"$OUT/lxray-audit.err" || { tail -c 2000 "$OUT/lxray-audit.err" >&2; exit 3; }
21
+ REPORT=$(ls -d "$OUT"/lxray-*/report | tail -n 1)
22
+ chgrp -R "$GROUP" "$OUT"
23
+ chmod -R g+rX,o-rwx "$OUT"
24
+ # keep the newest audits only (this folder belongs to lxray-audit)
25
+ ls -1d "$SPOOL"/*/ 2>/dev/null | sort | head -n "-$KEEP" | while read -r old; do rm -rf -- "$old"; done
26
+ echo "$REPORT"
@@ -0,0 +1,10 @@
1
+ [Unit]
2
+ Description=Run a root LXRAY audit when an application asks for one
3
+
4
+ [Path]
5
+ PathExistsGlob=/var/lib/lxray/requests/*.request
6
+ MakeDirectory=yes
7
+ DirectoryMode=2770
8
+
9
+ [Install]
10
+ WantedBy=multi-user.target
@@ -0,0 +1,9 @@
1
+ [Unit]
2
+ Description=Root LXRAY audit requested by an application
3
+
4
+ [Service]
5
+ Type=oneshot
6
+ ExecStart=/usr/local/sbin/lxray-audit-requests
7
+ Nice=10
8
+ IOSchedulingClass=idle
9
+ TimeoutStartSec=30min
@@ -0,0 +1,13 @@
1
+ #!/bin/bash
2
+ # Started by lxray-audit-request.path when an application drops <profile>.request into
3
+ # /var/lib/lxray/requests (group lxray, writable). Each request runs one root audit.
4
+ set -euo pipefail
5
+ export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
6
+ REQ=/var/lib/lxray/requests
7
+ shopt -s nullglob
8
+ for f in "$REQ"/*.request; do
9
+ name=$(basename "$f" .request)
10
+ rm -f -- "$f"
11
+ case "$name" in quick|standard|full) /usr/local/sbin/lxray-audit "$name" >/dev/null || logger -t lxray-audit "audit $name failed" ;;
12
+ *) logger -t lxray-audit "ignored request $name" ;; esac
13
+ done
@@ -0,0 +1,9 @@
1
+ [Unit]
2
+ Description=Scheduled root LXRAY audit (report in /var/lib/lxray/reports)
3
+
4
+ [Service]
5
+ Type=oneshot
6
+ ExecStart=/usr/local/sbin/lxray-audit standard
7
+ Nice=10
8
+ IOSchedulingClass=idle
9
+ TimeoutStartSec=30min
@@ -0,0 +1,11 @@
1
+ [Unit]
2
+ Description=Hourly root LXRAY audit
3
+
4
+ [Timer]
5
+ OnBootSec=10min
6
+ OnUnitActiveSec=1h
7
+ RandomizedDelaySec=5min
8
+ Persistent=true
9
+
10
+ [Install]
11
+ WantedBy=timers.target
@@ -0,0 +1,160 @@
1
+ 'use strict';
2
+
3
+ const { execFile, spawn } = require('node:child_process');
4
+ const { access, constants } = require('node:fs/promises');
5
+ const path = require('node:path');
6
+ const os = require('node:os');
7
+
8
+ /** Where LXRAY is looked for, in order (after options.binaryPath and LXRAY_PATH / LXDIAG_PATH). */
9
+ const DEFAULT_CANDIDATES = Object.freeze([
10
+ '/usr/local/bin/lxray',
11
+ '/usr/bin/lxray',
12
+ '/opt/lxray/bin/lxray',
13
+ path.join(os.homedir(), '.local/share/lxray/bin/lxray'),
14
+ // installations made before LXRAY 1.1 (command named lxdiag)
15
+ '/usr/local/bin/lxdiag',
16
+ '/opt/lxdiag/bin/lxdiag'
17
+ ]);
18
+
19
+ async function isExecutable(p) {
20
+ try {
21
+ await access(p, constants.X_OK);
22
+ return true;
23
+ } catch {
24
+ return false;
25
+ }
26
+ }
27
+
28
+ /** Searches $PATH without spawning `which` (absent from minimal images). */
29
+ async function findInPath(name) {
30
+ for (const dir of String(process.env.PATH || '').split(path.delimiter)) {
31
+ if (!dir) continue;
32
+ const p = path.join(dir, name);
33
+ if (await isExecutable(p)) return p;
34
+ }
35
+ return null;
36
+ }
37
+
38
+ /**
39
+ * Finds the `lxray` executable.
40
+ * Order: options.binaryPath, LXRAY_PATH, LXDIAG_PATH, `lxray` in $PATH, standard paths, `lxdiag`.
41
+ * @param {string} [customPath]
42
+ * @returns {Promise<string>}
43
+ */
44
+ async function resolveBinary(customPath) {
45
+ const explicit = customPath || process.env.LXRAY_PATH || process.env.LXDIAG_PATH;
46
+ if (explicit) {
47
+ if (await isExecutable(explicit)) return explicit;
48
+ throw new Error(`LXRAY binary not executable: ${explicit}`);
49
+ }
50
+ const inPath = (await findInPath('lxray')) || null;
51
+ if (inPath) return inPath;
52
+ for (const c of DEFAULT_CANDIDATES) if (await isExecutable(c)) return c;
53
+ const legacy = await findInPath('lxdiag');
54
+ if (legacy) return legacy;
55
+ const err = new Error(
56
+ 'LXRAY is not installed on this machine. Install it from https://jouan.us/upstream/packages ' +
57
+ '(apt, dnf, zypper), set LXRAY_PATH, or call lxray.install() for a user-space copy.'
58
+ );
59
+ err.code = 'LXRAY_NOT_FOUND';
60
+ throw err;
61
+ }
62
+
63
+ /**
64
+ * Runs a program without a shell (arguments are never interpreted: no command injection).
65
+ * @returns {Promise<{stdout: string, stderr: string, code: number}>}
66
+ */
67
+ function execNoShell(file, args, opts = {}) {
68
+ return new Promise((resolve, reject) => {
69
+ execFile(file, args, {
70
+ timeout: opts.timeout ?? 600000,
71
+ killSignal: 'SIGKILL',
72
+ maxBuffer: opts.maxBuffer ?? 64 * 1024 * 1024,
73
+ cwd: opts.cwd,
74
+ env: opts.env ? { ...process.env, ...opts.env } : process.env,
75
+ encoding: opts.encoding ?? 'utf8',
76
+ windowsHide: true
77
+ }, (error, stdout, stderr) => {
78
+ // some exit codes are results, not failures (lxray: 3 = partial collection, report still written)
79
+ if (error && !error.killed && typeof error.code === 'number' && (opts.okExitCodes || []).includes(error.code)) {
80
+ return resolve({ stdout, stderr, code: error.code });
81
+ }
82
+ if (error) {
83
+ const e = new Error(error.killed
84
+ ? `${path.basename(file)} ${args[0] ?? ''} was stopped after ${(opts.timeout ?? 600000) / 1000}s (timeout)`
85
+ : `${path.basename(file)} ${args[0] ?? ''} failed (exit ${error.code}): ${String(stderr || error.message).trim().slice(-2000)}`);
86
+ e.code = error.killed ? 'LXRAY_TIMEOUT' : 'LXRAY_EXIT';
87
+ e.exitCode = typeof error.code === 'number' ? error.code : null;
88
+ e.stdout = stdout;
89
+ e.stderr = stderr;
90
+ return reject(e);
91
+ }
92
+ resolve({ stdout, stderr, code: 0 });
93
+ });
94
+ });
95
+ }
96
+
97
+ /**
98
+ * Like execNoShell, but calls onLine(line, stream) for every output line as it comes (progress).
99
+ */
100
+ function execStream(file, args, opts = {}) {
101
+ return new Promise((resolve, reject) => {
102
+ const child = spawn(file, args, { cwd: opts.cwd, env: opts.env ? { ...process.env, ...opts.env } : process.env, shell: false, windowsHide: true });
103
+ let stdout = '', stderr = '', killed = false;
104
+ const timeout = opts.timeout ?? 600000;
105
+ const timer = setTimeout(() => { killed = true; child.kill('SIGKILL'); }, timeout);
106
+ const feed = (stream) => {
107
+ let buf = '';
108
+ return (chunk) => {
109
+ const s = chunk.toString('utf8');
110
+ if (stream === 'stdout') stdout += s; else stderr += s;
111
+ buf += s;
112
+ const lines = buf.split(/\r?\n/);
113
+ buf = lines.pop();
114
+ for (const l of lines) {
115
+ const clean = l.replace(/\x1b\[[0-9;]*[A-Za-z]/g, '');
116
+ if (clean.trim()) { try { opts.onLine(clean, stream); } catch { /* caller errors ignored */ } }
117
+ }
118
+ };
119
+ };
120
+ child.stdout.on('data', feed('stdout'));
121
+ child.stderr.on('data', feed('stderr'));
122
+ child.on('error', (e) => { clearTimeout(timer); reject(e); });
123
+ child.on('close', (code) => {
124
+ clearTimeout(timer);
125
+ if (killed) return reject(Object.assign(new Error(`${path.basename(file)} ${args[0] ?? ''} was stopped after ${timeout / 1000}s (timeout)`), { code: 'LXRAY_TIMEOUT', stdout, stderr }));
126
+ if (code === 0 || (opts.okExitCodes || []).includes(code)) return resolve({ stdout, stderr, code });
127
+ reject(Object.assign(new Error(`${path.basename(file)} ${args[0] ?? ''} failed (exit ${code}): ${stderr.trim().slice(-2000)}`), { code: 'LXRAY_EXIT', exitCode: code, stdout, stderr }));
128
+ });
129
+ });
130
+ }
131
+
132
+ /**
133
+ * Runs `lxray <subcommand> ...args` (no shell).
134
+ * @param {string} subcommand run | collect | analyze | plugins | version
135
+ * @param {string[]} [args]
136
+ * @param {{binaryPath?: string, processTimeout?: number, env?: object, cwd?: string}} [options]
137
+ */
138
+ async function execLxray(subcommand, args = [], options = {}) {
139
+ const binary = await resolveBinary(options.binaryPath);
140
+ // 3 = partial collection (a plugin failed or protected sources were unreadable): the report exists
141
+ const run = typeof options.onLog === 'function' ? execStream : execNoShell;
142
+ const res = await run(binary, [subcommand, ...args], { timeout: options.processTimeout, env: options.env, cwd: options.cwd, okExitCodes: [3], onLine: options.onLog });
143
+ return { ...res, binary };
144
+ }
145
+
146
+ /** Python 3.6+ is needed for the analysis step (collection works without it). */
147
+ async function checkPython() {
148
+ for (const bin of ['python3', 'python']) {
149
+ try {
150
+ const { stdout, stderr } = await execNoShell(bin, ['--version'], { timeout: 10000 });
151
+ const m = /Python\s+(\d+)\.(\d+)\.(\d+)/.exec(`${stdout}${stderr}`);
152
+ if (m && Number(m[1]) === 3 && Number(m[2]) >= 6) return { available: true, version: `${m[1]}.${m[2]}.${m[3]}`, binary: bin };
153
+ } catch {
154
+ // try the next name
155
+ }
156
+ }
157
+ return { available: false, version: null, binary: null };
158
+ }
159
+
160
+ module.exports = { DEFAULT_CANDIDATES, resolveBinary, execLxray, execNoShell, execStream, checkPython, findInPath };