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/windows.js ADDED
@@ -0,0 +1,201 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+
4
+ const execFileAsync = promisify(execFile);
5
+ const POWERSHELL_SCRIPT = String.raw`
6
+ $ErrorActionPreference = 'Stop'
7
+ $ProgressPreference = 'SilentlyContinue'
8
+ $result = [ordered]@{}
9
+ $systemRoot = $env:SystemRoot
10
+ $pnputil = Join-Path $systemRoot 'System32\\pnputil.exe'
11
+
12
+ # PnPUtil returns the live connected-container list and child PnP nodes as XML.
13
+ try {
14
+ $lines = & $pnputil /enum-containers /connected /devices /format xml 2>$null
15
+ $exitCode = $LASTEXITCODE
16
+ if ($exitCode -ne 0) { throw "PnPUtil exited with code $exitCode." }
17
+ [xml]$doc = $lines -join [Environment]::NewLine
18
+ $containers = @($doc.PnpUtil.Container)
19
+ $mapped = @($containers | ForEach-Object {
20
+ # PowerShell's XML adapter returns the leaf text as strings. Reading
21
+ # InnerText here produced null categories, which hid the actual type.
22
+ $categories = @($_.Categories.Category | ForEach-Object { [string]$_ })
23
+ $nodes = @($_.Devices.Device | ForEach-Object {
24
+ [pscustomobject]@{ name=$_.DeviceDescription; status=$_.Status }
25
+ })
26
+ [pscustomobject]@{
27
+ name=$_.Description
28
+ model=$_.ModelName
29
+ categories=$categories
30
+ status=$_.Status
31
+ devices=$nodes
32
+ }
33
+ })
34
+ $deviceNodeCount = 0
35
+ foreach ($container in $mapped) { $deviceNodeCount += $container.devices.Count }
36
+ $result.inventory = [pscustomobject]@{
37
+ available=$true
38
+ count=$mapped.Count
39
+ unit='connected-device-container'
40
+ deviceNodeCount=$deviceNodeCount
41
+ devices=$mapped
42
+ scope='Windows PnP containers filtered as connected; child PnP nodes and statuses are listed per container'
43
+ source='pnputil /enum-containers /connected /devices /format xml'
44
+ }
45
+ } catch {
46
+ $result.inventory = [pscustomobject]@{
47
+ available=$false; count=$null; unit='connected-device-container';
48
+ deviceNodeCount=$null; devices=@();
49
+ scope='Windows PnP connected containers'; source='pnputil /enum-containers /connected /devices /format xml';
50
+ reason=$_.Exception.Message
51
+ }
52
+ }
53
+
54
+ # Use the system container category (for example, Computer.Notebook) verbatim.
55
+ $hostContainer = $null
56
+ if ($result.inventory.available) {
57
+ $hostContainer = @($result.inventory.devices | Where-Object { @($_.categories) -match '^Computer\.' } | Select-Object -First 1)[0]
58
+ }
59
+ try {
60
+ $bios = Get-ItemProperty -Path 'HKLM:\\HARDWARE\\DESCRIPTION\\System\\BIOS' -Name SystemManufacturer,SystemProductName -ErrorAction Stop
61
+ $manufacturer = $bios.SystemManufacturer
62
+ $biosModel = $bios.SystemProductName
63
+ } catch {
64
+ $manufacturer = $null
65
+ $biosModel = $null
66
+ }
67
+ $deviceTypeCategory = if ($hostContainer) { @($hostContainer.categories | Where-Object { $_ -match '^Computer\.' } | Select-Object -First 1)[0] } else { $null }
68
+ $deviceType = if ($deviceTypeCategory) { $deviceTypeCategory.Substring('Computer.'.Length).ToLowerInvariant() } else { $null }
69
+ $model = if ($hostContainer -and $hostContainer.model) { $hostContainer.model } else { $biosModel }
70
+ $deviceName = if ($hostContainer -and $hostContainer.name) { $hostContainer.name } else { $env:COMPUTERNAME }
71
+ $result.identity = [pscustomobject]@{
72
+ available=([bool]$deviceName -or [bool]$model -or [bool]$deviceTypeCategory)
73
+ name=$deviceName
74
+ manufacturer=$manufacturer
75
+ model=$model
76
+ deviceType=$deviceType
77
+ deviceTypeCategory=$deviceTypeCategory
78
+ source=if ($hostContainer) { 'PnPUtil connected-container XML; model/manufacturer from Windows BIOS registry' } else { 'Windows BIOS registry and COMPUTERNAME environment value' }
79
+ deviceTypeStatus=if ($deviceTypeCategory) { 'reported by Windows PnP container category' } else { 'Windows returned no computer chassis category' }
80
+ }
81
+
82
+ # GetSystemPowerStatus returns the system-reported percentage, or 255 when unknown.
83
+ try {
84
+ $native = @'
85
+ using System;
86
+ using System.Runtime.InteropServices;
87
+ [StructLayout(LayoutKind.Sequential)]
88
+ public struct HawkSystemPowerStatus { public byte ACLineStatus; public byte BatteryFlag; public byte BatteryLifePercent; public byte SystemStatusFlag; public uint BatteryLifeTime; public uint BatteryFullLifeTime; }
89
+ public static class HawkPowerApi { [DllImport("kernel32.dll", SetLastError=true)] public static extern bool GetSystemPowerStatus(out HawkSystemPowerStatus status); }
90
+ '@
91
+ Add-Type -TypeDefinition $native -ErrorAction Stop
92
+ $power = New-Object HawkSystemPowerStatus
93
+ if (-not [HawkPowerApi]::GetSystemPowerStatus([ref]$power)) { throw "GetSystemPowerStatus failed with Win32 error $([Runtime.InteropServices.Marshal]::GetLastWin32Error())" }
94
+ $hasBattery = ($power.BatteryFlag -band 128) -eq 0
95
+ $percent = if ($power.BatteryLifePercent -le 100) { [int]$power.BatteryLifePercent } else { $null }
96
+ $charging = if ($power.BatteryFlag -eq 255) { $null } else { (($power.BatteryFlag -band 8) -ne 0) }
97
+ $ac = switch ([int]$power.ACLineStatus) { 0 {'offline'} 1 {'online'} default {'unknown'} }
98
+ $result.battery = [pscustomobject]@{
99
+ available=$hasBattery
100
+ levelPercent=$percent
101
+ charging=$charging
102
+ powerSource=$ac
103
+ batteryFlag=[int]$power.BatteryFlag
104
+ source='GetSystemPowerStatus'
105
+ reason=if (-not $hasBattery) {'Windows reports no system battery.'} elseif ($null -eq $percent) {'Windows returned an unknown charge level.'} else {$null}
106
+ }
107
+ } catch {
108
+ $result.battery = [pscustomobject]@{ available=$false; levelPercent=$null; charging=$null; powerSource='unknown'; source='GetSystemPowerStatus'; reason=$_.Exception.Message }
109
+ }
110
+
111
+ # Get-Process supplies process names and resident bytes without command lines.
112
+ try {
113
+ $processRows = @(Get-Process -ErrorAction Stop | ForEach-Object {
114
+ [pscustomobject]@{ pid=[int]$_.Id; name=[string]$_.ProcessName; memoryBytes=[long]$_.WorkingSet64; source='Get-Process' }
115
+ })
116
+ $result.processes = [pscustomobject]@{ available=$true; count=$processRows.Count; processes=$processRows; source='PowerShell Get-Process ProcessName,Id,WorkingSet64'; scope='running processes visible to Get-Process in this execution context; command-line arguments are excluded' }
117
+ } catch {
118
+ $result.processes = [pscustomobject]@{ available=$false; count=$null; processes=@(); source='PowerShell Get-Process'; reason='Windows process inventory was denied or unavailable.' }
119
+ }
120
+ try {
121
+ $serviceRows = @(Get-Service -ErrorAction Stop | ForEach-Object {
122
+ [pscustomobject]@{ name=[string]$_.Name; displayName=[string]$_.DisplayName; status=[string]$_.Status }
123
+ })
124
+ $result.services = [pscustomobject]@{ available=$true; count=$serviceRows.Count; services=$serviceRows; source='PowerShell Get-Service Name,DisplayName,Status'; scope='Windows services visible to Get-Service in this execution context, including stopped services' }
125
+ } catch {
126
+ $result.services = [pscustomobject]@{ available=$false; count=$null; services=@(); source='PowerShell Get-Service'; reason=$_.Exception.Message }
127
+ }
128
+
129
+ # Report only the foreground process identity; never read the window title.
130
+ try {
131
+ $nativeForeground = @'
132
+ using System;
133
+ using System.Runtime.InteropServices;
134
+ public static class HawkForegroundApi {
135
+ [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
136
+ [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hwnd, out uint processId);
137
+ }
138
+ '@
139
+ Add-Type -TypeDefinition $nativeForeground -ErrorAction Stop
140
+ $hwnd = [HawkForegroundApi]::GetForegroundWindow()
141
+ [uint32]$foregroundPid = 0
142
+ if ($hwnd -eq [IntPtr]::Zero -or [HawkForegroundApi]::GetWindowThreadProcessId($hwnd, [ref]$foregroundPid) -eq 0) { throw 'Windows returned no foreground application.' }
143
+ $foreground = Get-Process -Id $foregroundPid -ErrorAction Stop
144
+ $result.activeApplication = [pscustomobject]@{ available=$true; pid=[int]$foregroundPid; name=[string]$foreground.ProcessName; source='user32 GetForegroundWindow/GetWindowThreadProcessId and Get-Process'; titleCollected=$false }
145
+ } catch {
146
+ $result.activeApplication = [pscustomobject]@{ available=$false; pid=$null; name=$null; source='user32 foreground-window process ID and Get-Process'; reason=$_.Exception.Message; titleCollected=$false }
147
+ }
148
+
149
+ $result | ConvertTo-Json -Depth 8 -Compress
150
+ `;
151
+
152
+ function queryFailure(error, source) {
153
+ let reason = 'Windows interface query failed.';
154
+ if (error?.killed || error?.code === 'ETIMEDOUT') reason = 'Windows interface query timed out.';
155
+ else if (typeof error?.code === 'number') reason = `Windows interface returned exit code ${error.code}.`;
156
+ else if (typeof error?.code === 'string') reason = `Windows interface failed (${error.code}).`;
157
+ return { available: false, reason, source };
158
+ }
159
+
160
+ /** Read fixed, read-only Windows system interfaces; unknown values remain null. */
161
+ export async function collectWindowsTelemetry({ timeoutMs = 60000 } = {}) {
162
+ if (process.platform !== 'win32') return null;
163
+ const systemRoot = process.env.SystemRoot || 'C:\\Windows';
164
+ const executable = `${systemRoot}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
165
+ const encoded = Buffer.from(POWERSHELL_SCRIPT, 'utf16le').toString('base64');
166
+ try {
167
+ let stdout;
168
+ try {
169
+ ({ stdout } = await execFileAsync(executable, [
170
+ '-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', encoded,
171
+ ], { windowsHide: true, timeout: timeoutMs, maxBuffer: 8 * 1024 * 1024 }));
172
+ } catch (error) {
173
+ // PowerShell can return useful JSON while also exiting non-zero on a
174
+ // blocked PnP provider. Preserve structured per-source results if present.
175
+ if (!error.stdout) throw error;
176
+ stdout = error.stdout;
177
+ }
178
+ const result = JSON.parse(stdout.trim());
179
+ return {
180
+ identity: result.identity ?? { available: false, name: null, manufacturer: null, model: null, deviceType: null, source: 'Windows', reason: 'Windows returned no identity result.' },
181
+ connectedDevices: result.inventory ?? { available: false, count: null, deviceNodeCount: null, devices: [], source: 'PnPUtil', reason: 'Windows returned no inventory result.' },
182
+ battery: result.battery ?? { available: false, levelPercent: null, charging: null, powerSource: 'unknown', source: 'GetSystemPowerStatus', reason: 'Windows returned no battery result.' },
183
+ processes: result.processes ?? { available: false, count: null, processes: [], source: 'Get-Process', reason: 'Windows returned no process result.' },
184
+ services: result.services ?? { available: false, count: null, services: [], source: 'Get-Service', reason: 'Windows returned no service result.' },
185
+ activeApplication: result.activeApplication ?? { available: false, pid: null, name: null, source: 'Windows foreground process', reason: 'Windows returned no foreground process result.', titleCollected: false },
186
+ source: 'Windows system interfaces',
187
+ };
188
+ } catch (error) {
189
+ const reason = queryFailure(error, 'Windows PowerShell interface').reason;
190
+ return {
191
+ identity: { available: false, name: null, manufacturer: null, model: null, deviceType: null, source: 'Windows BIOS/PnP', reason },
192
+ connectedDevices: { available: false, count: null, deviceNodeCount: null, devices: [], scope: 'Windows PnP connected containers', source: 'PnPUtil', reason },
193
+ battery: { available: false, levelPercent: null, charging: null, powerSource: 'unknown', source: 'GetSystemPowerStatus', reason },
194
+ processes: { available: false, count: null, processes: [], source: 'Get-Process', reason },
195
+ services: { available: false, count: null, services: [], source: 'Get-Service', reason },
196
+ activeApplication: { available: false, pid: null, name: null, source: 'Windows foreground process', reason, titleCollected: false },
197
+ source: 'Windows system interfaces',
198
+ };
199
+ }
200
+ }
201
+