dsh-vigil 0.0.1 → 0.0.2

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.
@@ -1,194 +1,194 @@
1
- /**
2
- * Approval window-alert route.
3
- *
4
- * POST /api/dsh-vigil/alert-window { action: 'raise' | 'clear' | 'focus' }
5
- *
6
- * Capability chain (best-effort, never throws):
7
- * 1. Electron window control (Host runs in a desktop window process):
8
- * raise = restore/show/focus + temporary always-on-top;
9
- * focus = restore previous top state and bring the window forward;
10
- * clear = restore the previous always-on-top state.
11
- * 2. Fallback on Windows: `FlashWindowEx`. `raise` flashes the taskbar button
12
- * until it is cleared (or the window is focused); `focus` restores and
13
- * foregrounds the DSH window with `ShowWindow` + `SetForegroundWindow`.
14
- * 3. Otherwise report `unavailable`; the client falls back to window.focus()
15
- * and the notification click.
16
- *
17
- * @module dsh-vigil/alert-route
18
- */
19
-
20
- import { createRequire } from 'node:module'
21
- import { execFile } from 'node:child_process'
22
-
23
- /** Authenticated browser fetch path for the approval alert window action. */
24
- export const ALERT_WINDOW_PATH = '/api/dsh-vigil/alert-window'
25
-
26
- /** Load Electron from the Host process; null outside the Desktop main process. */
27
- function defaultLoadElectron() {
28
- try {
29
- return createRequire(import.meta.url)('electron')
30
- } catch {
31
- return null
32
- }
33
- }
34
-
35
- /**
36
- * PowerShell script that flashes/stops/foregrounds the DSH taskbar button.
37
- * The script is fixed text: no user input is ever interpolated into it.
38
- */
39
- function buildWindowScript(action) {
40
- // FLASHW_CAPTION 1, FLASHW_TRAY 2, FLASHW_TIMER 4, FLASHW_TIMERNOFG 8.
41
- // raise: keep flashing until the window is foreground. clear: stop.
42
- const flags = action === 'raise' ? '(0x1 -bor 0x2 -bor 0xC)' : '0x0'
43
- return [
44
- "$ErrorActionPreference = 'SilentlyContinue'",
45
- 'Add-Type @"',
46
- 'using System;',
47
- 'using System.Runtime.InteropServices;',
48
- 'public class VigilWin32 {',
49
- ' [StructLayout(LayoutKind.Sequential)] public struct FLASHWINFO { public uint cbSize; public IntPtr hwnd; public uint dwFlags; public uint uCount; public uint dwTimeout; }',
50
- ' [DllImport("user32.dll")] public static extern bool FlashWindowEx(ref FLASHWINFO pwfi);',
51
- ' [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);',
52
- ' [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd);',
53
- '}',
54
- '"@',
55
- `$flags = ${flags}`,
56
- "$wins = Get-Process | Where-Object { $_.MainWindowHandle -ne 0 -and ($_.MainWindowTitle -match 'DeepSeek|Harness' -or $_.ProcessName -match 'DeepSeek|Harness') }",
57
- 'foreach ($w in $wins) {',
58
- ' $info = New-Object VigilWin32+FLASHWINFO',
59
- ' $info.cbSize = [Runtime.InteropServices.Marshal]::SizeOf($info)',
60
- ' $info.hwnd = $w.MainWindowHandle',
61
- ' $info.dwFlags = $flags',
62
- ' $info.uCount = 0',
63
- ' $info.dwTimeout = 0',
64
- ' [void][VigilWin32]::FlashWindowEx([ref]$info)',
65
- '}',
66
- action === 'focus'
67
- ? 'foreach ($w in $wins) { [void][VigilWin32]::ShowWindow($w.MainWindowHandle, 9); [void][VigilWin32]::SetForegroundWindow($w.MainWindowHandle) }'
68
- : '',
69
- ].filter(Boolean).join('\n')
70
- }
71
-
72
- /** @returns {Promise<boolean>} whether the window script ran successfully */
73
- function defaultWindowAction(action) {
74
- return new Promise(resolve => {
75
- try {
76
- execFile(
77
- 'powershell.exe',
78
- ['-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-Command', buildWindowScript(action)],
79
- { timeout: 8000, windowsHide: true },
80
- error => resolve(!error),
81
- )
82
- } catch {
83
- resolve(false)
84
- }
85
- })
86
- }
87
-
88
- /**
89
- * Report how the Host can draw attention to the window right now.
90
- * @param {() => any} [loadElectron]
91
- * @param {NodeJS.Platform} [platform]
92
- * @returns {{ mode: 'electron'|'flash'|'unavailable', windows: number }}
93
- */
94
- export function probeAlertWindow(loadElectron = defaultLoadElectron, platform = process.platform) {
95
- try {
96
- const electron = loadElectron()
97
- const browserWindow = electron?.BrowserWindow
98
- const windows = typeof browserWindow?.getAllWindows === 'function'
99
- ? browserWindow.getAllWindows().filter(win => win && (typeof win.isDestroyed !== 'function' || !win.isDestroyed()))
100
- : []
101
- if (windows.length > 0) return { mode: 'electron', windows: windows.length }
102
- } catch {
103
- // fall through to the platform fallback
104
- }
105
- return platform === 'win32' ? { mode: 'flash', windows: 0 } : { mode: 'unavailable', windows: 0 }
106
- }
107
-
108
- /**
109
- * @param {{ loadElectron?: () => any, platform?: NodeJS.Platform, windowAction?: (action: 'raise'|'clear'|'focus') => Promise<boolean> }} [deps]
110
- * @returns {{ path: string, methods: string[], requestBody: 'buffered', fetch: (request: Request) => Promise<Response> }}
111
- */
112
- export function createAlertWindowRoute(deps = {}) {
113
- const loadElectron = deps.loadElectron ?? defaultLoadElectron
114
- const platform = deps.platform ?? process.platform
115
- const windowAction = deps.windowAction ?? defaultWindowAction
116
- /** Windows whose always-on-top state we changed, with the previous value. */
117
- const raised = new Map()
118
-
119
- const json = (payload, status = 200) => new Response(`${JSON.stringify(payload)}\n`, {
120
- status,
121
- headers: {
122
- 'content-type': 'application/json; charset=utf-8',
123
- 'cache-control': 'no-store',
124
- 'x-content-type-options': 'nosniff',
125
- },
126
- })
127
-
128
- const restoreTop = () => {
129
- for (const [win, previous] of raised) {
130
- try {
131
- win.setAlwaysOnTop(previous)
132
- } catch {
133
- // window already gone
134
- }
135
- }
136
- raised.clear()
137
- }
138
-
139
- return {
140
- path: ALERT_WINDOW_PATH,
141
- methods: ['POST'],
142
- requestBody: 'buffered',
143
- fetch: async request => {
144
- let body = null
145
- try {
146
- body = typeof request?.json === 'function' ? await request.json().catch(() => null) : null
147
- } catch {
148
- body = null
149
- }
150
- const action = body?.action === 'clear' ? 'clear' : body?.action === 'focus' ? 'focus' : 'raise'
151
-
152
- let windows = []
153
- try {
154
- const electron = loadElectron()
155
- const browserWindow = electron?.BrowserWindow
156
- windows = typeof browserWindow?.getAllWindows === 'function'
157
- ? browserWindow.getAllWindows().filter(win => win && (typeof win.isDestroyed !== 'function' || !win.isDestroyed()))
158
- : []
159
- } catch {
160
- windows = []
161
- }
162
-
163
- if (windows.length > 0) {
164
- if (action === 'clear') {
165
- restoreTop()
166
- return json({ ok: true, mode: 'electron', action, windows: windows.length })
167
- }
168
- if (action === 'focus') restoreTop()
169
- for (const win of windows) {
170
- try {
171
- if (typeof win.isMinimized === 'function' && win.isMinimized()) win.restore()
172
- if (typeof win.show === 'function') win.show()
173
- if (typeof win.focus === 'function') win.focus()
174
- if (action === 'raise' && typeof win.setAlwaysOnTop === 'function' && !raised.has(win)) {
175
- const previous = typeof win.isAlwaysOnTop === 'function' ? Boolean(win.isAlwaysOnTop()) : false
176
- raised.set(win, previous)
177
- if (!previous) win.setAlwaysOnTop(true, 'floating')
178
- }
179
- } catch {
180
- // best-effort per window
181
- }
182
- }
183
- return json({ ok: true, mode: 'electron', action, windows: windows.length })
184
- }
185
-
186
- if (platform === 'win32') {
187
- const ok = await windowAction(action)
188
- return json({ ok, mode: 'flash', action })
189
- }
190
-
191
- return json({ ok: false, mode: 'unavailable', action })
192
- },
193
- }
194
- }
1
+ /**
2
+ * Approval window-alert route.
3
+ *
4
+ * POST /api/dsh-vigil/alert-window { action: 'raise' | 'clear' | 'focus' }
5
+ *
6
+ * Capability chain (best-effort, never throws):
7
+ * 1. Electron window control (Host runs in a desktop window process):
8
+ * raise = restore/show/focus + temporary always-on-top;
9
+ * focus = restore previous top state and bring the window forward;
10
+ * clear = restore the previous always-on-top state.
11
+ * 2. Fallback on Windows: `FlashWindowEx`. `raise` flashes the taskbar button
12
+ * until it is cleared (or the window is focused); `focus` restores and
13
+ * foregrounds the DSH window with `ShowWindow` + `SetForegroundWindow`.
14
+ * 3. Otherwise report `unavailable`; the client falls back to window.focus()
15
+ * and the notification click.
16
+ *
17
+ * @module dsh-vigil/alert-route
18
+ */
19
+
20
+ import { createRequire } from 'node:module'
21
+ import { execFile } from 'node:child_process'
22
+
23
+ /** Authenticated browser fetch path for the approval alert window action. */
24
+ export const ALERT_WINDOW_PATH = '/api/dsh-vigil/alert-window'
25
+
26
+ /** Load Electron from the Host process; null outside the Desktop main process. */
27
+ function defaultLoadElectron() {
28
+ try {
29
+ return createRequire(import.meta.url)('electron')
30
+ } catch {
31
+ return null
32
+ }
33
+ }
34
+
35
+ /**
36
+ * PowerShell script that flashes/stops/foregrounds the DSH taskbar button.
37
+ * The script is fixed text: no user input is ever interpolated into it.
38
+ */
39
+ function buildWindowScript(action) {
40
+ // FLASHW_CAPTION 1, FLASHW_TRAY 2, FLASHW_TIMER 4, FLASHW_TIMERNOFG 8.
41
+ // raise: keep flashing until the window is foreground. clear: stop.
42
+ const flags = action === 'raise' ? '(0x1 -bor 0x2 -bor 0xC)' : '0x0'
43
+ return [
44
+ "$ErrorActionPreference = 'SilentlyContinue'",
45
+ 'Add-Type @"',
46
+ 'using System;',
47
+ 'using System.Runtime.InteropServices;',
48
+ 'public class VigilWin32 {',
49
+ ' [StructLayout(LayoutKind.Sequential)] public struct FLASHWINFO { public uint cbSize; public IntPtr hwnd; public uint dwFlags; public uint uCount; public uint dwTimeout; }',
50
+ ' [DllImport("user32.dll")] public static extern bool FlashWindowEx(ref FLASHWINFO pwfi);',
51
+ ' [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);',
52
+ ' [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd);',
53
+ '}',
54
+ '"@',
55
+ `$flags = ${flags}`,
56
+ "$wins = Get-Process | Where-Object { $_.MainWindowHandle -ne 0 -and ($_.MainWindowTitle -match 'DeepSeek|Harness' -or $_.ProcessName -match 'DeepSeek|Harness') }",
57
+ 'foreach ($w in $wins) {',
58
+ ' $info = New-Object VigilWin32+FLASHWINFO',
59
+ ' $info.cbSize = [Runtime.InteropServices.Marshal]::SizeOf($info)',
60
+ ' $info.hwnd = $w.MainWindowHandle',
61
+ ' $info.dwFlags = $flags',
62
+ ' $info.uCount = 0',
63
+ ' $info.dwTimeout = 0',
64
+ ' [void][VigilWin32]::FlashWindowEx([ref]$info)',
65
+ '}',
66
+ action === 'focus'
67
+ ? 'foreach ($w in $wins) { [void][VigilWin32]::ShowWindow($w.MainWindowHandle, 9); [void][VigilWin32]::SetForegroundWindow($w.MainWindowHandle) }'
68
+ : '',
69
+ ].filter(Boolean).join('\n')
70
+ }
71
+
72
+ /** @returns {Promise<boolean>} whether the window script ran successfully */
73
+ function defaultWindowAction(action) {
74
+ return new Promise(resolve => {
75
+ try {
76
+ execFile(
77
+ 'powershell.exe',
78
+ ['-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-Command', buildWindowScript(action)],
79
+ { timeout: 8000, windowsHide: true },
80
+ error => resolve(!error),
81
+ )
82
+ } catch {
83
+ resolve(false)
84
+ }
85
+ })
86
+ }
87
+
88
+ /**
89
+ * Report how the Host can draw attention to the window right now.
90
+ * @param {() => any} [loadElectron]
91
+ * @param {NodeJS.Platform} [platform]
92
+ * @returns {{ mode: 'electron'|'flash'|'unavailable', windows: number }}
93
+ */
94
+ export function probeAlertWindow(loadElectron = defaultLoadElectron, platform = process.platform) {
95
+ try {
96
+ const electron = loadElectron()
97
+ const browserWindow = electron?.BrowserWindow
98
+ const windows = typeof browserWindow?.getAllWindows === 'function'
99
+ ? browserWindow.getAllWindows().filter(win => win && (typeof win.isDestroyed !== 'function' || !win.isDestroyed()))
100
+ : []
101
+ if (windows.length > 0) return { mode: 'electron', windows: windows.length }
102
+ } catch {
103
+ // fall through to the platform fallback
104
+ }
105
+ return platform === 'win32' ? { mode: 'flash', windows: 0 } : { mode: 'unavailable', windows: 0 }
106
+ }
107
+
108
+ /**
109
+ * @param {{ loadElectron?: () => any, platform?: NodeJS.Platform, windowAction?: (action: 'raise'|'clear'|'focus') => Promise<boolean> }} [deps]
110
+ * @returns {{ path: string, methods: string[], requestBody: 'buffered', fetch: (request: Request) => Promise<Response> }}
111
+ */
112
+ export function createAlertWindowRoute(deps = {}) {
113
+ const loadElectron = deps.loadElectron ?? defaultLoadElectron
114
+ const platform = deps.platform ?? process.platform
115
+ const windowAction = deps.windowAction ?? defaultWindowAction
116
+ /** Windows whose always-on-top state we changed, with the previous value. */
117
+ const raised = new Map()
118
+
119
+ const json = (payload, status = 200) => new Response(`${JSON.stringify(payload)}\n`, {
120
+ status,
121
+ headers: {
122
+ 'content-type': 'application/json; charset=utf-8',
123
+ 'cache-control': 'no-store',
124
+ 'x-content-type-options': 'nosniff',
125
+ },
126
+ })
127
+
128
+ const restoreTop = () => {
129
+ for (const [win, previous] of raised) {
130
+ try {
131
+ win.setAlwaysOnTop(previous)
132
+ } catch {
133
+ // window already gone
134
+ }
135
+ }
136
+ raised.clear()
137
+ }
138
+
139
+ return {
140
+ path: ALERT_WINDOW_PATH,
141
+ methods: ['POST'],
142
+ requestBody: 'buffered',
143
+ fetch: async request => {
144
+ let body = null
145
+ try {
146
+ body = typeof request?.json === 'function' ? await request.json().catch(() => null) : null
147
+ } catch {
148
+ body = null
149
+ }
150
+ const action = body?.action === 'clear' ? 'clear' : body?.action === 'focus' ? 'focus' : 'raise'
151
+
152
+ let windows = []
153
+ try {
154
+ const electron = loadElectron()
155
+ const browserWindow = electron?.BrowserWindow
156
+ windows = typeof browserWindow?.getAllWindows === 'function'
157
+ ? browserWindow.getAllWindows().filter(win => win && (typeof win.isDestroyed !== 'function' || !win.isDestroyed()))
158
+ : []
159
+ } catch {
160
+ windows = []
161
+ }
162
+
163
+ if (windows.length > 0) {
164
+ if (action === 'clear') {
165
+ restoreTop()
166
+ return json({ ok: true, mode: 'electron', action, windows: windows.length })
167
+ }
168
+ if (action === 'focus') restoreTop()
169
+ for (const win of windows) {
170
+ try {
171
+ if (typeof win.isMinimized === 'function' && win.isMinimized()) win.restore()
172
+ if (typeof win.show === 'function') win.show()
173
+ if (typeof win.focus === 'function') win.focus()
174
+ if (action === 'raise' && typeof win.setAlwaysOnTop === 'function' && !raised.has(win)) {
175
+ const previous = typeof win.isAlwaysOnTop === 'function' ? Boolean(win.isAlwaysOnTop()) : false
176
+ raised.set(win, previous)
177
+ if (!previous) win.setAlwaysOnTop(true, 'floating')
178
+ }
179
+ } catch {
180
+ // best-effort per window
181
+ }
182
+ }
183
+ return json({ ok: true, mode: 'electron', action, windows: windows.length })
184
+ }
185
+
186
+ if (platform === 'win32') {
187
+ const ok = await windowAction(action)
188
+ return json({ ok, mode: 'flash', action })
189
+ }
190
+
191
+ return json({ ok: false, mode: 'unavailable', action })
192
+ },
193
+ }
194
+ }
@@ -1,87 +1,87 @@
1
- /**
2
- * Dialog artwork route.
3
- *
4
- * The Web client runs from a single `client.js`; it cannot read files from the
5
- * package directory. The two dialog illustrations are therefore served by the
6
- * Host over the authenticated browser Fetch channel:
7
- *
8
- * GET /api/dsh-vigil/artwork?name=warning|notice
9
- *
10
- * Only the two whitelisted names are readable, and the bytes are cached in
11
- * memory after the first read. Unknown names return 404 (no path traversal:
12
- * the request never becomes a filesystem path).
13
- *
14
- * @module dsh-vigil/artwork-route
15
- */
16
-
17
- import { readFileSync } from 'node:fs'
18
- import { join } from 'node:path'
19
-
20
- /** Authenticated browser fetch path for the dialog illustrations. */
21
- export const ARTWORK_PATH = '/api/dsh-vigil/artwork'
22
-
23
- /** Whitelisted illustration names and their package-relative files. */
24
- const ARTWORK_FILES = new Map([
25
- ['warning', 'illustrations/warning.png'],
26
- ['notice', 'illustrations/notice.png'],
27
- ])
28
-
29
- /**
30
- * @param {{ pluginDir: string }} deps
31
- * @returns {{ path: string, methods: string[], fetch: (request: Request) => Promise<Response> }}
32
- */
33
- export function createArtworkRoute(deps) {
34
- /** @type {Map<string, Buffer|null>} */
35
- const cache = new Map()
36
-
37
- /** @param {string} name @returns {Buffer|null} */
38
- const read = name => {
39
- if (cache.has(name)) return cache.get(name) ?? null
40
- const relative = ARTWORK_FILES.get(name)
41
- if (!relative) return null
42
- try {
43
- const bytes = readFileSync(join(deps.pluginDir, relative))
44
- cache.set(name, bytes)
45
- return bytes
46
- } catch {
47
- // Missing artwork must not break the dialog: the client falls back to
48
- // hiding the image on a 404.
49
- cache.set(name, null)
50
- return null
51
- }
52
- }
53
-
54
- return {
55
- path: ARTWORK_PATH,
56
- methods: ['GET'],
57
- fetch: async request => {
58
- let name = ''
59
- try {
60
- name = new URL(String(request.url ?? ''), 'http://127.0.0.1').searchParams.get('name') ?? ''
61
- } catch {
62
- name = ''
63
- }
64
- const bytes = read(name)
65
- if (!bytes) {
66
- return new Response('not found\n', {
67
- status: 404,
68
- headers: {
69
- 'content-type': 'text/plain; charset=utf-8',
70
- 'cache-control': 'no-store',
71
- 'x-content-type-options': 'nosniff',
72
- },
73
- })
74
- }
75
- return new Response(bytes, {
76
- status: 200,
77
- headers: {
78
- 'content-type': 'image/png',
79
- // The file is bundled with the plugin version, so a short public
80
- // cache is safe and avoids re-sending it for every dialog open.
81
- 'cache-control': 'public, max-age=3600',
82
- 'x-content-type-options': 'nosniff',
83
- },
84
- })
85
- },
86
- }
87
- }
1
+ /**
2
+ * Dialog artwork route.
3
+ *
4
+ * The Web client runs from a single `client.js`; it cannot read files from the
5
+ * package directory. The two dialog illustrations are therefore served by the
6
+ * Host over the authenticated browser Fetch channel:
7
+ *
8
+ * GET /api/dsh-vigil/artwork?name=warning|notice
9
+ *
10
+ * Only the two whitelisted names are readable, and the bytes are cached in
11
+ * memory after the first read. Unknown names return 404 (no path traversal:
12
+ * the request never becomes a filesystem path).
13
+ *
14
+ * @module dsh-vigil/artwork-route
15
+ */
16
+
17
+ import { readFileSync } from 'node:fs'
18
+ import { join } from 'node:path'
19
+
20
+ /** Authenticated browser fetch path for the dialog illustrations. */
21
+ export const ARTWORK_PATH = '/api/dsh-vigil/artwork'
22
+
23
+ /** Whitelisted illustration names and their package-relative files. */
24
+ const ARTWORK_FILES = new Map([
25
+ ['warning', 'illustrations/warning.png'],
26
+ ['notice', 'illustrations/notice.png'],
27
+ ])
28
+
29
+ /**
30
+ * @param {{ pluginDir: string }} deps
31
+ * @returns {{ path: string, methods: string[], fetch: (request: Request) => Promise<Response> }}
32
+ */
33
+ export function createArtworkRoute(deps) {
34
+ /** @type {Map<string, Buffer|null>} */
35
+ const cache = new Map()
36
+
37
+ /** @param {string} name @returns {Buffer|null} */
38
+ const read = name => {
39
+ if (cache.has(name)) return cache.get(name) ?? null
40
+ const relative = ARTWORK_FILES.get(name)
41
+ if (!relative) return null
42
+ try {
43
+ const bytes = readFileSync(join(deps.pluginDir, relative))
44
+ cache.set(name, bytes)
45
+ return bytes
46
+ } catch {
47
+ // Missing artwork must not break the dialog: the client falls back to
48
+ // hiding the image on a 404.
49
+ cache.set(name, null)
50
+ return null
51
+ }
52
+ }
53
+
54
+ return {
55
+ path: ARTWORK_PATH,
56
+ methods: ['GET'],
57
+ fetch: async request => {
58
+ let name = ''
59
+ try {
60
+ name = new URL(String(request.url ?? ''), 'http://127.0.0.1').searchParams.get('name') ?? ''
61
+ } catch {
62
+ name = ''
63
+ }
64
+ const bytes = read(name)
65
+ if (!bytes) {
66
+ return new Response('not found\n', {
67
+ status: 404,
68
+ headers: {
69
+ 'content-type': 'text/plain; charset=utf-8',
70
+ 'cache-control': 'no-store',
71
+ 'x-content-type-options': 'nosniff',
72
+ },
73
+ })
74
+ }
75
+ return new Response(bytes, {
76
+ status: 200,
77
+ headers: {
78
+ 'content-type': 'image/png',
79
+ // The file is bundled with the plugin version, so a short public
80
+ // cache is safe and avoids re-sending it for every dialog open.
81
+ 'cache-control': 'public, max-age=3600',
82
+ 'x-content-type-options': 'nosniff',
83
+ },
84
+ })
85
+ },
86
+ }
87
+ }