dsh-notification-focus 0.0.0-stage → 0.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,274 @@
1
+ // origin: opencode-agent/hy4-flash-free | 2026-11-26T11:30:00+08:00 | 暂停按钮可测试核心:URL/动作解析、白名单、令牌、toast actions XML、动作文件路径
2
+
3
+ // pause-actions.js —— 暂停按钮的「纯逻辑核心」。
4
+ //
5
+ // 设计原则(见 docs/PAUSE-BUTTON-IMPLEMENTATION.md):
6
+ // 1. 零副作用:本模块不 spawn、不写文件、不弹 toast、不碰注册表。
7
+ // 2. 已按用户要求撤下:Host 加载后强制 PAUSE_BUTTONS=false,UI 控件亦已移除。
8
+ // 本文件保留为代码层历史产物,勿恢复 5 个 toast 按钮。
9
+ // 3. 严格白名单:op ∈ {snooze,off,on},minutes ∈ {10,30,60,120,720}。
10
+ // 4. 一次性令牌:createTokenVerifier 可注入 now / random / issued,便于单测重放。
11
+ // 5. 文件动作通道:handler 写动作 JSON 到 %TEMP%,插件读后校验再应用;
12
+ // 不新增任何无鉴权 HTTP 路由。
13
+ //
14
+ // 所有涉及时间/路径/随机数的入口都允许注入,测试可完全确定性。
15
+
16
+ import { join } from 'node:path'
17
+
18
+ // ---- 常量白名单(改动这里必须同步 notify-action-handler.ps1)----
19
+ export const ALLOWED_OPS = ['snooze', 'off', 'on']
20
+ export const ALLOWED_MINUTES = [10, 30, 60, 120, 720]
21
+ export const MAX_ACTIONS = 5 // Windows toast 最多 5 个按钮(实证见 PAUSE-BUTTON-EVIDENCE.md)
22
+ export const ACTION_FILE_NAME = 'dsh-notify-action.json'
23
+ export const TOKEN_TTL_MS = 5 * 60 * 1000
24
+
25
+ export const ACTION_LABELS = {
26
+ 10: '10 分钟',
27
+ 30: '30 分钟',
28
+ 60: '1 小时',
29
+ 120: '2 小时',
30
+ 720: '12 小时',
31
+ off: '永久关闭',
32
+ on: '恢复通知',
33
+ }
34
+
35
+ // 默认关闭:只有 DSH_NOTIFICATION_PAUSE_BUTTONS=1 才生效。
36
+ export function isPauseButtonsEnabled(env = process.env) {
37
+ return env?.DSH_NOTIFICATION_PAUSE_BUTTONS === '1'
38
+ }
39
+
40
+ // .NET System.Security.SecurityElement::Escape 的等价语义:
41
+ // 先转义 &,再转义 < > " '(顺序不可换,否则会产生 &amp;lt;)。
42
+ export function securityElementEscape(value) {
43
+ return String(value ?? '')
44
+ .replace(/&/g, '&amp;')
45
+ .replace(/</g, '&lt;')
46
+ .replace(/>/g, '&gt;')
47
+ .replace(/"/g, '&quot;')
48
+ .replace(/'/g, '&apos;')
49
+ }
50
+
51
+ function isTokenShape(token) {
52
+ return typeof token === 'string' && /^[A-Za-z0-9_-]{8,128}$/.test(token)
53
+ }
54
+
55
+ // 数字分钟归一化:只接受白名单里的整数(字符串 '010' 会被归一为 10,仍属白名单值)。
56
+ function coerceMinutes(raw) {
57
+ if (typeof raw === 'number' && Number.isInteger(raw)) {
58
+ return ALLOWED_MINUTES.includes(raw) ? raw : null
59
+ }
60
+ if (typeof raw === 'string' && /^\d{1,4}$/.test(raw)) {
61
+ const n = Number(raw)
62
+ return ALLOWED_MINUTES.includes(n) ? n : null
63
+ }
64
+ return null
65
+ }
66
+
67
+ function safeDecode(raw) {
68
+ try { return decodeURIComponent(raw) } catch { return raw }
69
+ }
70
+
71
+ // dshnotify://act?op=snooze&m=10&t=TOKEN → 'op=snooze&m=10&t=TOKEN'
72
+ // 只认 dshnotify: 协议;空 head 允许测试直接传 '?op=...'。
73
+ export function extractQuery(url) {
74
+ const s = String(url ?? '')
75
+ const i = s.indexOf('?')
76
+ if (i < 0) return null
77
+ const head = s.slice(0, i)
78
+ if (head && !/^dshnotify:\/\//i.test(head)) return null
79
+ return s.slice(i + 1)
80
+ }
81
+
82
+ export function parseQuery(query) {
83
+ const out = Object.create(null)
84
+ const q = String(query ?? '')
85
+ if (!q) return out
86
+ for (const pair of q.split('&')) {
87
+ if (!pair) continue
88
+ const eq = pair.indexOf('=')
89
+ const k = eq < 0 ? pair : pair.slice(0, eq)
90
+ const v = eq < 0 ? '' : pair.slice(eq + 1)
91
+ out[safeDecode(k)] = safeDecode(v)
92
+ }
93
+ return out
94
+ }
95
+
96
+ // 统一归一化:URL query 用 {op,m,t},动作文件 JSON 用 {op,minutes,token}。
97
+ // 两者都接受,后续 validateAction 只认一种形状。
98
+ export function parseActionObject(obj) {
99
+ if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return null
100
+ const op = typeof obj.op === 'string' ? obj.op : null
101
+ const rawMinutes = obj.minutes !== undefined ? obj.minutes : obj.m
102
+ const minutes = coerceMinutes(rawMinutes)
103
+ const rawToken = obj.token !== undefined ? obj.token : obj.t
104
+ const token = typeof rawToken === 'string' ? rawToken : null
105
+ // k/askedId 只用于审批"拒绝"动作;其余动作不带也不会受影响
106
+ const rawKey = obj.key !== undefined ? obj.key : obj.k
107
+ const key = typeof rawKey === 'string' ? rawKey : null
108
+ return { op, minutes, token, key }
109
+ }
110
+
111
+ export function parseActionUrl(url) {
112
+ const query = extractQuery(url)
113
+ return query === null ? null : parseActionObject(parseQuery(query))
114
+ }
115
+
116
+ // 插件侧读动作文件:限长 + JSON.parse + 归一化;任何异常返回 null(fail-closed)。
117
+ export function parseActionFile(raw, { maxBytes = 2048 } = {}) {
118
+ const text = typeof raw === 'string' ? raw : String(raw ?? '')
119
+ if (!text || text.length > maxBytes) return null
120
+ let obj
121
+ try { obj = JSON.parse(text) } catch { return null }
122
+ return parseActionObject(obj)
123
+ }
124
+
125
+ // 校验 + 消费令牌。verifier 可选:不传时只做令牌形状检查;
126
+ // 传入时 consume 一次即销毁,重放必失败。
127
+ export function validateAction(parsed, opts = {}) {
128
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
129
+ return { ok: false, reason: 'malformed' }
130
+ }
131
+ const op = parsed.op
132
+ if (!ALLOWED_OPS.includes(op)) return { ok: false, reason: 'bad-op' }
133
+
134
+ let minutes = null
135
+ if (op === 'snooze') {
136
+ minutes = coerceMinutes(parsed.minutes)
137
+ if (minutes === null) return { ok: false, reason: 'bad-minutes' }
138
+ }
139
+
140
+ const token = typeof parsed.token === 'string' ? parsed.token : null
141
+ const verifier = opts.verifier
142
+ if (verifier && typeof verifier.consume === 'function') {
143
+ if (!verifier.consume(token, opts.now)) return { ok: false, reason: 'bad-token' }
144
+ } else if (!isTokenShape(token)) {
145
+ return { ok: false, reason: 'bad-token' }
146
+ }
147
+ return { ok: true, action: { op, minutes, token } }
148
+ }
149
+
150
+ export function validateActionFile(raw, opts = {}) {
151
+ return validateAction(parseActionFile(raw, opts), opts)
152
+ }
153
+
154
+ function defaultRandom() {
155
+ const g = globalThis.crypto
156
+ if (g && typeof g.randomUUID === 'function') return g.randomUUID().replace(/-/g, '')
157
+ return Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2)
158
+ }
159
+
160
+ // 一次性令牌:短 TTL,伪造的最坏后果只是给自己静音,绝不授予能力。
161
+ // now / random / issued 全部可注入,测试可模拟重放与过期。
162
+ export function createTokenVerifier({
163
+ now = () => Date.now(),
164
+ ttlMs = TOKEN_TTL_MS,
165
+ random = defaultRandom,
166
+ issued = new Map(), // token -> expiresAt(ms)
167
+ } = {}) {
168
+ const clock = () => {
169
+ const n = Number(now())
170
+ return Number.isFinite(n) ? n : Date.now()
171
+ }
172
+ const prune = (at) => {
173
+ for (const [k, exp] of issued) if (!(Number(at) < Number(exp))) issued.delete(k)
174
+ }
175
+ return {
176
+ issue(at = clock()) {
177
+ const t = Number(at)
178
+ prune(t)
179
+ const generated = String(random()).replace(/[^A-Za-z0-9_-]/g, '').slice(0, 128)
180
+ const token = isTokenShape(generated) ? generated : 'tok' + t.toString(36) + Math.random().toString(36).slice(2)
181
+ issued.set(token, t + ttlMs)
182
+ return token
183
+ },
184
+ consume(token, at = clock()) {
185
+ if (!isTokenShape(token)) return false
186
+ const exp = issued.get(token)
187
+ if (exp === undefined) return false
188
+ issued.delete(token) // 先销毁:无论是否过期,重放一律失败
189
+ return Number(at) < Number(exp)
190
+ },
191
+ prune,
192
+ size() { return issued.size },
193
+ pending() { return [...issued.keys()] },
194
+ }
195
+ }
196
+
197
+ export function buildActionUrl({ op, minutes = null, token }) {
198
+ if (!ALLOWED_OPS.includes(op)) throw new RangeError('op not whitelisted: ' + op)
199
+ let url = 'dshnotify://act?op=' + op
200
+ if (op === 'snooze') {
201
+ const m = coerceMinutes(minutes)
202
+ if (m === null) throw new RangeError('minutes not whitelisted: ' + minutes)
203
+ url += '&m=' + m
204
+ }
205
+ url += '&t=' + encodeURIComponent(String(token ?? ''))
206
+ return url
207
+ }
208
+
209
+ // 默认 4 个时长 + 永久关闭 = 5 个按钮(Windows 上限)。
210
+ // 需要 720(12 小时)时用 { durations:[10,30,60,120,720], includeOff:false }。
211
+ export function buildToastActions({
212
+ token,
213
+ durations = [10, 30, 60, 120],
214
+ includeOff = true,
215
+ includeOn = false,
216
+ } = {}) {
217
+ if (!isTokenShape(token)) return [] // fail-closed:无合法令牌就不给 toast 加按钮
218
+ const specs = []
219
+ for (const d of durations) {
220
+ const m = coerceMinutes(d)
221
+ if (m !== null && !specs.some(s => s.op === 'snooze' && s.minutes === m)) {
222
+ specs.push({ op: 'snooze', minutes: m, label: ACTION_LABELS[m] })
223
+ }
224
+ }
225
+ if (includeOff) specs.push({ op: 'off', minutes: null, label: ACTION_LABELS.off })
226
+ if (includeOn) specs.push({ op: 'on', minutes: null, label: ACTION_LABELS.on })
227
+ return specs.slice(0, MAX_ACTIONS).map(s => ({
228
+ op: s.op,
229
+ minutes: s.minutes,
230
+ label: s.label,
231
+ activationType: 'protocol',
232
+ arguments: buildActionUrl({ op: s.op, minutes: s.minutes, token }),
233
+ }))
234
+ }
235
+
236
+ // 动作对象 → toast <actions> XML。属性值全部走 SecurityElement::Escape 等价转义。
237
+ export function formatActionXml(actions) {
238
+ if (!Array.isArray(actions) || actions.length === 0) return ''
239
+ const lines = ['<actions>']
240
+ let count = 0
241
+ for (const a of actions.slice(0, MAX_ACTIONS)) {
242
+ if (!a || !ALLOWED_OPS.includes(a.op)) continue
243
+ if (a.op === 'snooze' && coerceMinutes(a.minutes) === null) continue
244
+ const label = (typeof a.label === 'string' && a.label)
245
+ ? a.label
246
+ : (a.op === 'snooze' ? ACTION_LABELS[a.minutes] : ACTION_LABELS[a.op])
247
+ let args = typeof a.arguments === 'string' ? a.arguments : ''
248
+ if (!args) {
249
+ try { args = buildActionUrl({ op: a.op, minutes: a.minutes, token: a.token }) } catch { continue }
250
+ }
251
+ if (!label || !args) continue
252
+ lines.push(
253
+ ' <action activationType="protocol" arguments="' + securityElementEscape(args) +
254
+ '" content="' + securityElementEscape(label) + '"/>',
255
+ )
256
+ count++
257
+ }
258
+ if (count === 0) return ''
259
+ lines.push('</actions>')
260
+ return lines.join('\n')
261
+ }
262
+
263
+ // 文件动作通道路径约定:handler 与插件必须用同一个 %TEMP% 文件名。
264
+ export function actionFilePath({ temp = process.env.TEMP || process.cwd(), name = ACTION_FILE_NAME } = {}) {
265
+ return join(temp, name)
266
+ }
267
+
268
+ export function actionTempFilePath({
269
+ temp = process.env.TEMP || process.cwd(),
270
+ pid = process.pid,
271
+ name = ACTION_FILE_NAME,
272
+ } = {}) {
273
+ return join(temp, name + '.tmp.' + pid)
274
+ }
package/play-file.ps1 ADDED
@@ -0,0 +1,67 @@
1
+ # origin: opencode-agent/hy4-flash-free | 2026-11-27T09:08:33+08:00 | Play one local audio file (env-only input).
2
+ #
3
+ # Purpose: play a single local notification sound named by DSH_NOTIFICATION_AUDIO_FILE.
4
+ # The path is validated strictly before playback: length, extension whitelist, existence as a
5
+ # real file, and explicit rejection of UNC paths, URL schemes, wildcards, quotes and control
6
+ # characters. Invalid input exits 2; playback failure exits 3.
7
+ #
8
+ # Only local files are played. No network, no URL execution, no credential reads, no registry
9
+ # writes, no popups. Text never comes from the command line: env vars are the only input.
10
+ #
11
+ # Why ASCII-only: PowerShell 5.1 decodes a BOM-less script as GBK, so any non-ASCII byte here
12
+ # would corrupt the lines after it. Keeping this file plain ASCII removes the BOM requirement.
13
+ #
14
+ # Exit codes: 0 = played, 2 = invalid path, 3 = playback failed.
15
+ param()
16
+
17
+ $ErrorActionPreference = 'Stop'
18
+
19
+ $path = $env:DSH_NOTIFICATION_AUDIO_FILE
20
+ $ext = ''
21
+
22
+ try {
23
+ if ([string]::IsNullOrEmpty($path)) { exit 2 }
24
+ if ($path.Length -gt 4096) { exit 2 }
25
+ if ($path.StartsWith('\\')) { exit 2 }
26
+ if ($path.Contains('://')) { exit 2 }
27
+ if ($path.Contains('*') -or $path.Contains('?')) { exit 2 }
28
+ # Quotes (double and single) and C0/DEL control characters must never reach a file API.
29
+ if ($path -match '[\x00-\x1f\x7f\x22\x27]') { exit 2 }
30
+
31
+ $ext = [System.IO.Path]::GetExtension($path).ToLowerInvariant()
32
+ $allowed = @('.wav', '.mp3', '.m4a', '.wma', '.aac', '.flac')
33
+ if ($allowed -notcontains $ext) { exit 2 }
34
+
35
+ if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { exit 2 }
36
+ $item = Get-Item -LiteralPath $path -ErrorAction Stop
37
+ if ($item.PSIsContainer) { exit 2 }
38
+ } catch {
39
+ exit 2
40
+ }
41
+
42
+ try {
43
+ [void][Windows.Media.Playback.MediaPlayer, Windows.Media.Playback, ContentType = WindowsRuntime]
44
+ [void][Windows.Media.Core.MediaSource, Windows.Media.Core, ContentType = WindowsRuntime]
45
+ $player = New-Object Windows.Media.Playback.MediaPlayer
46
+ $player.Source = [Windows.Media.Core.MediaSource]::CreateFromUri((New-Object System.Uri($path)))
47
+ $player.Play()
48
+ # Cap the wait at five seconds so a long file cannot hang the notification host.
49
+ Start-Sleep -Milliseconds 5000
50
+ $player.Dispose()
51
+ exit 0
52
+ } catch {
53
+ # WinRT projections are missing on some systems; .wav has a managed fallback.
54
+ if ($ext -eq '.wav') {
55
+ try {
56
+ $sound = New-Object System.Media.SoundPlayer $path
57
+ $sound.Play()
58
+ Start-Sleep -Milliseconds 5000
59
+ $sound.Stop()
60
+ $sound.Dispose()
61
+ exit 0
62
+ } catch {
63
+ exit 3
64
+ }
65
+ }
66
+ exit 3
67
+ }
@@ -0,0 +1,62 @@
1
+ # origin: lead/deepseek-v4.1-flash | 2026-11-26T22:10:00+08:00 | Play one Windows notification sound once (settings preview).
2
+ #
3
+ # Why this file is ASCII-only: PS 5.1 decodes a BOM-less script as GBK, so any non-ASCII
4
+ # comment would corrupt the lines after it (the project learned this the hard way with the
5
+ # toast script losing its launch attribute). Keeping it ASCII removes the BOM requirement.
6
+ #
7
+ # Playback goes through WinRT MediaPlayer with the same "ms-winsoundevent:" source that the
8
+ # toast XML uses, so the preview is exactly the sound that notification kind would make.
9
+ # Must run under powershell.exe (5.1): PowerShell 7 cannot resolve WinRT projections.
10
+ #
11
+ # Exit codes: 0 = played or intentionally silent (None), 2 = unknown sound, 3 = playback failed.
12
+ param([Parameter(Mandatory = $true)][string]$Sound)
13
+
14
+ $allowed = @(
15
+ 'Notification.Default', 'Notification.IM', 'Notification.Mail', 'Notification.Reminder',
16
+ 'Notification.LoopingCall', 'Notification.LoopingAlarm', 'Notification.LoopingAlarm2',
17
+ 'Notification.LoopingCall2'
18
+ )
19
+
20
+ # The silent option has nothing to play; treat it as success so the UI stays quiet.
21
+ if ($Sound -eq 'None') { exit 0 }
22
+ if ($allowed -notcontains $Sound) { exit 2 }
23
+
24
+ # The four Looping* sources are toast-only: MediaPlayer accepts the URI but reports
25
+ # PlaybackState=None and stays silent (measured 2026-11-26). For those, fall back to the
26
+ # closest built-in system tone so the picker still gives audible feedback. This is an
27
+ # approximation, not the exact toast tone -- the real one can only be produced by the
28
+ # notification platform itself.
29
+ $loopApprox = @{
30
+ 'Notification.LoopingCall' = 'Ring01.wav'
31
+ 'Notification.LoopingCall2' = 'Ring02.wav'
32
+ 'Notification.LoopingAlarm' = 'Alarm01.wav'
33
+ 'Notification.LoopingAlarm2' = 'Alarm02.wav'
34
+ }
35
+ if ($loopApprox.ContainsKey($Sound)) {
36
+ $wav = Join-Path $env:WINDIR ('Media\' + $loopApprox[$Sound])
37
+ if (-not (Test-Path -LiteralPath $wav)) { exit 3 }
38
+ try {
39
+ $p = New-Object System.Media.SoundPlayer $wav
40
+ $p.Play()
41
+ Start-Sleep -Milliseconds 2200
42
+ $p.Stop()
43
+ exit 0
44
+ } catch {
45
+ exit 3
46
+ }
47
+ }
48
+
49
+ try {
50
+ [void][Windows.Media.Playback.MediaPlayer, Windows.Media.Playback, ContentType = WindowsRuntime]
51
+ [void][Windows.Media.Core.MediaSource, Windows.Media.Core, ContentType = WindowsRuntime]
52
+ $player = New-Object Windows.Media.Playback.MediaPlayer
53
+ $player.Source = [Windows.Media.Core.MediaSource]::CreateFromUri((New-Object System.Uri("ms-winsoundevent:$Sound")))
54
+ $player.Play()
55
+ # Looping* sources repeat, so hold the process open briefly and then stop: a preview must
56
+ # never loop forever in the background.
57
+ Start-Sleep -Milliseconds 2500
58
+ $player.Dispose()
59
+ exit 0
60
+ } catch {
61
+ exit 3
62
+ }
package/speak.ps1 ADDED
@@ -0,0 +1,59 @@
1
+ # origin: opencode-agent/hy4-flash-free | 2026-11-27T09:08:33+08:00 | Speak notification text via System.Speech (env-only input).
2
+ #
3
+ # Purpose: read DSH_NOTIFICATION_TTS_TEXT (pure-ASCII \uXXXX escapes), decode it to Unicode,
4
+ # and speak it once through System.Speech.Synthesis.SpeechSynthesizer. An optional
5
+ # DSH_NOTIFICATION_TTS_VOICE selects an installed voice by exact VoiceInfo.Name; when the voice
6
+ # is unknown, the script degrades silently to the system default instead of failing.
7
+ #
8
+ # Why ASCII-only: PowerShell 5.1 decodes a BOM-less script as GBK, so any non-ASCII byte here
9
+ # would corrupt the lines after it. Keeping this file plain ASCII removes the BOM requirement.
10
+ #
11
+ # -List only prints installed voice names (one per line, stdout) and never speaks.
12
+ # No network, no credential reads, no URL execution, no registry writes, no popups.
13
+ # Text never comes from the command line: environment variables are the only input channel.
14
+ # Exit codes: 0 = spoken / empty text / listed, 3 = speech engine error.
15
+ param([switch]$List)
16
+
17
+ $ErrorActionPreference = 'Stop'
18
+
19
+ function Decode-UE([string]$s) {
20
+ if ([string]::IsNullOrEmpty($s)) { return '' }
21
+ return [regex]::Replace($s, '\\u([0-9a-fA-F]{4})', {
22
+ param($m) [string][char][Convert]::ToInt32($m.Groups[1].Value, 16)
23
+ })
24
+ }
25
+
26
+ try {
27
+ Add-Type -AssemblyName System.Speech
28
+ $synth = New-Object System.Speech.Synthesis.SpeechSynthesizer
29
+
30
+ if ($List) {
31
+ foreach ($iv in $synth.GetInstalledVoices()) {
32
+ [Console]::WriteLine($iv.VoiceInfo.Name)
33
+ }
34
+ $synth.Dispose()
35
+ exit 0
36
+ }
37
+
38
+ $text = Decode-UE $env:DSH_NOTIFICATION_TTS_TEXT
39
+ if ([string]::IsNullOrEmpty($text)) {
40
+ $synth.Dispose()
41
+ exit 0
42
+ }
43
+
44
+ $voice = $env:DSH_NOTIFICATION_TTS_VOICE
45
+ if ($voice) {
46
+ $found = $false
47
+ foreach ($iv in $synth.GetInstalledVoices()) {
48
+ if ($iv.VoiceInfo.Name -ceq $voice) { $found = $true; break }
49
+ }
50
+ # Unknown voice: ignore it silently and keep the system default.
51
+ if ($found) { $synth.SelectVoice($voice) }
52
+ }
53
+
54
+ $synth.Speak($text)
55
+ $synth.Dispose()
56
+ exit 0
57
+ } catch {
58
+ exit 3
59
+ }