si-hawk 0.0.0-stage → 1.1.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.
package/src/scan.js ADDED
@@ -0,0 +1,263 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+
4
+ const execFileAsync = promisify(execFile);
5
+
6
+ function number(value) {
7
+ const match = String(value ?? '').match(/-?\d+(?:\.\d+)?/);
8
+ return match ? Number(match[0]) : null;
9
+ }
10
+
11
+ function wifiPoint(ssid, bssid, fields = {}) {
12
+ return {
13
+ ssid: ssid?.trim() || null,
14
+ bssid: bssid?.trim().toLowerCase() || null,
15
+ signalPercent: fields.signalPercent ?? null,
16
+ signalDbm: fields.signalDbm ?? null,
17
+ channel: fields.channel ?? null,
18
+ securityType: fields.securityType ?? 'unknown',
19
+ detectionCase: 'nearby-access-point',
20
+ radioType: fields.radioType ?? null,
21
+ source: fields.source,
22
+ };
23
+ }
24
+
25
+ /** Parse `netsh wlan show networks mode=bssid` output without assuming a locale. */
26
+ export function parseWindowsWifiScan(text) {
27
+ const networks = [];
28
+ let ssid = null;
29
+ let authentication = null;
30
+ let encryption = null;
31
+ let point = null;
32
+ let recognized = false;
33
+ const flush = () => {
34
+ if (point) networks.push(wifiPoint(ssid, point.bssid, {
35
+ signalPercent: point.signalPercent,
36
+ channel: point.channel,
37
+ radioType: point.radioType,
38
+ securityType: authentication ? (encryption ? `${authentication} (${encryption})` : authentication) : 'unknown',
39
+ source: 'netsh wlan show networks mode=bssid',
40
+ }));
41
+ point = null;
42
+ };
43
+ for (const line of String(text ?? '').split(/\r?\n/)) {
44
+ let match = line.match(/^\s*SSID\s+\d+\s*:\s*(.*?)\s*$/i);
45
+ if (match) {
46
+ flush();
47
+ recognized = true;
48
+ ssid = match[1] || null;
49
+ authentication = null;
50
+ encryption = null;
51
+ continue;
52
+ }
53
+ match = line.match(/^\s*BSSID\s+\d+\s*:\s*([\da-f:.-]{17})\s*$/i);
54
+ if (match) {
55
+ flush();
56
+ recognized = true;
57
+ point = { bssid: match[1] };
58
+ continue;
59
+ }
60
+ match = line.match(/^\s*(Authentication|Encryption)\s*:\s*(.*?)\s*$/i);
61
+ if (match) {
62
+ recognized = true;
63
+ if (match[1].toLowerCase() === 'authentication') authentication = match[2] || null;
64
+ else encryption = match[2] || null;
65
+ continue;
66
+ }
67
+ if (!point) continue;
68
+ match = line.match(/^\s*(Signal|Channel|Radio type)\s*:\s*(.*?)\s*$/i);
69
+ if (!match) continue;
70
+ recognized = true;
71
+ if (match[1].toLowerCase() === 'signal') point.signalPercent = number(match[2]);
72
+ if (match[1].toLowerCase() === 'channel') point.channel = number(match[2]);
73
+ if (match[1].toLowerCase() === 'radio type') point.radioType = match[2] || null;
74
+ }
75
+ flush();
76
+ if (/There are 0 networks? currently visible/i.test(String(text ?? ''))) recognized = true;
77
+ return { networks, recognized };
78
+ }
79
+
80
+ function channelFromFrequency(frequency) {
81
+ if (frequency === 2484) return 14;
82
+ if (frequency >= 2412 && frequency <= 2472) return (frequency - 2407) / 5;
83
+ if (frequency >= 5000 && frequency < 5925) return (frequency - 5000) / 5;
84
+ if (frequency >= 5955 && frequency <= 7115) return (frequency - 5950) / 5;
85
+ return null;
86
+ }
87
+
88
+ /** Parse `iw dev <interface> scan` output. */
89
+ export function parseIwWifiScan(text) {
90
+ const blocks = String(text ?? '').split(/(?=^BSS\s)/m).filter(block => /^BSS\s/m.test(block));
91
+ const networks = blocks.map(block => {
92
+ const bssid = block.match(/^BSS\s+([\da-f:]{17})/im)?.[1] ?? null;
93
+ const ssid = block.match(/^\s*SSID:\s*(.*?)\s*$/im)?.[1] ?? null;
94
+ const frequency = number(block.match(/^\s*freq:\s*(.*?)\s*$/im)?.[1]);
95
+ const signalDbm = number(block.match(/^\s*signal:\s*(-?\d+(?:\.\d+)?)\s*dBm/im)?.[1]);
96
+ const channel = number(block.match(/^\s*(?:DS Parameter set:\s*channel|primary channel):\s*(.*?)\s*$/im)?.[1]) ?? channelFromFrequency(frequency);
97
+ const auth = [...block.matchAll(/^\s*\*\s*Authentication suites:\s*(.*?)\s*$/gim)].map(item => item[1]).join(' ');
98
+ let securityType = 'unknown';
99
+ if (!/Privacy/i.test(block.match(/^\s*capability:.*$/im)?.[0] ?? '')) securityType = 'open';
100
+ else if (/SAE/i.test(auth)) securityType = 'WPA3-SAE';
101
+ else if (/RSN:/i.test(block) && /PSK/i.test(auth)) securityType = 'WPA2-PSK';
102
+ else if (/WPA:/i.test(block) && /PSK/i.test(auth)) securityType = 'WPA-PSK';
103
+ else if (auth) securityType = auth;
104
+ else if (/Privacy/i.test(block)) securityType = 'secured (type unavailable)';
105
+ return wifiPoint(ssid, bssid, { signalDbm, channel, securityType, source: 'iw scan passive' });
106
+ }).filter(point => point.bssid);
107
+ return { networks, recognized: blocks.length > 0 };
108
+ }
109
+
110
+ /** Parse the tabular output from Apple's legacy `airport -s` scan command. */
111
+ export function parseMacWifiScan(text) {
112
+ const networks = [];
113
+ let recognized = false;
114
+ for (const line of String(text ?? '').split(/\r?\n/)) {
115
+ const match = line.match(/^(.*?)\s+([\da-f:]{17})\s+(-?\d+)\s+(\d+(?:,\d+)?)\s+\S+\s+\S+\s+(.+?)\s*$/i);
116
+ if (!match) continue;
117
+ recognized = true;
118
+ networks.push(wifiPoint(match[1], match[2], {
119
+ signalDbm: Number(match[3]),
120
+ channel: Number(match[4].split(',')[0]),
121
+ securityType: match[5].trim() || 'unknown',
122
+ source: 'airport -s',
123
+ }));
124
+ }
125
+ return { networks, recognized };
126
+ }
127
+
128
+ function unavailable(reason, source) {
129
+ return { available: false, count: null, devices: [], source, scope: 'nearby Bluetooth Low Energy advertisements received by a passive scan during this observation only; device identifiers are not retained after the command exits', reason };
130
+ }
131
+
132
+ const windowsBleSource = 'Windows WinRT BluetoothLEAdvertisementWatcher (passive)';
133
+ const windowsBleScript = String.raw`$ErrorActionPreference = 'Stop'
134
+ $watcherType = [Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementWatcher,Windows.Devices.Bluetooth,ContentType=WindowsRuntime]
135
+ $modeType = [Windows.Devices.Bluetooth.Advertisement.BluetoothLEScanningMode,Windows.Devices.Bluetooth,ContentType=WindowsRuntime]
136
+ $receivedType = [Windows.Foundation.TypedEventHandler[Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementWatcher,Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementReceivedEventArgs]]
137
+ $watcher = $watcherType::new()
138
+ $watcher.ScanningMode = $modeType::Passive
139
+ $devices = [hashtable]::Synchronized(@{})
140
+ $handler = $receivedType {
141
+ param($sender, $eventArgs)
142
+ $hex = '{0:X12}' -f [UInt64]$eventArgs.BluetoothAddress
143
+ $address = (($hex -replace '(.{2})(?=.)', '$1:').ToLowerInvariant())
144
+ $devices[$address] = [pscustomobject]@{
145
+ address = $address
146
+ name = $(if ($eventArgs.Advertisement.LocalName) { $eventArgs.Advertisement.LocalName } else { $null })
147
+ signalDbm = [int]$eventArgs.RawSignalStrengthInDBm
148
+ detectionCase = 'nearby-bluetooth-advertisement'
149
+ source = 'Windows WinRT BluetoothLEAdvertisementWatcher (passive)'
150
+ }
151
+ }
152
+ try {
153
+ $watcher.add_Received($handler)
154
+ $watcher.Start()
155
+ if ($watcher.Status.ToString() -ne 'Started') { throw "Bluetooth watcher status: $($watcher.Status)" }
156
+ Start-Sleep -Milliseconds 5000
157
+ } finally {
158
+ if ($watcher.Status.ToString() -eq 'Started') { $watcher.Stop() }
159
+ try { $watcher.remove_Received($handler) } catch { }
160
+ }
161
+ ConvertTo-Json -InputObject @($devices.Values) -Compress -Depth 4
162
+ `;
163
+
164
+ export function parseWindowsBleScan(text, source = windowsBleSource) {
165
+ const lines = String(text ?? '').trim().split(/\r?\n/).filter(Boolean);
166
+ try {
167
+ const parsed = JSON.parse(lines.at(-1) ?? '[]');
168
+ const rows = Array.isArray(parsed) ? parsed : parsed ? [parsed] : [];
169
+ const devices = new Map();
170
+ for (const row of rows) {
171
+ if (!row?.address) continue;
172
+ const address = String(row.address).toLowerCase();
173
+ devices.set(address, { address, name: typeof row.name === 'string' && row.name ? row.name : null, signalDbm: Number.isFinite(Number(row.signalDbm)) ? Number(row.signalDbm) : null, detectionCase: 'nearby-bluetooth-advertisement', source });
174
+ }
175
+ return { available: true, count: devices.size, devices: [...devices.values()], source, scope: 'nearby Bluetooth LE advertisements received passively by the Windows OS during this observation only; Classic Bluetooth is not scanned and identifiers are not retained after the command exits', ...(devices.size ? {} : { reason: 'No passive BLE advertisements were observed during the scan window.' }) };
176
+ } catch {
177
+ return unavailable('Windows returned Bluetooth scan output Hawk could not reliably interpret.', source);
178
+ }
179
+ }
180
+
181
+ async function scanBluetooth() {
182
+ if (process.platform === 'linux') {
183
+ const source = 'hcitool lescan --passive --duplicates';
184
+ try {
185
+ const { stdout } = await execFileAsync('hcitool', ['lescan', '--passive', '--duplicates'], { timeout: 6000, maxBuffer: 1024 * 1024 });
186
+ return parseHciLeScan(stdout, source);
187
+ } catch (error) {
188
+ const partial = parseHciLeScan(error?.stdout, source);
189
+ if (partial.devices.length) return partial;
190
+ const reason = error?.code === 'ENOENT' ? 'hcitool is unavailable; no Bluetooth scan was started.' : error?.killed || error?.code === 'ETIMEDOUT' ? 'The passive Bluetooth observation window ended without advertisements.' : 'The Bluetooth adapter or passive LE scan is unavailable or denied.';
191
+ return unavailable(reason, source);
192
+ }
193
+ }
194
+ if (process.platform === 'win32') {
195
+ try {
196
+ const { stdout } = await execFileAsync('powershell.exe', ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', windowsBleScript], { timeout: 9000, maxBuffer: 1024 * 1024, windowsHide: true });
197
+ return parseWindowsBleScan(stdout, windowsBleSource);
198
+ } catch (error) {
199
+ const output = `${error?.stdout ?? ''}\n${error?.stderr ?? ''}`;
200
+ const reason = error?.code === 'ENOENT' ? 'Windows PowerShell is unavailable; no Bluetooth scan was started.'
201
+ : error?.killed || error?.code === 'ETIMEDOUT' ? 'The passive Bluetooth observation window timed out.'
202
+ : /access|denied|capability|disabled/i.test(output) ? 'Windows denied passive Bluetooth scanning; check Bluetooth settings, adapter support, and app permissions.'
203
+ : 'The Windows Bluetooth adapter or passive LE watcher is unavailable.';
204
+ return unavailable(reason, windowsBleSource);
205
+ }
206
+ }
207
+ if (process.platform === 'darwin') return unavailable('CoreBluetooth does not expose a passive-only scan mode through Hawk’s CLI adapter; active discovery was not started.', 'CoreBluetooth passive scan (unavailable)');
208
+ return unavailable('This operating system has no supported passive Bluetooth LE scan adapter.', 'Bluetooth LE');
209
+ }
210
+
211
+ /** Parse the rows emitted by passive `hcitool lescan`. */
212
+ export function parseHciLeScan(text, source = 'hcitool lescan --passive --duplicates') {
213
+ const devices = new Map();
214
+ for (const line of String(text ?? '').split(/\r?\n/)) {
215
+ const match = line.match(/^\s*([\da-f]{2}(?::[\da-f]{2}){5})\s+(.+?)\s*$/i);
216
+ if (!match) continue;
217
+ const address = match[1].toLowerCase();
218
+ const name = match[2].trim();
219
+ devices.set(address, { address, name: name && name !== '(unknown)' ? name : null, signalDbm: null, detectionCase: 'nearby-bluetooth-advertisement', source });
220
+ }
221
+ return { available: true, count: devices.size, devices: [...devices.values()], source, scope: 'nearby Bluetooth LE advertisements received passively during this observation only; Classic Bluetooth is not scanned and device identifiers are not retained after the command exits', ...(devices.size ? {} : { reason: 'No passive BLE advertisements were observed during the scan window.' }) };
222
+ }
223
+
224
+ async function scanWifi() {
225
+ const source = process.platform === 'win32' ? 'netsh wlan show networks mode=bssid'
226
+ : process.platform === 'linux' ? 'iw dev <interface> scan passive'
227
+ : process.platform === 'darwin' ? 'airport -s' : null;
228
+ if (!source) return { available: false, count: null, networks: [], source, scope: 'nearby Wi-Fi access points visible to the monitored device', reason: 'This operating system has no Hawk Wi-Fi scan adapter.' };
229
+ try {
230
+ let stdout;
231
+ if (process.platform === 'win32') {
232
+ ({ stdout } = await execFileAsync('netsh.exe', ['wlan', 'show', 'networks', 'mode=bssid'], { timeout: 10000, maxBuffer: 2 * 1024 * 1024, windowsHide: true }));
233
+ } else if (process.platform === 'linux') {
234
+ const { stdout: devices } = await execFileAsync('iw', ['dev'], { timeout: 5000, maxBuffer: 256 * 1024 });
235
+ const interfaces = [...devices.matchAll(/^\s*Interface\s+(\S+)/gm)].map(match => match[1]);
236
+ if (!interfaces.length) return { available: false, count: null, networks: [], source: 'iw dev', scope: 'nearby Wi-Fi access points visible to the monitored device', reason: 'No wireless interface was reported by iw.' };
237
+ const results = await Promise.allSettled(interfaces.map(name => execFileAsync('iw', ['dev', name, 'scan', 'passive'], { timeout: 10000, maxBuffer: 2 * 1024 * 1024 })));
238
+ const completed = results.filter(result => result.status === 'fulfilled').map(result => result.value.stdout);
239
+ if (!completed.length) throw results.find(result => result.status === 'rejected')?.reason ?? new Error('No wireless scan completed.');
240
+ stdout = completed.join('\n');
241
+ } else {
242
+ const airport = '/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport';
243
+ ({ stdout } = await execFileAsync(airport, ['-s'], { timeout: 10000, maxBuffer: 2 * 1024 * 1024 }));
244
+ }
245
+ const parsed = process.platform === 'win32' ? parseWindowsWifiScan(stdout)
246
+ : process.platform === 'linux' ? parseIwWifiScan(stdout) : parseMacWifiScan(stdout);
247
+ if (!parsed.recognized) return { available: false, count: null, networks: [], source, scope: 'nearby Wi-Fi access points visible to the monitored device; no network is joined', reason: 'The operating system returned scan output Hawk could not reliably interpret.' };
248
+ return { available: true, count: parsed.networks.length, networks: parsed.networks, source, scope: 'nearby Wi-Fi access points visible to the monitored device; OS scan only, no network is joined or authenticated', ...(parsed.networks.length ? {} : { reason: 'The operating system reported no nearby access points.' }) };
249
+ } catch (error) {
250
+ const commandOutput = `${error?.stdout ?? ''}\n${error?.stderr ?? ''}`;
251
+ const reason = process.platform === 'win32' && /command was not found/i.test(commandOutput) ? 'The Windows netsh WLAN context is unavailable on this installation.'
252
+ : error?.code === 'ENOENT' ? 'The operating system Wi-Fi scan command is unavailable.'
253
+ : error?.killed || error?.code === 'ETIMEDOUT' ? 'The Wi-Fi scan timed out.'
254
+ : 'The wireless adapter or OS scan permission is unavailable or denied.';
255
+ return { available: false, count: null, networks: [], source, scope: 'nearby Wi-Fi access points visible to the monitored device; no network is joined', reason };
256
+ }
257
+ }
258
+
259
+ /** Scan nearby radio surroundings using OS scan interfaces; never joins a network or connects to a device. */
260
+ export async function scanNearby() {
261
+ const [wifi, bluetooth] = await Promise.all([scanWifi(), scanBluetooth()]);
262
+ return { observedAt: new Date().toISOString(), wifi, bluetooth };
263
+ }
@@ -0,0 +1,30 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+
4
+ const execFileAsync = promisify(execFile);
5
+
6
+ export async function collectServices({ timeoutMs = 10000 } = {}) {
7
+ if (process.platform === 'win32') {
8
+ return { available: false, count: null, services: [], source: 'PowerShell Get-Service', reason: 'Windows service inventory is collected with the host adapter; call snapshotNode() on Windows.' };
9
+ }
10
+ try {
11
+ if (process.platform === 'darwin') {
12
+ const { stdout } = await execFileAsync('launchctl', ['list'], { timeout: timeoutMs, maxBuffer: 8 * 1024 * 1024 });
13
+ const services = stdout.split(/\r?\n/).slice(1).map(line => {
14
+ const match = line.trim().match(/^(\S+)\s+(\S+)\s+(.+)$/);
15
+ return match ? { pid: /^\d+$/.test(match[1]) ? Number(match[1]) : null, status: match[2], name: match[3] } : null;
16
+ }).filter(Boolean);
17
+ return { available: true, count: services.length, services, source: 'launchctl list', scope: 'launch agents and daemons visible in the current macOS bootstrap domain' };
18
+ }
19
+ const { stdout } = await execFileAsync('systemctl', ['list-units', '--type=service', '--state=running', '--no-legend', '--no-pager', '--plain'], { timeout: timeoutMs, maxBuffer: 8 * 1024 * 1024 });
20
+ const services = stdout.split(/\r?\n/).map(line => {
21
+ const match = line.trim().match(/^([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)(?:\s+(.*))?$/);
22
+ return match ? { name: match[1], load: match[2], active: match[3], sub: match[4], description: match[5] ?? null } : null;
23
+ }).filter(Boolean);
24
+ return { available: true, count: services.length, services, source: 'systemctl list-units --type=service --state=running', scope: 'running systemd services visible to this user' };
25
+ } catch (error) {
26
+ const source = process.platform === 'darwin' ? 'launchctl list' : 'systemctl list-units --type=service --state=running';
27
+ return { available: false, count: null, services: [], source, reason: error?.killed || error?.code === 'ETIMEDOUT' ? 'Service inventory timed out.' : `${source} is unavailable or denied (${error?.code || 'OS error'}).` };
28
+ }
29
+ }
30
+
package/src/types.d.ts ADDED
@@ -0,0 +1,216 @@
1
+ // Type declarations for si-hawk
2
+ // These MUST match the runtime behavior in src/*.js
3
+
4
+ export interface ParsedUA {
5
+ browser: string;
6
+ version: string | null;
7
+ engine: string;
8
+ os: string;
9
+ osVersion: string | null;
10
+ device: string;
11
+ brand: string;
12
+ model: string | null;
13
+ type: 'desktop' | 'mobile' | 'tablet' | 'bot';
14
+ bot: boolean;
15
+ }
16
+
17
+ export interface DeviceInfo {
18
+ language: string | null;
19
+ languages: string[] | null;
20
+ onLine: boolean | null;
21
+ cookieEnabled: boolean | null;
22
+ hardwareConcurrency: number | null;
23
+ deviceMemory: number | null;
24
+ maxTouchPoints: number;
25
+ pointerEnabled: boolean;
26
+ }
27
+
28
+ export interface ScreenInfo {
29
+ supported: boolean;
30
+ width: number | null;
31
+ height: number | null;
32
+ availWidth: number | null;
33
+ availHeight: number | null;
34
+ colorDepth: number | null;
35
+ pixelRatio: number | null;
36
+ orientation: string | null;
37
+ }
38
+
39
+ export interface TouchInfo {
40
+ supported: boolean;
41
+ touchSupport: boolean;
42
+ maxTouchPoints: number;
43
+ pointerEnabled: boolean;
44
+ }
45
+
46
+ export interface WebGLInfo {
47
+ supported: boolean;
48
+ version: string | null;
49
+ vendor: string | null;
50
+ renderer: string | null;
51
+ unmaskedVendor: string | null;
52
+ unmaskedRenderer: string | null;
53
+ }
54
+
55
+ export interface AudioInfo {
56
+ supported: boolean;
57
+ sampleRate: number | null;
58
+ channelCount: number | null;
59
+ contextSupport: boolean;
60
+ }
61
+
62
+ export interface StorageInfo {
63
+ supported: boolean;
64
+ localStorage: boolean;
65
+ sessionStorage: boolean;
66
+ indexedDB: boolean;
67
+ quota: number | Promise<number | undefined> | null;
68
+ usage: number | Promise<number | undefined> | null;
69
+ }
70
+
71
+ export interface NetworkInfo {
72
+ supported: boolean;
73
+ online: boolean | null;
74
+ connection: {
75
+ type: string | null;
76
+ downlink: number | null;
77
+ rtt: number | null;
78
+ saveData: boolean;
79
+ } | null;
80
+ }
81
+
82
+ export interface ServiceWorkerInfo {
83
+ supported: boolean;
84
+ }
85
+
86
+ export interface BatteryInfo {
87
+ supported: boolean;
88
+ }
89
+
90
+ export interface PerformanceInfo {
91
+ supported: boolean;
92
+ memory: {
93
+ usedJSHeapSize: number | null;
94
+ totalJSHeapSize: number | null;
95
+ jsHeapSizeLimit: number | null;
96
+ };
97
+ timing: Record<string, number> | null;
98
+ nowPrecision: number | null;
99
+ }
100
+
101
+ export interface Capabilities {
102
+ screen: ScreenInfo;
103
+ touch: TouchInfo;
104
+ webgl: WebGLInfo;
105
+ audio: AudioInfo;
106
+ storage: StorageInfo;
107
+ network: NetworkInfo;
108
+ sw: ServiceWorkerInfo;
109
+ battery: BatteryInfo;
110
+ performance: PerformanceInfo;
111
+ }
112
+
113
+ export interface FingerprintResult {
114
+ hash: string;
115
+ components: Record<string, string>;
116
+ }
117
+
118
+ export interface Snapshot {
119
+ detect: ParsedUA & DeviceInfo & Capabilities;
120
+ fingerprint: FingerprintResult;
121
+ timestamp: number;
122
+ }
123
+
124
+ export interface MonitorEvent {
125
+ type: 'visibility' | 'network' | 'connection' | 'battery';
126
+ [key: string]: any;
127
+ }
128
+
129
+ export interface NodeDeviceInfo {
130
+ name: string; platform: string; release: string; arch: string;
131
+ cpus: number; totalmem: number; freemem: number;
132
+ cpu: { model: string | null; logicalCores: number; utilizationPercent?: number | null; measurement?: { kind: 'measured'; source: string; windowMs: number } };
133
+ memory: { totalBytes: number; availableBytes: number; usedBytes: number; usedPercent: number | null };
134
+ nodeVersion: string; v8Version: string;
135
+ }
136
+ export interface NodeHostSnapshot extends NodeDeviceInfo {
137
+ manufacturer: string | null; model: string | null; deviceType: string | null; deviceTypeStatus: string;
138
+ cpu: NodeDeviceInfo['cpu'] & { utilizationPercent: number | null; measurement: { kind: 'measured'; source: string; windowMs: number } };
139
+ }
140
+ export interface NodeDeviceIdentity { available: boolean; name: string | null; manufacturer: string | null; model: string | null; deviceType: string | null; deviceTypeCategory?: string | null; source: string | null; deviceTypeStatus?: string; reason?: string; }
141
+ export interface NodeBatteryInfo { available: boolean; levelPercent: number | null; charging: boolean | null; powerSource?: string; batteryFlag?: number; batteries?: Array<{ capacity: number | null; status: string | null }>; source?: string | null; reason?: string; }
142
+ export interface NodeConnectedDevice { name: string; model: string | null; categories: string[]; status: string; devices: Array<{ name: string; status: string }>; }
143
+ export interface NodeProcess { pid: number; parentPid?: number; name: string; memoryBytes?: number; state?: string; elapsed?: string; source?: string; }
144
+ export interface NodeService { name: string; displayName?: string; status?: string; pid?: number | null; active?: string; sub?: string; description?: string | null; }
145
+ export interface NodeNetworkInterface { name: string; address: string; family: string | number; netmask: string; cidr: string | null; mac: string; internal: boolean; }
146
+ export interface NodeWifiConnection { interface: string | null; ssid: string; bssid: string | null; detectionCase: 'own-association'; signalPercent?: number | null; signalDbm?: number | null; radioType?: string | null; channel?: number | null; frequencyMHz?: number | null; receiveRateMbps?: number | null; transmitRateMbps?: number | null; }
147
+ export interface NodeNearbyWifiNetwork { ssid: string | null; bssid: string | null; detectionCase: 'nearby-access-point'; signalPercent: number | null; signalDbm: number | null; channel: number | null; securityType: string; radioType?: string | null; source: string; }
148
+ export interface NodeNearbyBluetoothDevice { address: string; name: string | null; detectionCase: 'nearby-bluetooth-advertisement'; signalDbm: number | null; source: string; }
149
+ export interface NodeNeighbor { address: string; mac: string | null; detectionCase: 'same-lan-neighbor'; interface?: string | null; state?: string | null; }
150
+ export interface NodeRouterClient { mac: string; name: string | null; addresses: string[]; interface: string; state: string; source: string; }
151
+ export interface NodeActiveApplication { available: boolean; pid: number | null; name: string | null; source: string | null; reason?: string; titleCollected: false; }
152
+ export interface NodeChanges {
153
+ baseline: boolean; activeApplicationChanged: { previous: { pid: number | null; name: string | null }; current: { pid: number | null; name: string | null } } | null; startedProcesses: NodeProcess[]; stoppedProcesses: NodeProcess[];
154
+ serviceChanges: Array<{ type: 'added' | 'removed' | 'state-changed'; service: NodeService }>;
155
+ wifiConnectionChanged: { previous: NodeWifiConnection[]; current: NodeWifiConnection[] } | null;
156
+ nearbyChanges: { newWifiNetworks: NodeNearbyWifiNetwork[]; removedWifiNetworks: NodeNearbyWifiNetwork[]; newBluetoothDevices: NodeNearbyBluetoothDevice[]; removedBluetoothDevices: NodeNearbyBluetoothDevice[] };
157
+ newNeighbors: NodeNeighbor[]; removedNeighbors: NodeNeighbor[];
158
+ newWifiClients: NodeRouterClient[]; disconnectedWifiClients: NodeRouterClient[];
159
+ }
160
+ export interface NodeSnapshot {
161
+ observedAt: string; source: string; host: NodeHostSnapshot;
162
+ storage: { available: boolean; volumeRoot: string | null; mountPoint: string | null; totalBytes?: number; availableBytes?: number; usedBytes?: number; usedPercent?: number | null; reason?: string };
163
+ deviceIdentity: NodeDeviceIdentity; battery: NodeBatteryInfo; activeApplication: NodeActiveApplication;
164
+ connectedDevices: { available: boolean; count: number | null; unit?: string; deviceNodeCount?: number | null; devices: NodeConnectedDevice[]; scope?: string; source?: string; reason?: string };
165
+ processes: { available: boolean; count: number | null; processes: NodeProcess[]; source?: string; scope?: string; reason?: string };
166
+ services: { available: boolean; count: number | null; services: NodeService[]; source?: string; scope?: string; reason?: string };
167
+ network: {
168
+ observedAt: string;
169
+ interfaces: { available: boolean; count: number; devices: NodeNetworkInterface[]; source: string };
170
+ wifiConnection: { available: boolean; count: number | null; connections: NodeWifiConnection[]; source: string | null; scope?: string; reason?: string };
171
+ nearby: { observedAt: string; wifi: { available: boolean; count: number | null; networks: NodeNearbyWifiNetwork[]; source: string | null; scope?: string; reason?: string } | null; bluetooth: { available: boolean; count: number | null; devices: NodeNearbyBluetoothDevice[]; source: string | null; scope?: string; reason?: string } | null; source?: string | null; reason?: string };
172
+ neighbors: { available: boolean; count: number | null; devices: NodeNeighbor[]; source: string; scope?: string; observedAt?: string; reason?: string };
173
+ router?: { available: boolean; count?: number | null; accessPointCount?: number; clients: NodeRouterClient[]; source: string; scope?: string; transport?: string; reason?: string };
174
+ };
175
+ sources: Record<string, string | null | undefined>; changes?: NodeChanges;
176
+ }
177
+ export function watchNode(options?: { intervalMs?: number; signal?: AbortSignal; sampleMs?: number; storagePath?: string; includeNetwork?: boolean; includeRouter?: boolean; includeNearby?: boolean }): AsyncGenerator<NodeSnapshot>;
178
+ export function watchScan(options?: { intervalMs?: number; signal?: AbortSignal }): AsyncGenerator<{ observedAt: string; baseline?: boolean; changes?: NodeChanges['nearbyChanges']; wifi: NonNullable<NodeSnapshot['network']>['nearby']['wifi']; bluetooth: NonNullable<NodeSnapshot['network']>['nearby']['bluetooth'] }>;
179
+ export function scanNearby(): Promise<{ observedAt: string; wifi: { available: boolean; count: number | null; networks: NodeNearbyWifiNetwork[]; source: string | null; scope?: string; reason?: string }; bluetooth: { available: boolean; count: number | null; devices: NodeNearbyBluetoothDevice[]; source: string | null; scope?: string; reason?: string } }>;
180
+ export function parseWindowsWifiScan(text: string): { networks: NodeNearbyWifiNetwork[]; recognized: boolean };
181
+ export function parseWindowsBleScan(text: string, source?: string): { available: boolean; count: number | null; devices: NodeNearbyBluetoothDevice[]; source: string; scope: string; reason?: string };
182
+ export function parseIwWifiScan(text: string): { networks: NodeNearbyWifiNetwork[]; recognized: boolean };
183
+ export function parseMacWifiScan(text: string): { networks: NodeNearbyWifiNetwork[]; recognized: boolean };
184
+ export function parseHciLeScan(text: string, source?: string): { available: boolean; count: number; devices: NodeNearbyBluetoothDevice[]; source: string; scope: string; reason?: string };
185
+ export function compareNodeSnapshots(previous: NodeSnapshot | null, current: NodeSnapshot): NodeChanges;
186
+
187
+ export function parseUserAgent(ua?: string | null): ParsedUA;
188
+ export function detectDevice(env?: any): DeviceInfo;
189
+ export function detectCapabilities(env?: any): Capabilities;
190
+ export function detect(env?: any): ParsedUA & DeviceInfo & Capabilities;
191
+ export function generateFingerprint(env?: any): FingerprintResult;
192
+ export function fingerprint(env?: any): FingerprintResult;
193
+ export function snapshot(env?: any): Snapshot;
194
+ export function monitor(callback: (event: MonitorEvent) => void, env?: any): () => void;
195
+ export function detectNode(): NodeDeviceInfo;
196
+ export function snapshotNode(options?: { sampleMs?: number; storagePath?: string; includeNetwork?: boolean; includeRouter?: boolean; includeNearby?: boolean }): Promise<NodeSnapshot>;
197
+ /** Collect a point-in-time report about the current host device. */
198
+ export function hawkInv(options?: { sampleMs?: number; storagePath?: string; includeNetwork?: boolean; includeRouter?: boolean; includeNearby?: boolean }): Promise<NodeSnapshot>;
199
+ /** Observe nearby Wi-Fi access points and passive Bluetooth LE advertisements. */
200
+ export function hawkEvo(): ReturnType<typeof scanNearby>;
201
+ export function fingerprintNode(): string;
202
+ export function djb2(str: string, seed?: number): string;
203
+ export function tryFn<T>(fn: () => T, fallback?: T): T;
204
+ export function isObject(v: unknown): boolean;
205
+ export function isString(v: unknown): boolean;
206
+ export function hasProperty(obj: object, prop: string): boolean;
207
+
208
+ declare const hawk: {
209
+ detect: typeof detect;
210
+ fingerprint: typeof fingerprint;
211
+ snapshot: typeof snapshot;
212
+ monitor: typeof monitor;
213
+ inv: typeof hawkInv;
214
+ evo: typeof hawkEvo;
215
+ };
216
+ export default hawk;
package/src/util.js ADDED
@@ -0,0 +1,16 @@
1
+ // Utility helpers
2
+ export function tryFn(fn, fallback = null) {
3
+ try { return fn(); } catch { return fallback; }
4
+ }
5
+
6
+ export function isObject(v) {
7
+ return typeof v === 'object' && v !== null;
8
+ }
9
+
10
+ export function isString(v) {
11
+ return typeof v === 'string';
12
+ }
13
+
14
+ export function hasProperty(obj, prop) {
15
+ return Object.prototype.hasOwnProperty.call(obj, prop);
16
+ }