dsh-folia 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,254 @@
1
+ /**
2
+ * desktop-context.js — 屏幕感知(v1.2 Level 1 前台窗口 / Level 2 屏幕 OCR)。
3
+ *
4
+ * **默认全关**:没有任何轮询在这里开始;只有路由在设置 `screen.mode !== 'off'` 时才调用。
5
+ * 两条通道都走 Windows PowerShell(不新增原生依赖):
6
+ *
7
+ * Level 1 $foreground → user32 GetForegroundWindow / GetWindowText / 进程名
8
+ * 只取「应用名 + 标题摘要」,30–60 秒一次;不读窗口内容。
9
+ *
10
+ * Level 2 $ocr → System.Drawing 截屏到**内存** + Windows.Media.Ocr 识别,
11
+ * OCR 文本只在本地;截图不落盘、不上传、不进日志;密码管理器/银行等按进程名跳过;
12
+ * 锁屏/LogonUI 直接停。
13
+ *
14
+ * 诚实边界:只能读「前台窗口标题 + 屏幕像素」。读不到别的 App 的内部数据;OCR 对复杂界面/
15
+ * 小字/游戏画面会不准。失败一律回 `{ok:false, reason}`,不假装看到了。
16
+ */
17
+ import { spawn } from 'node:child_process';
18
+ import { existsSync } from 'node:fs';
19
+ import { join } from 'node:path';
20
+
21
+ /** 默认跳过的进程名(小写比较):密码管理器 / 银行 / 远程桌面 / 锁屏。 */
22
+ export const SENSITIVE_APPS = Object.freeze([
23
+ '1password', '1password7', 'bitwarden', 'keepass', 'keepassxc', 'lastpass', 'dashlane',
24
+ 'enpass', 'roboform', 'nordpass', 'mstsc', 'logonui', 'lockapp', 'credentialuibroker',
25
+ 'bank', 'banking', 'alipay', 'wechatpay', 'wallet',
26
+ ]);
27
+
28
+ /** 标题里出现这些词也跳过(进程名拿不到时的第二道闸)。 */
29
+ export const SENSITIVE_TITLE_WORDS = Object.freeze([
30
+ '密码', '银行', '支付', '登录', 'password', 'bank', 'sign in', 'login', 'wallet',
31
+ ]);
32
+
33
+ /** 前台窗口脚本:只输出 JSON;任何异常都以 ok:false 收尾,不把堆栈写进日志。 */
34
+ const FOREGROUND_SCRIPT = String.raw`
35
+ $ErrorActionPreference = 'Stop'
36
+ [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
37
+ Add-Type @"
38
+ using System;
39
+ using System.Text;
40
+ using System.Runtime.InteropServices;
41
+ public class FoliaForeground {
42
+ [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
43
+ [DllImport("user32.dll")] public static extern int GetWindowTextLength(IntPtr h);
44
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetWindowText(IntPtr h, StringBuilder s, int max);
45
+ [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
46
+ }
47
+ "@
48
+ try {
49
+ $h = [FoliaForeground]::GetForegroundWindow()
50
+ if ($h -eq [IntPtr]::Zero) { '{"ok":false,"reason":"no-foreground"}' | Write-Output; exit 0 }
51
+ $len = [FoliaForeground]::GetWindowTextLength($h)
52
+ $sb = New-Object System.Text.StringBuilder ($len + 2)
53
+ [void][FoliaForeground]::GetWindowText($h, $sb, $sb.Capacity)
54
+ $pidOut = 0
55
+ [void][FoliaForeground]::GetWindowThreadProcessId($h, [ref]$pidOut)
56
+ $app = ''
57
+ try { $app = (Get-Process -Id $pidOut -ErrorAction Stop).ProcessName } catch { $app = '' }
58
+ $payload = @{ ok = $true; pid = [int]$pidOut; app = [string]$app; title = [string]$sb.ToString() }
59
+ $payload | ConvertTo-Json -Compress
60
+ } catch {
61
+ '{"ok":false,"reason":"foreground-failed"}' | Write-Output
62
+ }
63
+ `;
64
+
65
+ /** 截屏 + OCR:全程内存(InMemoryRandomAccessStream),不写临时文件。 */
66
+ const OCR_SCRIPT = String.raw`
67
+ $ErrorActionPreference = 'Stop'
68
+ [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
69
+ Add-Type -AssemblyName System.Drawing
70
+ Add-Type -AssemblyName System.Windows.Forms
71
+ Add-Type -AssemblyName System.Runtime.WindowsRuntime
72
+ $null = [Windows.Storage.Streams.InMemoryRandomAccessStream, Windows.Storage, ContentType = WindowsRuntime]
73
+ $null = [Windows.Graphics.Imaging.BitmapDecoder, Windows.Graphics.Imaging, ContentType = WindowsRuntime]
74
+ $null = [Windows.Media.Ocr.OcrEngine, Windows.Foundation, ContentType = WindowsRuntime]
75
+ $null = [Windows.Globalization.Language, Windows.Globalization, ContentType = WindowsRuntime]
76
+ function Await($op, $type) {
77
+ $task = [System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object {
78
+ $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation` + "`" + `1'
79
+ } | Select-Object -First 1
80
+ $task = $task.MakeGenericMethod($type)
81
+ $t = $task.Invoke($null, @($op))
82
+ $t.Wait(-1) | Out-Null
83
+ return $t.Result
84
+ }
85
+ try {
86
+ $engine = [Windows.Media.Ocr.OcrEngine]::TryCreateFromUserProfileLanguages()
87
+ if (-not $engine) { '{"ok":false,"reason":"no-ocr-engine"}' | Write-Output; exit 0 }
88
+ $bounds = [System.Windows.Forms.SystemInformation]::VirtualScreen
89
+ if ($bounds.Width -lt 8 -or $bounds.Height -lt 8) { '{"ok":false,"reason":"no-screen"}' | Write-Output; exit 0 }
90
+ $bmp = New-Object System.Drawing.Bitmap($bounds.Width, $bounds.Height)
91
+ $g = [System.Drawing.Graphics]::FromImage($bmp)
92
+ $g.CopyFromScreen($bounds.Left, $bounds.Top, 0, 0, $bmp.Size)
93
+ $ms = New-Object System.IO.MemoryStream
94
+ $bmp.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)
95
+ $bytes = $ms.ToArray()
96
+ $g.Dispose(); $bmp.Dispose(); $ms.Dispose()
97
+ $stream = New-Object Windows.Storage.Streams.InMemoryRandomAccessStream
98
+ $writer = New-Object Windows.Storage.Streams.DataWriter($stream)
99
+ $writer.WriteBytes($bytes)
100
+ [void](Await ($writer.StoreAsync()) 'UInt32')
101
+ $writer.DetachStream() | Out-Null
102
+ $stream.Seek(0) | Out-Null
103
+ $decoder = Await ([Windows.Graphics.Imaging.BitmapDecoder]::CreateAsync($stream)) 'Windows.Graphics.Imaging.BitmapDecoder'
104
+ $software = Await ($decoder.GetSoftwareBitmapAsync()) 'Windows.Graphics.Imaging.SoftwareBitmap'
105
+ $result = Await ($engine.RecognizeAsync($software)) 'Windows.Media.Ocr.OcrResult'
106
+ $lines = @()
107
+ foreach ($line in $result.Lines) { $lines += [string]$line.Text }
108
+ $payload = @{ ok = $true; lines = $lines }
109
+ $payload | ConvertTo-Json -Compress -Depth 4
110
+ } catch {
111
+ '{"ok":false,"reason":"ocr-failed"}' | Write-Output
112
+ }
113
+ `;
114
+
115
+ /** 找 Windows PowerShell(pwsh 7 加载 WinRT 不稳,固定用 5.1)。 */
116
+ export function resolvePowerShell() {
117
+ const fixed = join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
118
+ if (existsSync(fixed)) return fixed;
119
+ return 'powershell.exe';
120
+ }
121
+
122
+ /**
123
+ * 跑一段 PowerShell,拿最后一行 JSON。永不抛(失败回 `{ok:false}`)。
124
+ * @param {string} script
125
+ * @param {{timeoutMs?:number, run?:Function}} [options]
126
+ */
127
+ export function runPowerShellJson(script, options = {}) {
128
+ const timeoutMs = Math.max(2000, Math.min(30000, Number(options.timeoutMs) || 12000));
129
+ if (typeof options.run === 'function') {
130
+ // 判据注入:`run(script, timeoutMs) => {stdout, stderr, code}`(同步)
131
+ try {
132
+ const result = options.run(script, timeoutMs) || {};
133
+ return parseJsonLine(String(result.stdout || ''));
134
+ } catch (error) {
135
+ return { ok: false, reason: 'runner-error', error: String((error && error.message) || error).slice(0, 120) };
136
+ }
137
+ }
138
+ return new Promise((resolveP) => {
139
+ let child;
140
+ try {
141
+ child = spawn(resolvePowerShell(), [
142
+ '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', script,
143
+ ], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
144
+ } catch (error) {
145
+ resolveP({ ok: false, reason: 'spawn-failed', error: String((error && error.message) || error).slice(0, 120) });
146
+ return;
147
+ }
148
+ let out = '';
149
+ let err = '';
150
+ const timer = setTimeout(() => {
151
+ // pid 落地才 kill(未起来时裸 kill 会抛错/挂住事件循环;与 verify-child-kill 同一条纪律)
152
+ try { if (child.pid !== undefined) child.kill(); } catch { /* ignore */ }
153
+ }, timeoutMs);
154
+ child.stdout.on('data', (chunk) => { out += chunk; });
155
+ child.stderr.on('data', (chunk) => { err = (err + chunk).slice(-500); });
156
+ child.on('error', () => {
157
+ clearTimeout(timer);
158
+ resolveP({ ok: false, reason: 'spawn-failed' });
159
+ });
160
+ child.on('close', (code) => {
161
+ clearTimeout(timer);
162
+ const parsed = parseJsonLine(out);
163
+ if (parsed && parsed.ok !== undefined) { resolveP(parsed); return; }
164
+ resolveP({ ok: false, reason: code === 0 ? 'bad-output' : 'ps-exit-' + code });
165
+ });
166
+ });
167
+ }
168
+
169
+ function parseJsonLine(text) {
170
+ const lines = String(text || '').split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
171
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
172
+ if (!lines[i].startsWith('{')) continue;
173
+ try { return JSON.parse(lines[i]); } catch { /* 继续往上找 */ }
174
+ }
175
+ return null;
176
+ }
177
+
178
+ /** 是否敏感应用(进程名或标题命中)。 */
179
+ export function isSensitiveApp(app, title = '') {
180
+ const name = String(app || '').toLowerCase().trim();
181
+ if (name && SENSITIVE_APPS.some((item) => name === item || name.includes(item))) return true;
182
+ const text = String(title || '').toLowerCase();
183
+ return SENSITIVE_TITLE_WORDS.some((word) => text.includes(word.toLowerCase()));
184
+ }
185
+
186
+ /** 锁屏 / 登录界面(这时必须停止采样,也不该截屏)。 */
187
+ export function isLockScreen(app, title = '') {
188
+ const name = String(app || '').toLowerCase();
189
+ const text = String(title || '').toLowerCase();
190
+ return ['lockapp', 'logonui', 'winlogon'].includes(name) || /锁屏|lock screen|sign-in|登录/.test(text);
191
+ }
192
+
193
+ /**
194
+ * Level 1:读前台应用 + 标题摘要。
195
+ * @param {{run?:Function}} [options]
196
+ * @returns {Promise<{ok:boolean, app?:string, title?:string, pid?:number, sensitive?:boolean, locked?:boolean, reason?:string}>}
197
+ */
198
+ export async function readForegroundWindow(options = {}) {
199
+ const raw = await runPowerShellJson(FOREGROUND_SCRIPT, { timeoutMs: 6000, run: options.run });
200
+ if (!raw || raw.ok !== true) return { ok: false, reason: (raw && raw.reason) || 'foreground-failed' };
201
+ const app = String(raw.app || '').slice(0, 60);
202
+ const title = String(raw.title || '').replace(/\s+/g, ' ').trim().slice(0, 120);
203
+ return {
204
+ ok: true,
205
+ app,
206
+ title,
207
+ pid: Number(raw.pid) || 0,
208
+ sensitive: isSensitiveApp(app, title),
209
+ locked: isLockScreen(app, title),
210
+ };
211
+ }
212
+
213
+ /**
214
+ * Level 2:截屏 + OCR(内存直读,不落盘)。
215
+ * @param {{run?:Function, maxChars?:number}} [options]
216
+ * @returns {Promise<{ok:boolean, text?:string, lines?:string[], chars?:number, reason?:string}>}
217
+ */
218
+ export async function captureScreenOcr(options = {}) {
219
+ const raw = await runPowerShellJson(OCR_SCRIPT, { timeoutMs: 20000, run: options.run });
220
+ if (!raw || raw.ok !== true) return { ok: false, reason: (raw && raw.reason) || 'ocr-failed' };
221
+ const lines = Array.isArray(raw.lines)
222
+ ? raw.lines.map((line) => String(line || '').replace(/\s+/g, ' ').trim()).filter(Boolean)
223
+ : [];
224
+ const maxChars = Math.max(40, Math.min(2000, Number(options.maxChars) || 600));
225
+ const text = lines.join('\n').slice(0, maxChars);
226
+ if (!text.trim()) return { ok: false, reason: 'ocr-empty' };
227
+ return { ok: true, text, lines, chars: [...text].length };
228
+ }
229
+
230
+ /** 观察记录文本:应用名 + 标题摘要(去掉窗口标题里的私密细节?不——只截断)。 */
231
+ export function foregroundObservation(fg) {
232
+ if (!fg || fg.ok !== true) return '';
233
+ const app = String(fg.app || '').trim();
234
+ if (!app) return '';
235
+ const title = String(fg.title || '').trim();
236
+ const text = title ? `前台应用:${app} · ${title.slice(0, 40)}` : `前台应用:${app}`;
237
+ return text.slice(0, 120);
238
+ }
239
+
240
+ /** OCR 观察文本:一行摘要,不存整屏原文。 */
241
+ export function ocrObservation(ocr) {
242
+ if (!ocr || ocr.ok !== true) return '';
243
+ const first = String(ocr.text || '').split('\n').map((line) => line.trim()).filter(Boolean).slice(0, 2).join(' / ');
244
+ if (!first) return '';
245
+ return ('屏幕文字摘要:' + first).slice(0, 160);
246
+ }
247
+
248
+ /** 采样节奏:Level 1 30–60 秒,Level 2 2–5 分钟(任务书 §7)。 */
249
+ export const OBSERVE_RULES = Object.freeze({
250
+ foregroundMs: 45000,
251
+ ocrMs: 3 * 60 * 1000,
252
+ /** 同一应用+标题在这段时间内不重复写观察记录(避免刷屏)。 */
253
+ dedupeMs: 10 * 60 * 1000,
254
+ });