si-hawk 0.0.0-stage → 1.1.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/src/monitor.js ADDED
@@ -0,0 +1,110 @@
1
+ import { snapshotNode } from './node.js';
2
+ import { scanNearby } from './scan.js';
3
+
4
+ function keyed(items, keyOf) {
5
+ return new Map((items ?? []).map(item => [keyOf(item), item]));
6
+ }
7
+
8
+ function diffItems(before, after, keyOf, changed = null) {
9
+ const oldItems = keyed(before, keyOf);
10
+ const newItems = keyed(after, keyOf);
11
+ const added = [...newItems].filter(([key]) => !oldItems.has(key)).map(([, item]) => item);
12
+ const removed = [...oldItems].filter(([key]) => !newItems.has(key)).map(([, item]) => item);
13
+ const updated = changed ? [...newItems].filter(([key, item]) => oldItems.has(key) && changed(oldItems.get(key), item)).map(([, item]) => item) : [];
14
+ return { added, removed, updated };
15
+ }
16
+
17
+ function compareNearby(previous, current) {
18
+ const empty = { newWifiNetworks: [], removedWifiNetworks: [], newBluetoothDevices: [], removedBluetoothDevices: [] };
19
+ if (!previous || !current) return empty;
20
+ const oldWifi = previous.wifi?.available && current.wifi?.available
21
+ ? diffItems(previous.wifi.networks, current.wifi.networks, item => item.bssid ?? `${item.ssid ?? '<hidden>'}:${item.channel ?? 'unknown'}`)
22
+ : { added: [], removed: [] };
23
+ const oldBluetooth = previous.bluetooth?.available && current.bluetooth?.available
24
+ ? diffItems(previous.bluetooth.devices, current.bluetooth.devices, item => item.address)
25
+ : { added: [], removed: [] };
26
+ return {
27
+ newWifiNetworks: oldWifi.added,
28
+ removedWifiNetworks: oldWifi.removed,
29
+ newBluetoothDevices: oldBluetooth.added,
30
+ removedBluetoothDevices: oldBluetooth.removed,
31
+ };
32
+ }
33
+
34
+ export function compareNodeSnapshots(previous, current) {
35
+ if (!previous) return { baseline: true, startedProcesses: [], stoppedProcesses: [], serviceChanges: [], wifiConnectionChanged: null, nearbyChanges: compareNearby(null, current.network?.nearby), newNeighbors: [], removedNeighbors: [], newWifiClients: [], disconnectedWifiClients: [], activeApplicationChanged: null };
36
+ const processDiff = diffItems(previous.processes?.processes, current.processes?.processes, item => `${item.pid}:${item.name}`);
37
+ const serviceDiff = diffItems(previous.services?.services, current.services?.services, item => item.name, (a, b) => a.status !== b.status || a.active !== b.active || a.sub !== b.sub);
38
+ const neighborDiff = previous.network?.neighbors?.available && current.network?.neighbors?.available
39
+ ? diffItems(previous.network.neighbors.devices, current.network.neighbors.devices, item => `${item.mac ?? 'no-mac'}:${item.address}`)
40
+ : { added: [], removed: [] };
41
+ const wifiDiff = previous.network?.router?.available && current.network?.router?.available
42
+ ? diffItems(previous.network.router.clients, current.network.router.clients, item => item.mac)
43
+ : { added: [], removed: [] };
44
+ const previousWifi = previous.network?.wifiConnection?.connections ?? [];
45
+ const currentWifi = current.network?.wifiConnection?.connections ?? [];
46
+ const wifiConnectionChanged = previous.network?.wifiConnection?.available && current.network?.wifiConnection?.available &&
47
+ JSON.stringify(previousWifi.map(({ interface: name, ssid, bssid }) => ({ interface: name, ssid, bssid })) ) !==
48
+ JSON.stringify(currentWifi.map(({ interface: name, ssid, bssid }) => ({ interface: name, ssid, bssid })) )
49
+ ? { previous: previousWifi, current: currentWifi }
50
+ : null;
51
+ const oldApp = previous.activeApplication;
52
+ const newApp = current.activeApplication;
53
+ const activeApplicationChanged = oldApp?.available && newApp?.available && (oldApp.pid !== newApp.pid || oldApp.name !== newApp.name)
54
+ ? { previous: { pid: oldApp.pid, name: oldApp.name }, current: { pid: newApp.pid, name: newApp.name } }
55
+ : null;
56
+ return {
57
+ baseline: false,
58
+ startedProcesses: processDiff.added,
59
+ stoppedProcesses: processDiff.removed,
60
+ serviceChanges: [...serviceDiff.added.map(service => ({ type: 'added', service })), ...serviceDiff.removed.map(service => ({ type: 'removed', service })), ...serviceDiff.updated.map(service => ({ type: 'state-changed', service }))],
61
+ wifiConnectionChanged,
62
+ nearbyChanges: compareNearby(previous.network?.nearby, current.network?.nearby),
63
+ newNeighbors: neighborDiff.added,
64
+ removedNeighbors: neighborDiff.removed,
65
+ newWifiClients: wifiDiff.added,
66
+ disconnectedWifiClients: wifiDiff.removed,
67
+ activeApplicationChanged,
68
+ };
69
+ }
70
+
71
+ /** Yield nearby scan snapshots and in-session changes; no history is persisted. */
72
+ export async function* watchScan({ intervalMs = 30000, signal } = {}) {
73
+ if (!Number.isFinite(intervalMs) || intervalMs < 1000) throw new RangeError('intervalMs must be at least 1000');
74
+ let previous = null;
75
+ while (!signal?.aborted) {
76
+ const started = Date.now();
77
+ const current = await scanNearby();
78
+ current.changes = compareNearby(previous, current);
79
+ current.baseline = previous === null;
80
+ yield current;
81
+ previous = current;
82
+ const delay = Math.max(0, intervalMs - (Date.now() - started));
83
+ if (!delay || signal?.aborted) continue;
84
+ await new Promise(resolve => {
85
+ const finish = () => { clearTimeout(timer); signal?.removeEventListener('abort', finish); resolve(); };
86
+ const timer = setTimeout(finish, delay);
87
+ signal?.addEventListener('abort', finish, { once: true });
88
+ });
89
+ }
90
+ }
91
+
92
+ /** Yield source-backed device snapshots and observed changes until aborted. */
93
+ export async function* watchNode({ intervalMs = 30000, signal, ...snapshotOptions } = {}) {
94
+ if (!Number.isFinite(intervalMs) || intervalMs < 1000) throw new RangeError('intervalMs must be at least 1000');
95
+ let previous = null;
96
+ while (!signal?.aborted) {
97
+ const started = Date.now();
98
+ const current = await snapshotNode(snapshotOptions);
99
+ current.changes = compareNodeSnapshots(previous, current);
100
+ yield current;
101
+ previous = current;
102
+ const delay = Math.max(0, intervalMs - (Date.now() - started));
103
+ if (!delay || signal?.aborted) continue;
104
+ await new Promise(resolve => {
105
+ const finish = () => { clearTimeout(timer); signal?.removeEventListener('abort', finish); resolve(); };
106
+ const timer = setTimeout(finish, delay);
107
+ signal?.addEventListener('abort', finish, { once: true });
108
+ });
109
+ }
110
+ }
package/src/network.js ADDED
@@ -0,0 +1,211 @@
1
+ import os from 'node:os';
2
+ import { execFile } from 'node:child_process';
3
+ import { promisify } from 'node:util';
4
+ import { scanNearby } from './scan.js';
5
+
6
+ const execFileAsync = promisify(execFile);
7
+
8
+ function parseNeighbors(text, platform) {
9
+ const rows = [];
10
+ for (const line of text.split(/\r?\n/)) {
11
+ let match;
12
+ if (platform === 'win32') {
13
+ match = line.match(/^\s*([\da-f:.]+)\s+([\da-f-]{17})\s+(dynamic|static)\s*$/i);
14
+ if (match) rows.push({ address: match[1], mac: match[2].replaceAll('-', ':').toLowerCase(), state: match[3].toLowerCase(), detectionCase: 'same-lan-neighbor' });
15
+ } else if (platform === 'linux') {
16
+ match = line.match(/^\s*([\da-f:.]+)\s+dev\s+(\S+)(?:\s+lladdr\s+([\da-f:]{17}))?(?:\s+router)?\s*(\S+)?/i);
17
+ if (match) rows.push({ address: match[1], interface: match[2], mac: match[3]?.toLowerCase() ?? null, state: match[4] ?? null, detectionCase: 'same-lan-neighbor' });
18
+ } else {
19
+ match = line.match(/^\S+\s+\(([\da-f:.]+)\)\s+at\s+([\da-f:]{17}|\(incomplete\))(?:\s+on\s+(\S+))?/i);
20
+ if (match) rows.push({ address: match[1], mac: match[2] === '(incomplete)' ? null : match[2].toLowerCase(), interface: match[3] ?? null, state: match[2] === '(incomplete)' ? 'incomplete' : 'cached', detectionCase: 'same-lan-neighbor' });
21
+ }
22
+ }
23
+ return rows;
24
+ }
25
+
26
+ async function getNeighbors() {
27
+ const candidates = process.platform === 'win32'
28
+ ? [['arp.exe', ['-a'], 'arp.exe -a']]
29
+ : process.platform === 'linux'
30
+ ? [['ip', ['neigh', 'show'], 'ip neigh show'], ['arp', ['-an'], 'arp -an']]
31
+ : [['arp', ['-an'], 'arp -an']];
32
+ let lastError;
33
+ for (const [command, args, source] of candidates) {
34
+ try {
35
+ const { stdout } = await execFileAsync(command, args, { timeout: 5000, maxBuffer: 4 * 1024 * 1024 });
36
+ return { available: true, devices: parseNeighbors(stdout, process.platform), source, scope: 'OS neighbor/ARP cache across interfaces; may include cached entries and does not enumerate every Wi-Fi client' };
37
+ } catch (error) { lastError = error; }
38
+ }
39
+ return { available: false, devices: [], source: candidates.map(c => c[2]).join(' or '), reason: lastError?.killed ? 'Neighbor-cache query timed out.' : 'The operating system neighbor-cache command is unavailable or denied.' };
40
+ }
41
+
42
+ function parseWindowsWifi(text) {
43
+ const blocks = text.split(/(?=^\s*Name\s*:)/im).filter(block => /^\s*Name\s*:/im.test(block));
44
+ let recognized = blocks.length > 0;
45
+ const connections = blocks.flatMap(block => {
46
+ const value = key => {
47
+ const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
48
+ return block.match(new RegExp(`^\\s*${escaped}\\s*:\\s*(.*?)\\s*$`, 'im'))?.[1] ?? null;
49
+ };
50
+ const state = value('State')?.toLowerCase();
51
+ if (!state) recognized = false;
52
+ if (state !== 'connected') return [];
53
+ const ssid = value('SSID');
54
+ if (!ssid) { recognized = false; return []; }
55
+ const numeric = key => {
56
+ const found = value(key)?.match(/[\d.]+/);
57
+ return found ? Number(found[0]) : null;
58
+ };
59
+ return [{
60
+ interface: value('Name'), ssid, bssid: value('BSSID')?.toLowerCase() ?? null,
61
+ signalPercent: numeric('Signal'), radioType: value('Radio type'), channel: numeric('Channel'),
62
+ receiveRateMbps: numeric('Receive rate (Mbps)'), transmitRateMbps: numeric('Transmit rate (Mbps)'),
63
+ detectionCase: 'own-association',
64
+ }];
65
+ });
66
+ return { connections, recognized };
67
+ }
68
+
69
+ async function getWifiConnection() {
70
+ try {
71
+ if (process.platform === 'win32') {
72
+ const { stdout } = await execFileAsync('netsh.exe', ['wlan', 'show', 'interfaces'], { timeout: 5000, maxBuffer: 1024 * 1024, windowsHide: true });
73
+ const { connections, recognized } = parseWindowsWifi(stdout);
74
+ if (!recognized) return { available: false, connections: [], count: null, source: 'netsh wlan show interfaces', scope: 'active Wi-Fi association of the monitored Windows device; no nearby networks are scanned', reason: 'Windows returned WLAN output that Hawk could not reliably interpret.' };
75
+ return connections.length
76
+ ? { available: true, connections, count: connections.length, source: 'netsh wlan show interfaces', scope: 'Wi-Fi associations of the monitored Windows device; no nearby networks are scanned' }
77
+ : { available: true, connections: [], count: 0, source: 'netsh wlan show interfaces', scope: 'Wi-Fi associations of the monitored Windows device; no nearby networks are scanned', reason: 'No active Wi-Fi association was reported.' };
78
+ }
79
+ if (process.platform === 'linux') {
80
+ const { stdout: devices } = await execFileAsync('iw', ['dev'], { timeout: 5000, maxBuffer: 1024 * 1024 });
81
+ const names = [...devices.matchAll(/^\s*Interface\s+(\S+)/gm)].map(match => match[1]);
82
+ const results = await Promise.all(names.map(async name => {
83
+ const { stdout } = await execFileAsync('iw', ['dev', name, 'link'], { timeout: 5000, maxBuffer: 256 * 1024 });
84
+ const field = key => stdout.match(new RegExp(`^${key}:\\s*(.+)$`, 'im'))?.[1]?.trim() ?? null;
85
+ const ssid = field('SSID');
86
+ if (!ssid) return null;
87
+ const signal = field('signal')?.match(/-?[\d.]+/)?.[0];
88
+ const frequency = field('freq');
89
+ const bitrate = field('tx bitrate')?.match(/[\d.]+/)?.[0];
90
+ return { interface: name, ssid, bssid: stdout.match(/^Connected to\s+([\da-f:]+)/im)?.[1]?.toLowerCase() ?? null, signalDbm: signal ? Number(signal) : null, frequencyMHz: frequency ? Number(frequency) : null, transmitRateMbps: bitrate ? Number(bitrate) : null, detectionCase: 'own-association' };
91
+ }));
92
+ const connections = results.filter(Boolean);
93
+ return { available: true, connections, count: connections.length, source: 'iw dev <interface> link', scope: 'Wi-Fi associations of the monitored Linux device; no nearby networks are scanned', ...(connections.length ? {} : { reason: 'No active Wi-Fi association was reported.' }) };
94
+ }
95
+ if (process.platform === 'darwin') {
96
+ const { stdout: ports } = await execFileAsync('networksetup', ['-listallhardwareports'], { timeout: 5000, maxBuffer: 256 * 1024 });
97
+ const device = ports.match(/Hardware Port:\s*(?:Wi-Fi|AirPort)[\s\S]*?Device:\s*(\S+)/i)?.[1];
98
+ if (!device) return { available: true, connections: [], count: 0, source: 'networksetup -listallhardwareports / -getairportnetwork', scope: 'Wi-Fi association of the monitored macOS device; no nearby networks are scanned', reason: 'No Wi-Fi interface was reported.' };
99
+ const { stdout } = await execFileAsync('networksetup', ['-getairportnetwork', device], { timeout: 5000, maxBuffer: 256 * 1024 });
100
+ const ssid = stdout.match(/Current Wi-Fi Network:\s*(.+)/i)?.[1]?.trim();
101
+ const connections = ssid ? [{ interface: device, ssid, bssid: null, detectionCase: 'own-association' }] : [];
102
+ return { available: true, connections, count: connections.length, source: 'networksetup -getairportnetwork', scope: 'Wi-Fi association of the monitored macOS device; no nearby networks are scanned', ...(connections.length ? {} : { reason: 'No active Wi-Fi association was reported.' }) };
103
+ }
104
+ return { available: false, connections: [], count: null, source: null, scope: 'active Wi-Fi association of the monitored device', reason: 'This operating system has no Wi-Fi association adapter.' };
105
+ } catch (error) {
106
+ const command = process.platform === 'win32' ? 'netsh wlan' : process.platform === 'linux' ? 'iw' : 'networksetup';
107
+ return { available: false, connections: [], count: null, source: command, scope: 'active Wi-Fi association of the monitored device; no nearby networks are scanned', reason: error?.code === 'ENOENT' ? `The ${command} command is unavailable.` : error?.killed || error?.code === 'ETIMEDOUT' ? 'The Wi-Fi association query timed out.' : 'The operating system could not provide the active Wi-Fi association.' };
108
+ }
109
+ }
110
+
111
+ async function openWrtRouter() {
112
+ const endpoint = process.env.HAWK_ROUTER_UBUS_URL;
113
+ const username = process.env.HAWK_ROUTER_USERNAME;
114
+ const password = process.env.HAWK_ROUTER_PASSWORD;
115
+ if (!endpoint || !username || !password) {
116
+ return { available: false, count: null, clients: [], source: 'OpenWrt ubus JSON-RPC', reason: 'Router inventory is not configured; set HAWK_ROUTER_UBUS_URL, HAWK_ROUTER_USERNAME, and HAWK_ROUTER_PASSWORD.' };
117
+ }
118
+ let url;
119
+ try { url = new URL(endpoint); } catch {
120
+ return { available: false, count: null, clients: [], source: 'OpenWrt ubus JSON-RPC', reason: 'Router URL is invalid.' };
121
+ }
122
+ if (!['http:', 'https:'].includes(url.protocol)) return { available: false, count: null, clients: [], source: 'OpenWrt ubus JSON-RPC', reason: 'Router URL must use HTTP or HTTPS.' };
123
+ if (url.protocol !== 'https:') {
124
+ return { available: false, count: null, clients: [], source: 'OpenWrt ubus JSON-RPC', reason: 'HTTPS is required for router credentials; no network request was made.' };
125
+ }
126
+ const rpcUrl = new URL('/ubus', url);
127
+ let id = 1;
128
+ const call = async (session, object, method, params = {}) => {
129
+ const response = await fetch(rpcUrl, {
130
+ method: 'POST',
131
+ headers: { 'content-type': 'application/json' },
132
+ body: JSON.stringify({ jsonrpc: '2.0', id: id++, method: 'call', params: [session, object, method, params] }),
133
+ signal: AbortSignal.timeout(5000),
134
+ });
135
+ if (!response.ok) throw new Error('router HTTP request failed');
136
+ const payload = await response.json();
137
+ const [status, data] = payload.result ?? [];
138
+ if (status !== 0) throw new Error('router rejected the read-only request or the required ubus method is unavailable');
139
+ return data;
140
+ };
141
+ let session = null;
142
+ try {
143
+ const login = await call('00000000000000000000000000000000', 'session', 'login', { username, password, timeout: 60 });
144
+ session = login?.ubus_rpc_session;
145
+ if (!session) throw new Error('router login did not return a session');
146
+ const [hints, wireless] = await Promise.all([
147
+ call(session, 'luci-rpc', 'getHostHints'),
148
+ call(session, 'network.wireless', 'status').catch(() => null),
149
+ ]);
150
+ const clients = [];
151
+ const radios = wireless && typeof wireless === 'object' ? Object.values(wireless) : [];
152
+ if (!radios.length) throw new Error('router did not return wireless interface status; Wi-Fi client coverage is unavailable');
153
+ let accessPointCount = 0;
154
+ for (const radio of radios) {
155
+ for (const iface of radio?.interfaces ?? []) {
156
+ if (iface?.config?.mode !== 'ap' || !iface?.ifname) continue;
157
+ accessPointCount++;
158
+ const association = await call(session, 'iwinfo', 'assoclist', { device: iface.ifname }).catch(() => {
159
+ throw new Error(`router denied association data for ${iface.ifname}`);
160
+ });
161
+ const stations = association?.results ?? association?.clients ?? [];
162
+ for (const station of stations) {
163
+ const mac = String(station.mac ?? station.address ?? '').toLowerCase();
164
+ if (!mac) throw new Error(`router returned an unidentifiable station on ${iface.ifname}`);
165
+ const hint = Object.entries(hints ?? {}).find(([address]) => address.toLowerCase() === mac)?.[1] ?? {};
166
+ const ipv6Hints = Array.isArray(hint.ip6addr) ? hint.ip6addr.filter(value => typeof value === 'string') : typeof hint.ip6addr === 'string' ? [hint.ip6addr] : [];
167
+ clients.push({ mac, name: typeof hint.name === 'string' ? hint.name : null, addresses: [typeof hint.ipaddr === 'string' ? hint.ipaddr : null, ...ipv6Hints].filter(Boolean), interface: iface.ifname, state: 'associated', source: 'OpenWrt iwinfo assoclist' });
168
+ }
169
+ }
170
+ }
171
+ if (!accessPointCount) throw new Error('router returned no active access-point interfaces');
172
+ return {
173
+ available: true,
174
+ clients,
175
+ count: clients.length,
176
+ accessPointCount,
177
+ source: 'OpenWrt ubus network.wireless status + iwinfo assoclist; names/IP hints from luci-rpc getHostHints',
178
+ scope: 'currently associated Wi-Fi stations on configured OpenWrt access points; wired clients and other mesh nodes may not be included',
179
+ transport: 'https',
180
+ };
181
+ } catch (error) {
182
+ return { available: false, clients: [], count: null, source: 'OpenWrt ubus JSON-RPC', reason: error?.name === 'TimeoutError' ? 'Router query timed out.' : error?.message || 'Router query failed.' };
183
+ } finally {
184
+ if (session) call(session, 'session', 'destroy').catch(() => {});
185
+ }
186
+ }
187
+
188
+ /** Read host network state; optional nearby scans are separate from router telemetry. */
189
+ export async function collectNetworkTelemetry({ includeRouter = false, includeNearby = false } = {}) {
190
+ const rawInterfaces = os.networkInterfaces();
191
+ const interfaces = Object.entries(rawInterfaces).flatMap(([name, addresses]) => (addresses ?? []).map(item => ({
192
+ name,
193
+ address: item.address,
194
+ family: item.family,
195
+ netmask: item.netmask,
196
+ cidr: item.cidr,
197
+ mac: item.mac,
198
+ internal: item.internal,
199
+ })));
200
+ const [wifiConnection, neighbors, router, nearby] = await Promise.all([getWifiConnection(), getNeighbors(), includeRouter ? openWrtRouter() : null,
201
+ includeNearby ? scanNearby() : Promise.resolve({ available: false, wifi: null, bluetooth: null, observedAt: new Date().toISOString(), source: null, reason: 'Nearby radio scans were not requested; run `hawk scan` or use host watch mode.' })]);
202
+ return {
203
+ observedAt: new Date().toISOString(),
204
+ wifiConnection,
205
+ nearby,
206
+ interfaces: { available: true, count: interfaces.length, devices: interfaces, source: 'node:os.networkInterfaces()' },
207
+ neighbors: { ...neighbors, count: neighbors.available ? neighbors.devices.length : null, observedAt: new Date().toISOString() },
208
+ ...(router ? { router } : {}),
209
+ };
210
+ }
211
+
package/src/node.js ADDED
@@ -0,0 +1,184 @@
1
+ import os from 'node:os';
2
+ import { readFile, statfs } from 'node:fs/promises';
3
+ import { parse, resolve, sep } from 'node:path';
4
+ import { execFile } from 'node:child_process';
5
+ import { promisify } from 'node:util';
6
+ import { collectWindowsTelemetry } from './windows.js';
7
+ import { collectPortableTelemetry } from './portable.js';
8
+ import { collectProcesses } from './processes.js';
9
+ import { collectServices } from './services.js';
10
+ import { collectNetworkTelemetry } from './network.js';
11
+
12
+ function cpuTotals(cpus) {
13
+ return cpus.reduce((total, cpu) => {
14
+ for (const [mode, time] of Object.entries(cpu.times)) total[mode] += time;
15
+ return total;
16
+ }, { user: 0, nice: 0, sys: 0, idle: 0, irq: 0 });
17
+ }
18
+
19
+ const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
20
+ const execFileAsync = promisify(execFile);
21
+
22
+ async function findMountPoint(storagePath) {
23
+ if (process.platform === 'win32') return parse(storagePath).root || null;
24
+ if (process.platform === 'linux') {
25
+ try {
26
+ const target = resolve(storagePath);
27
+ const entries = (await readFile('/proc/self/mountinfo', 'utf8')).split('\n');
28
+ const mountPoints = entries.map(line => {
29
+ const fields = line.split(' ');
30
+ return fields[4]?.replace(/\\(040|011|134)/g, (_, code) => ({'040':' ','011':'\t','134':'\\'}[code]));
31
+ }).filter(Boolean).sort((a, b) => b.length - a.length);
32
+ return mountPoints.find(mount => target === mount || target.startsWith(mount.endsWith(sep) ? mount : `${mount}${sep}`)) ?? null;
33
+ } catch { return null; }
34
+ }
35
+ if (process.platform === 'darwin') {
36
+ try {
37
+ const { stdout } = await execFileAsync('df', ['-P', storagePath], { timeout: 4000, maxBuffer: 256 * 1024 });
38
+ const lines = stdout.trim().split(/\r?\n/);
39
+ return lines.length > 1 ? lines.at(-1).trim().split(/\s+/).at(-1) : null;
40
+ } catch { return null; }
41
+ }
42
+ return null;
43
+ }
44
+
45
+ export function detectNode() {
46
+ const cpus = os.cpus();
47
+ const totalmem = os.totalmem();
48
+ const freemem = os.freemem();
49
+ return {
50
+ name: os.hostname(),
51
+ platform: os.platform(),
52
+ release: os.release(),
53
+ arch: os.arch(),
54
+ // Preserve the original public fields for existing consumers.
55
+ cpus: cpus.length,
56
+ totalmem,
57
+ freemem,
58
+ cpu: { model: cpus[0]?.model ?? null, logicalCores: cpus.length },
59
+ memory: {
60
+ totalBytes: totalmem,
61
+ availableBytes: freemem,
62
+ usedBytes: totalmem - freemem,
63
+ usedPercent: totalmem ? Math.round(((totalmem - freemem) / totalmem) * 10000) / 100 : null,
64
+ },
65
+ nodeVersion: process.version,
66
+ v8Version: process.versions.v8,
67
+ };
68
+ }
69
+
70
+ /**
71
+ * Collects host telemetry available to this Node.js process. This reports only
72
+ * the current host; connected-device inventory requires an explicit platform
73
+ * adapter and is never inferred by probing the local network.
74
+ */
75
+ export async function snapshotNode({ sampleMs = 1000, storagePath = process.cwd(), includeNetwork = true, includeRouter = false, includeNearby = false } = {}) {
76
+ const effectiveSampleMs = Math.max(1000, Number.isFinite(sampleMs) ? sampleMs : 1000);
77
+ const cpuSampleStarted = performance.now();
78
+ const before = cpuTotals(os.cpus());
79
+ await wait(effectiveSampleMs);
80
+ const after = cpuTotals(os.cpus());
81
+ const cpuSampleMs = Math.round(performance.now() - cpuSampleStarted);
82
+ const total = Object.values(after).reduce((sum, value) => sum + value, 0) -
83
+ Object.values(before).reduce((sum, value) => sum + value, 0);
84
+ const idle = after.idle - before.idle;
85
+ const base = detectNode();
86
+ const [windows, portable, processes, services, network] = await Promise.all([
87
+ collectWindowsTelemetry(),
88
+ collectPortableTelemetry(),
89
+ process.platform !== 'win32' ? collectProcesses() : null,
90
+ process.platform === 'win32' ? null : collectServices(),
91
+ includeNetwork ? collectNetworkTelemetry({ includeRouter, includeNearby }) : null,
92
+ ]);
93
+ const identity = windows?.identity ?? portable?.identity ?? {
94
+ available: Boolean(base.name), name: base.name || null, manufacturer: null, model: null, deviceType: null,
95
+ source: 'node:os.hostname()', reason: 'This platform adapter does not expose manufacturer, model, or device type.',
96
+ };
97
+ const battery = windows?.battery ?? portable?.battery ?? {
98
+ available: false, levelPercent: null, charging: null, powerSource: 'unknown',
99
+ source: null, reason: 'No battery adapter is available for this platform.',
100
+ };
101
+ const processInventory = windows?.processes ?? processes ?? { available: false, count: null, processes: [], reason: 'No process adapter is available.' };
102
+ const serviceInventory = windows?.services ?? services ?? { available: false, count: null, services: [], reason: 'No service adapter is available.' };
103
+ const activeApplication = windows?.activeApplication ?? portable?.activeApplication ?? { available: false, pid: null, name: null, source: null, reason: 'No foreground-application adapter is available.', titleCollected: false };
104
+
105
+ const mountPoint = await findMountPoint(storagePath);
106
+ let storage = { available: false, volumeRoot: mountPoint, mountPoint, reason: 'Storage statistics are unavailable.' };
107
+ try {
108
+ const fs = await statfs(storagePath);
109
+ const blockSize = Number(fs.bsize);
110
+ const totalBytes = Number(fs.blocks) * blockSize;
111
+ const availableBytes = Number(fs.bavail) * blockSize;
112
+ storage = {
113
+ available: true,
114
+ volumeRoot: mountPoint,
115
+ mountPoint,
116
+ totalBytes,
117
+ availableBytes,
118
+ usedBytes: totalBytes - availableBytes,
119
+ usedPercent: totalBytes ? Math.round(((totalBytes - availableBytes) / totalBytes) * 10000) / 100 : null,
120
+ };
121
+ } catch (error) {
122
+ storage = { ...storage, reason: error?.message || storage.reason };
123
+ }
124
+
125
+ return {
126
+ observedAt: new Date().toISOString(),
127
+ source: 'node:os and node:fs',
128
+ host: {
129
+ ...base,
130
+ manufacturer: identity.manufacturer ?? null,
131
+ model: identity.model ?? null,
132
+ deviceType: identity.deviceType ?? null,
133
+ deviceTypeStatus: identity.deviceTypeStatus || identity.reason || 'No platform identity adapter is available.',
134
+ cpu: {
135
+ ...base.cpu,
136
+ utilizationPercent: total > 0 ? Math.round(((total - idle) / total) * 10000) / 100 : null,
137
+ measurement: {
138
+ kind: 'measured',
139
+ source: 'node:os.cpus() cumulative time deltas',
140
+ windowMs: cpuSampleMs,
141
+ },
142
+ },
143
+ },
144
+ storage,
145
+ deviceIdentity: identity,
146
+ battery,
147
+ connectedDevices: windows?.connectedDevices ?? {
148
+ available: false, count: null, devices: [], scope: null,
149
+ reason: 'No authorized platform device-inventory adapter is configured.',
150
+ },
151
+ processes: processInventory,
152
+ services: serviceInventory,
153
+ activeApplication,
154
+ network: network ?? { available: false, reason: 'Network inventory was not requested.' },
155
+ sources: {
156
+ host: 'node:os',
157
+ cpu: 'node:os.cpus() cumulative time deltas over measurement.windowMs',
158
+ memory: 'node:os totalmem() and freemem()',
159
+ storage: 'node:fs.statfs() for the volume containing storagePath',
160
+ deviceIdentity: identity.source,
161
+ battery: battery.source,
162
+ ...(windows ? { windows: windows.source, connectedDevices: windows.connectedDevices.source } : {}),
163
+ processes: processInventory.source,
164
+ services: serviceInventory.source,
165
+ activeApplication: activeApplication.source,
166
+ ...(network ? {
167
+ networkInterfaces: network.interfaces.source,
168
+ networkWifiConnection: network.wifiConnection.source,
169
+ networkNeighbors: network.neighbors.source,
170
+ networkNearby: [network.nearby.wifi?.source, network.nearby.bluetooth?.source].filter(Boolean).join('; ') || network.nearby.reason,
171
+ ...(network.router ? { router: network.router.source } : {}),
172
+ } : {}),
173
+ },
174
+ };
175
+ }
176
+
177
+ export function fingerprintNode() {
178
+ const node = detectNode();
179
+ const str = `${node.platform}|${node.arch}|${node.cpu.logicalCores}|${node.memory.totalBytes}`;
180
+ let h = 5381;
181
+ for (let i = 0; i < str.length; i++) h = ((h << 5) + h) + str.charCodeAt(i);
182
+ return (h >>> 0).toString(16).padStart(8, '0');
183
+ }
184
+
@@ -0,0 +1,84 @@
1
+ import os from 'node:os';
2
+ import { readFile, readdir } from 'node:fs/promises';
3
+ import { execFile } from 'node:child_process';
4
+ import { promisify } from 'node:util';
5
+
6
+ const execFileAsync = promisify(execFile);
7
+
8
+ async function readText(path) {
9
+ try { return (await readFile(path, 'utf8')).trim() || null; } catch { return null; }
10
+ }
11
+
12
+ async function linuxAdapter() {
13
+ const [manufacturer, model, chassisRaw, entries] = await Promise.all([
14
+ readText('/sys/class/dmi/id/sys_vendor'),
15
+ readText('/sys/class/dmi/id/product_name'),
16
+ readText('/sys/class/dmi/id/chassis_type'),
17
+ readdir('/sys/class/power_supply').catch(() => []),
18
+ ]);
19
+ const chassis = Number(chassisRaw);
20
+ const chassisTypes = new Map([[3,'desktop'],[4,'desktop'],[5,'desktop'],[6,'desktop'],[7,'desktop'],[8,'portable'],[9,'laptop'],[10,'notebook'],[11,'handheld'],[12,'docking-station'],[13,'all-in-one'],[14,'subnotebook'],[15,'space-saving'],[16,'lunchbox'],[17,'server'],[23,'server'],[30,'tablet']]);
21
+ const identity = { available: Boolean(os.hostname() || manufacturer || model), name: os.hostname() || null, manufacturer, model, deviceType: chassisTypes.get(chassis) ?? null, deviceTypeCategory: Number.isFinite(chassis) ? `SMBIOS chassis type ${chassis}` : null, source: 'Linux hostname and /sys/class/dmi/id', deviceTypeStatus: chassisTypes.has(chassis) ? 'mapped from the OS SMBIOS chassis_type value' : 'Linux did not expose a recognized SMBIOS chassis_type value' };
22
+ const batteries = entries.filter(name => /^BAT/i.test(name));
23
+ if (!batteries.length) return { identity, battery: { available: false, levelPercent: null, charging: null, source: 'Linux power_supply sysfs', reason: 'No BAT* power-supply entry is exposed by Linux.' } };
24
+ const readings = await Promise.all(batteries.map(async name => {
25
+ const [capacity, status] = await Promise.all([
26
+ readText(`/sys/class/power_supply/${name}/capacity`),
27
+ readText(`/sys/class/power_supply/${name}/status`),
28
+ ]);
29
+ return { capacity: capacity === null ? null : Number(capacity), status };
30
+ }));
31
+ const valid = readings.map(row => row.capacity).filter(value => Number.isFinite(value) && value >= 0 && value <= 100);
32
+ const oneBattery = readings.length === 1;
33
+ return { identity, battery: { available: oneBattery && valid.length === 1, levelPercent: oneBattery && valid.length === 1 ? valid[0] : null, batteries: readings, charging: readings.length === 1 ? (readings[0].status === 'Charging' ? true : ['Full','Not charging','Discharging'].includes(readings[0].status) ? false : null) : null, powerSource: readings.some(x=>x.status === 'Charging' || x.status === 'Full') ? 'online' : 'unknown', source: 'Linux /sys/class/power_supply BAT* capacity and status', reason: oneBattery && valid.length === 1 ? null : readings.length > 1 ? 'Multiple batteries are present; individual readings are reported without combining them.' : 'Linux did not expose a valid battery capacity reading.' } };
34
+ }
35
+
36
+ async function macAdapter() {
37
+ let identity = { available: Boolean(os.hostname()), name: os.hostname() || null, manufacturer: 'Apple', model: null, deviceType: null, deviceTypeCategory: null, source: 'macOS hostname and system_profiler SPHardwareDataType', deviceTypeStatus: 'macOS model query has not returned a device category' };
38
+ try {
39
+ const { stdout } = await execFileAsync('system_profiler', ['SPHardwareDataType', '-json'], { timeout: 12000, maxBuffer: 4 * 1024 * 1024 });
40
+ const data = JSON.parse(stdout).SPHardwareDataType?.[0] ?? {};
41
+ const modelName = data.machine_name ?? null;
42
+ const model = [modelName, data.machine_model].filter(Boolean).join(' (') + (modelName && data.machine_model ? ')' : '');
43
+ const type = /MacBook/i.test(modelName ?? '') ? 'laptop' : /iMac|Mac mini|Mac Studio|Mac Pro/i.test(modelName ?? '') ? 'desktop' : null;
44
+ identity = { ...identity, available: Boolean(identity.name || model), model: model || null, deviceType: type, deviceTypeCategory: type ? `Apple model family: ${modelName}` : null, deviceTypeStatus: type ? 'classified from the model name returned by system_profiler' : 'system_profiler returned no model family that identifies the form factor' };
45
+ } catch { /* Preserve known hostname and leave model/type unavailable. */ }
46
+ let battery = { available: false, levelPercent: null, charging: null, source: 'pmset -g batt', reason: 'macOS battery status is unavailable or the device has no battery.' };
47
+ try {
48
+ const { stdout } = await execFileAsync('pmset', ['-g', 'batt'], { timeout: 4000, maxBuffer: 256 * 1024 });
49
+ const percent = stdout.match(/\b(\d+(?:\.\d+)?)%/);
50
+ const hasBattery = /InternalBattery/i.test(stdout);
51
+ if (hasBattery) battery = { available: Boolean(percent), levelPercent: percent ? Number(percent[1]) : null, charging: /\bcharging\b/i.test(stdout) ? true : /\bdischarging\b|\bcharged\b/i.test(stdout) ? false : null, powerSource: /AC Power/i.test(stdout) ? 'online' : 'offline', source: 'pmset -g batt', reason: percent ? null : 'macOS returned no numeric battery percentage.' };
52
+ } catch { /* Keep explicit unavailable status. */ }
53
+ return { identity, battery };
54
+ }
55
+
56
+ async function linuxActiveApplication() {
57
+ const source = 'X11 focused window PID via xdotool and process name via ps';
58
+ if (process.env.WAYLAND_DISPLAY) return { available: false, pid: null, name: null, source, titleCollected: false, reason: 'Wayland does not expose the foreground application through this adapter.' };
59
+ if (!process.env.DISPLAY) return { available: false, pid: null, name: null, source, titleCollected: false, reason: 'No X11 display is available to this process.' };
60
+ try {
61
+ const { stdout } = await execFileAsync('xdotool', ['getwindowfocus', 'getwindowpid'], { timeout: 3000, maxBuffer: 65536 });
62
+ const pid = Number(stdout.trim());
63
+ if (!Number.isInteger(pid) || pid <= 0) throw new Error('X11 returned no focused process ID.');
64
+ const proc = await execFileAsync('ps', ['-p', String(pid), '-o', 'comm='], { timeout: 3000, maxBuffer: 65536 });
65
+ return { available: true, pid, name: proc.stdout.trim() || null, source, titleCollected: false };
66
+ } catch (error) { return { available: false, pid: null, name: null, source, titleCollected: false, reason: error?.code === 'ENOENT' ? 'xdotool is not installed or is not on PATH.' : error.message }; }
67
+ }
68
+
69
+ async function macActiveApplication() {
70
+ const source = 'System Events frontmost process UNIX ID and ps process name';
71
+ try {
72
+ const { stdout } = await execFileAsync('osascript', ['-e', 'tell application "System Events" to get unix id of first application process whose frontmost is true'], { timeout: 4000, maxBuffer: 65536 });
73
+ const pid = Number(stdout.trim());
74
+ if (!Number.isInteger(pid) || pid <= 0) throw new Error('System Events returned no frontmost process ID.');
75
+ const proc = await execFileAsync('ps', ['-p', String(pid), '-o', 'comm='], { timeout: 3000, maxBuffer: 65536 });
76
+ return { available: true, pid, name: proc.stdout.trim() || null, source, titleCollected: false };
77
+ } catch (error) { return { available: false, pid: null, name: null, source, titleCollected: false, reason: /not allowed|assistive|permission/i.test(error.message) ? 'macOS Accessibility permission is required for System Events.' : error.message }; }
78
+ }
79
+
80
+ export async function collectPortableTelemetry() {
81
+ if (process.platform === 'linux') return { ...await linuxAdapter(), activeApplication: await linuxActiveApplication() };
82
+ if (process.platform === 'darwin') return { ...await macAdapter(), activeApplication: await macActiveApplication() };
83
+ return null;
84
+ }
@@ -0,0 +1,41 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+
4
+ const execFileAsync = promisify(execFile);
5
+
6
+ /** Snapshot running processes without collecting command-line arguments. */
7
+ export async function collectProcesses({ timeoutMs = 8000 } = {}) {
8
+ try {
9
+ if (process.platform === 'win32') {
10
+ return { available: false, count: null, processes: [], source: 'PowerShell Get-Process', reason: 'Windows process inventory is collected with the host adapter; call snapshotNode() on Windows.' };
11
+ }
12
+
13
+ const args = process.platform === 'darwin'
14
+ ? ['-A', '-o', 'pid=,ppid=,rss=,state=,etime=,comm=']
15
+ : ['-e', '-o', 'pid=,ppid=,rss=,stat=,etime=,comm='];
16
+ const { stdout } = await execFileAsync('ps', args, { timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024 });
17
+ const processes = stdout.split(/\r?\n/).map(line => line.trim()).filter(Boolean).map(line => {
18
+ const fields = line.match(/^(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\S+)\s+(.+)$/);
19
+ if (!fields) return null;
20
+ return {
21
+ pid: Number(fields[1]),
22
+ parentPid: Number(fields[2]),
23
+ memoryBytes: Number(fields[3]) * 1024,
24
+ state: fields[4],
25
+ elapsed: fields[5],
26
+ name: fields[6],
27
+ source: 'ps',
28
+ };
29
+ }).filter(Boolean);
30
+ return { available: true, count: processes.length, processes, source: `ps ${args.join(' ')}`, scope: 'running processes; command-line arguments are excluded; RSS is the OS-reported resident set size' };
31
+ } catch (error) {
32
+ return {
33
+ available: false,
34
+ count: null,
35
+ processes: [],
36
+ source: process.platform === 'win32' ? 'tasklist.exe' : 'ps',
37
+ reason: error?.killed || error?.code === 'ETIMEDOUT' ? 'Process inventory timed out.' : `Process inventory unavailable (${error?.code || 'OS error'}).`,
38
+ };
39
+ }
40
+ }
41
+