@tavlo-dsh/dsh-plugin-hooks 0.0.0-stage → 0.1.3

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,403 @@
1
+ /**
2
+ * Custom `.wav` sound validation, atomic storage, and native Host playback.
3
+ */
4
+
5
+ import { randomBytes } from 'node:crypto'
6
+ import { spawn as nodeSpawn } from 'node:child_process'
7
+ import { mkdir, open, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises'
8
+ import path from 'node:path'
9
+
10
+ export const MAX_WAV_BYTES = 20 * 1024 * 1024
11
+
12
+ const MAX_FILENAME_LENGTH = 120
13
+ const DEFAULT_PLAY_TIMEOUT_MS = 15_000
14
+ const MAX_PLAY_TIMEOUT_MS = 60_000
15
+ const MAX_STDERR_BYTES = 2048
16
+
17
+ const WIN32_PLAY_COMMAND =
18
+ '$p=$env:DSH_SOUND_PATH; if ($p -and (Test-Path -LiteralPath $p)) { $sp = New-Object System.Media.SoundPlayer $p; $sp.PlaySync() }'
19
+
20
+ let cachedScrubbedParentEnv = null
21
+
22
+ async function getScrubbedEnv() {
23
+ if (!cachedScrubbedParentEnv) {
24
+ try {
25
+ const mod = await import('@deepseek-ai/dsh-subprocess')
26
+ if (typeof mod?.scrubbedParentEnv === 'function') {
27
+ cachedScrubbedParentEnv = mod.scrubbedParentEnv
28
+ }
29
+ } catch {
30
+ // Fallback when running isolated tests before dependencies are installed.
31
+ }
32
+ if (!cachedScrubbedParentEnv) {
33
+ cachedScrubbedParentEnv = () => {
34
+ const env = {}
35
+ for (const [key, value] of Object.entries(process.env)) {
36
+ if (
37
+ value !== undefined &&
38
+ !/KEY|PASSWORD|SECRET|TOKEN/i.test(key) &&
39
+ !key.toUpperCase().startsWith('DSH_')
40
+ ) {
41
+ env[key] = value
42
+ }
43
+ }
44
+ return env
45
+ }
46
+ }
47
+ }
48
+ return cachedScrubbedParentEnv()
49
+ }
50
+
51
+ function toBufferView(buf) {
52
+ if (Buffer.isBuffer(buf)) return buf
53
+ if (buf instanceof Uint8Array) {
54
+ return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
55
+ }
56
+ return null
57
+ }
58
+
59
+ /**
60
+ * Validate a WAV buffer against size bounds and RIFF/WAVE header bytes.
61
+ * @param {Buffer|Uint8Array} buf
62
+ * @returns {{ valid: boolean, errorCode?: string, reason?: string }}
63
+ */
64
+ export function validateWavBuffer(buf) {
65
+ const view = toBufferView(buf)
66
+ if (!view) {
67
+ return {
68
+ valid: false,
69
+ errorCode: 'sound/invalid-buffer',
70
+ reason: 'Expected a Buffer or Uint8Array.',
71
+ }
72
+ }
73
+ if (view.byteLength === 0) {
74
+ return {
75
+ valid: false,
76
+ errorCode: 'sound/empty',
77
+ reason: 'WAV file is empty.',
78
+ }
79
+ }
80
+ if (view.byteLength > MAX_WAV_BYTES) {
81
+ return {
82
+ valid: false,
83
+ errorCode: 'sound/too-large',
84
+ reason: `WAV file exceeds ${MAX_WAV_BYTES} bytes limit.`,
85
+ }
86
+ }
87
+ if (view.byteLength < 12) {
88
+ return {
89
+ valid: false,
90
+ errorCode: 'sound/invalid-header',
91
+ reason: 'WAV header must be at least 12 bytes.',
92
+ }
93
+ }
94
+ const riff = view.toString('ascii', 0, 4)
95
+ const wave = view.toString('ascii', 8, 12)
96
+ if (riff !== 'RIFF' || wave !== 'WAVE') {
97
+ return {
98
+ valid: false,
99
+ errorCode: 'sound/invalid-wav',
100
+ reason: 'File does not have a valid RIFF/WAVE header.',
101
+ }
102
+ }
103
+ return { valid: true }
104
+ }
105
+
106
+ function sanitizeSoundFilename(originalName) {
107
+ const raw = typeof originalName === 'string' ? originalName : ''
108
+ const base = raw.split(/[\\/]+/).pop()?.trim() ?? ''
109
+ let cleaned = base
110
+ .replace(/[\x00-\x1f\x7f<>:"/\\|?*]/g, '_')
111
+ .replace(/^\.+/, '')
112
+ .trim()
113
+ if (!cleaned) cleaned = 'custom.wav'
114
+ if (!cleaned.toLowerCase().endsWith('.wav')) {
115
+ cleaned = `${cleaned}.wav`
116
+ }
117
+ if (cleaned.length > MAX_FILENAME_LENGTH) {
118
+ const stem = cleaned.slice(0, MAX_FILENAME_LENGTH - 4).replace(/[. ]+$/, '') || 'custom'
119
+ cleaned = `${stem}.wav`
120
+ }
121
+ return cleaned
122
+ }
123
+
124
+ /**
125
+ * Resolve the path where the active custom WAV sound is stored.
126
+ * @param {string} dataDir
127
+ * @returns {string}
128
+ */
129
+ export function getCustomSoundPath(dataDir) {
130
+ if (typeof dataDir !== 'string' || !dataDir.trim()) {
131
+ throw new TypeError('dataDir must be a non-empty string')
132
+ }
133
+ return path.join(dataDir, 'sounds', 'custom.wav')
134
+ }
135
+
136
+ function getCustomSoundMetaPath(dataDir) {
137
+ return `${getCustomSoundPath(dataDir)}.json`
138
+ }
139
+
140
+ async function atomicWriteFile(targetPath, data) {
141
+ const suffix = `.tmp-${process.pid}-${randomBytes(6).toString('hex')}`
142
+ const tmpPath = `${targetPath}${suffix}`
143
+ try {
144
+ await writeFile(tmpPath, data)
145
+ await rename(tmpPath, targetPath)
146
+ } catch (error) {
147
+ await unlink(tmpPath).catch(() => {})
148
+ throw error
149
+ }
150
+ }
151
+
152
+ /**
153
+ * Validate and persist a custom WAV sound and its metadata atomically.
154
+ * @param {string} dataDir
155
+ * @param {Buffer|Uint8Array} buf
156
+ * @param {string} originalName
157
+ * @returns {Promise<{ filename: string, bytes: number, updatedAt: string }>}
158
+ */
159
+ export async function saveCustomSound(dataDir, buf, originalName) {
160
+ const check = validateWavBuffer(buf)
161
+ if (!check.valid) {
162
+ const err = new Error(check.reason || 'Invalid WAV sound')
163
+ err.code = check.errorCode || 'sound/invalid-wav'
164
+ throw err
165
+ }
166
+ const view = toBufferView(buf)
167
+ const soundPath = getCustomSoundPath(dataDir)
168
+ const metaPath = getCustomSoundMetaPath(dataDir)
169
+ await mkdir(path.dirname(soundPath), { recursive: true })
170
+
171
+ const info = {
172
+ filename: sanitizeSoundFilename(originalName),
173
+ bytes: view.byteLength,
174
+ updatedAt: new Date().toISOString(),
175
+ }
176
+
177
+ await atomicWriteFile(soundPath, view)
178
+ await atomicWriteFile(metaPath, JSON.stringify(info, null, 2))
179
+ return info
180
+ }
181
+
182
+ /**
183
+ * Read custom WAV metadata and verify the audio file exists and passes RIFF/WAVE header + size checks.
184
+ * @param {string} dataDir
185
+ * @returns {Promise<{ filename: string, bytes: number, updatedAt: string } | null>}
186
+ */
187
+ export async function getCustomSoundInfo(dataDir) {
188
+ if (typeof dataDir !== 'string' || !dataDir.trim()) return null
189
+ const soundPath = getCustomSoundPath(dataDir)
190
+ const metaPath = getCustomSoundMetaPath(dataDir)
191
+
192
+ let meta
193
+ try {
194
+ const raw = await readFile(metaPath, 'utf8')
195
+ meta = JSON.parse(raw)
196
+ } catch {
197
+ return null
198
+ }
199
+ if (!meta || typeof meta !== 'object' || typeof meta.filename !== 'string' || !meta.filename.trim()) {
200
+ return null
201
+ }
202
+
203
+ let fileStat
204
+ try {
205
+ fileStat = await stat(soundPath)
206
+ } catch {
207
+ return null
208
+ }
209
+ if (!fileStat.isFile() || fileStat.size < 12 || fileStat.size > MAX_WAV_BYTES) {
210
+ return null
211
+ }
212
+
213
+ let handle
214
+ try {
215
+ handle = await open(soundPath, 'r')
216
+ const header = Buffer.alloc(12)
217
+ const { bytesRead } = await handle.read(header, 0, 12, 0)
218
+ if (bytesRead < 12) return null
219
+ if (header.toString('ascii', 0, 4) !== 'RIFF' || header.toString('ascii', 8, 12) !== 'WAVE') {
220
+ return null
221
+ }
222
+ } catch {
223
+ return null
224
+ } finally {
225
+ await handle?.close().catch(() => {})
226
+ }
227
+
228
+ return {
229
+ filename: sanitizeSoundFilename(meta.filename),
230
+ bytes: fileStat.size,
231
+ updatedAt: typeof meta.updatedAt === 'string' ? meta.updatedAt : fileStat.mtime.toISOString(),
232
+ }
233
+ }
234
+
235
+ /**
236
+ * Remove custom WAV audio and metadata, ignoring ENOENT.
237
+ * @param {string} dataDir
238
+ * @returns {Promise<void>}
239
+ */
240
+ export async function clearCustomSound(dataDir) {
241
+ if (typeof dataDir !== 'string' || !dataDir.trim()) return
242
+ const targets = [getCustomSoundPath(dataDir), getCustomSoundMetaPath(dataDir)]
243
+ for (const target of targets) {
244
+ try {
245
+ await unlink(target)
246
+ } catch (error) {
247
+ if (error?.code !== 'ENOENT') throw error
248
+ }
249
+ }
250
+ }
251
+
252
+ function runCommandWithTimeout(spawnImpl, cmd, args, options, timeoutMs) {
253
+ return new Promise((resolve) => {
254
+ let settled = false
255
+ let exitFallbackTimer = null
256
+ const stderrChunks = []
257
+ let stderrLen = 0
258
+
259
+ let child
260
+ try {
261
+ child = spawnImpl(cmd, args, options)
262
+ } catch (error) {
263
+ resolve({ played: false, reason: error?.message || 'spawn failed' })
264
+ return
265
+ }
266
+ if (!child || typeof child.once !== 'function') {
267
+ resolve({ played: false, reason: 'Invalid child process handle' })
268
+ return
269
+ }
270
+
271
+ const timer = setTimeout(() => {
272
+ try {
273
+ child.kill?.('SIGKILL')
274
+ } catch {
275
+ try {
276
+ child.kill?.()
277
+ } catch {
278
+ // Ignore kill error
279
+ }
280
+ }
281
+ finish({ played: false, reason: 'timeout' })
282
+ }, timeoutMs)
283
+ timer.unref?.()
284
+
285
+ function finish(result) {
286
+ if (settled) return
287
+ settled = true
288
+ clearTimeout(timer)
289
+ if (exitFallbackTimer) clearTimeout(exitFallbackTimer)
290
+ resolve(result)
291
+ }
292
+
293
+ if (child.stderr && typeof child.stderr.on === 'function') {
294
+ child.stderr.on('data', (chunk) => {
295
+ if (stderrLen >= MAX_STDERR_BYTES) return
296
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))
297
+ const slice = buf.subarray(0, MAX_STDERR_BYTES - stderrLen)
298
+ stderrChunks.push(slice)
299
+ stderrLen += slice.length
300
+ })
301
+ }
302
+
303
+ child.once('error', (error) => {
304
+ finish({ played: false, reason: error?.message || 'process error' })
305
+ })
306
+
307
+ const handleCompletion = (code, signal) => {
308
+ if (code === 0) {
309
+ finish({ played: true })
310
+ return
311
+ }
312
+ const stderrText = Buffer.concat(stderrChunks).toString('utf8').replace(/\s+/g, ' ').trim()
313
+ const detail = stderrText || (signal ? `signal ${signal}` : `exit code ${code}`)
314
+ finish({ played: false, reason: detail })
315
+ }
316
+
317
+ child.once('close', handleCompletion)
318
+ child.once('exit', (code, signal) => {
319
+ if (settled) return
320
+ exitFallbackTimer = setTimeout(() => handleCompletion(code, signal), 25)
321
+ exitFallbackTimer.unref?.()
322
+ })
323
+ })
324
+ }
325
+
326
+ /**
327
+ * Play a local WAV file on the Host OS with bounded timeout and non-throwing result.
328
+ * @param {string} filePath
329
+ * @param {{ platform?: string, spawnImpl?: Function, timeoutMs?: number }} [opts]
330
+ * @returns {Promise<{ played: boolean, reason?: string }>}
331
+ */
332
+ export async function playNativeSound(
333
+ filePath,
334
+ { platform = process.platform, spawnImpl = nodeSpawn, timeoutMs = DEFAULT_PLAY_TIMEOUT_MS } = {},
335
+ ) {
336
+ if (typeof filePath !== 'string' || !filePath.trim() || filePath.includes('\0')) {
337
+ return { played: false, reason: 'Invalid sound file path' }
338
+ }
339
+ const boundedTimeout =
340
+ Number.isFinite(timeoutMs) && timeoutMs > 0
341
+ ? Math.min(Math.round(timeoutMs), MAX_PLAY_TIMEOUT_MS)
342
+ : DEFAULT_PLAY_TIMEOUT_MS
343
+
344
+ const scrubbedEnv = await getScrubbedEnv()
345
+
346
+ if (platform === 'win32') {
347
+ return runCommandWithTimeout(
348
+ spawnImpl,
349
+ 'powershell.exe',
350
+ ['-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-Command', WIN32_PLAY_COMMAND],
351
+ {
352
+ env: { ...scrubbedEnv, DSH_SOUND_PATH: filePath },
353
+ windowsHide: true,
354
+ stdio: ['ignore', 'ignore', 'pipe'],
355
+ },
356
+ boundedTimeout,
357
+ )
358
+ }
359
+
360
+ if (platform === 'darwin') {
361
+ return runCommandWithTimeout(
362
+ spawnImpl,
363
+ 'afplay',
364
+ [filePath],
365
+ {
366
+ env: scrubbedEnv,
367
+ windowsHide: true,
368
+ stdio: ['ignore', 'ignore', 'pipe'],
369
+ },
370
+ boundedTimeout,
371
+ )
372
+ }
373
+
374
+ if (platform === 'linux') {
375
+ const deadline = Date.now() + boundedTimeout
376
+ const first = await runCommandWithTimeout(
377
+ spawnImpl,
378
+ 'paplay',
379
+ [filePath],
380
+ {
381
+ env: scrubbedEnv,
382
+ windowsHide: true,
383
+ stdio: ['ignore', 'ignore', 'pipe'],
384
+ },
385
+ boundedTimeout,
386
+ )
387
+ if (first.played || first.reason === 'timeout') return first
388
+ const remaining = Math.max(1000, deadline - Date.now())
389
+ return runCommandWithTimeout(
390
+ spawnImpl,
391
+ 'aplay',
392
+ [filePath],
393
+ {
394
+ env: scrubbedEnv,
395
+ windowsHide: true,
396
+ stdio: ['ignore', 'ignore', 'pipe'],
397
+ },
398
+ remaining,
399
+ )
400
+ }
401
+
402
+ return { played: false, reason: `Unsupported platform: ${platform}` }
403
+ }