cc-viewer 1.9.25 → 1.9.26

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.
Files changed (100) hide show
  1. package/README.md +1 -1
  2. package/dist/assets/App-CjP88gbM.css +1 -0
  3. package/dist/assets/App-CkbwkH74.js +2 -0
  4. package/dist/assets/ArchivePreview-1XAr8LvB.js +1 -0
  5. package/dist/assets/AudioPreview-7zCADwCz.css +1 -0
  6. package/dist/assets/AudioPreview-DGcbrJjl.js +1 -0
  7. package/dist/assets/{MdxEditorPanel-BiKPuJGb.js → MdxEditorPanel-DFGSL5OM.js} +1 -1
  8. package/dist/assets/Mobile-DFu8Kn5W.js +1 -0
  9. package/dist/assets/ProxyStatsModal-BU9liIIO.js +1 -0
  10. package/dist/assets/SubtitlePreview-BGW9y2LI.css +1 -0
  11. package/dist/assets/SubtitlePreview-Ca_dpMFL.js +1 -0
  12. package/dist/assets/{_baseUniq-h4hafO2D.js → _baseUniq-9PjtCZvX.js} +1 -1
  13. package/dist/assets/{arc-CN5nAVn-.js → arc-C7i0W-3s.js} +1 -1
  14. package/dist/assets/{architectureDiagram-Q4EWVU46-NTnIUsWP.js → architectureDiagram-Q4EWVU46-B0-9CMiF.js} +1 -1
  15. package/dist/assets/{blockDiagram-DXYQGD6D-BPFMPOwn.js → blockDiagram-DXYQGD6D-v3Zg9ooQ.js} +1 -1
  16. package/dist/assets/{c4Diagram-AHTNJAMY-CAPyXRVj.js → c4Diagram-AHTNJAMY-BngN_7qF.js} +1 -1
  17. package/dist/assets/{channel-BULnUStk.js → channel-IbZhDvnM.js} +1 -1
  18. package/dist/assets/{chunk-4BX2VUAB-BeSOU8fB.js → chunk-4BX2VUAB-8cHviTVA.js} +1 -1
  19. package/dist/assets/{chunk-4TB4RGXK-BVCrVLA0.js → chunk-4TB4RGXK-C3CP4doN.js} +1 -1
  20. package/dist/assets/{chunk-55IACEB6-D0XHzdzo.js → chunk-55IACEB6-FUVA-xfN.js} +1 -1
  21. package/dist/assets/{chunk-EDXVE4YY-DizHN_m_.js → chunk-EDXVE4YY-BL4ddY7-.js} +1 -1
  22. package/dist/assets/{chunk-FMBD7UC4-3r0oXmep.js → chunk-FMBD7UC4-fgqPq6Tx.js} +1 -1
  23. package/dist/assets/{chunk-OYMX7WX6-C701FNEA.js → chunk-OYMX7WX6-BGnPcd9h.js} +1 -1
  24. package/dist/assets/{chunk-QZHKN3VN-KAdMyJai.js → chunk-QZHKN3VN-Cs6WjmqO.js} +1 -1
  25. package/dist/assets/{chunk-YZCP3GAM-Cn2gaRZ3.js → chunk-YZCP3GAM-qq4Q4j7H.js} +1 -1
  26. package/dist/assets/classDiagram-6PBFFD2Q-Bszndikj.js +1 -0
  27. package/dist/assets/classDiagram-v2-HSJHXN6E-Bszndikj.js +1 -0
  28. package/dist/assets/clone-MC_fW61A.js +1 -0
  29. package/dist/assets/{cose-bilkent-S5V4N54A-URab8isi.js → cose-bilkent-S5V4N54A-D-uK3RSk.js} +1 -1
  30. package/dist/assets/{dagre-KV5264BT-Cq24tJ6h.js → dagre-KV5264BT-BulmeCnQ.js} +1 -1
  31. package/dist/assets/{diagram-5BDNPKRD-D4KEpJ0T.js → diagram-5BDNPKRD-DI7Q04yx.js} +1 -1
  32. package/dist/assets/{diagram-G4DWMVQ6-DZLa6S7S.js → diagram-G4DWMVQ6-B7zYIZac.js} +1 -1
  33. package/dist/assets/{diagram-MMDJMWI5-BBhsOBKy.js → diagram-MMDJMWI5-D_f5k-GJ.js} +1 -1
  34. package/dist/assets/{diagram-TYMM5635-ClWpYbD-.js → diagram-TYMM5635-DQ-vW7nJ.js} +1 -1
  35. package/dist/assets/{erDiagram-SMLLAGMA-5RXRgGvh.js → erDiagram-SMLLAGMA-BgubHrDi.js} +1 -1
  36. package/dist/assets/{flowDiagram-DWJPFMVM-DXiHDbOU.js → flowDiagram-DWJPFMVM-fPYA9wmX.js} +1 -1
  37. package/dist/assets/{ganttDiagram-T4ZO3ILL-Db5oVw9h.js → ganttDiagram-T4ZO3ILL-hNsatnIF.js} +1 -1
  38. package/dist/assets/{gitGraphDiagram-UUTBAWPF-CCPK1X9H.js → gitGraphDiagram-UUTBAWPF-1GijxkLh.js} +1 -1
  39. package/dist/assets/{graph-DNxO4J9w.js → graph-sNq_HPra.js} +1 -1
  40. package/dist/assets/{index-DaP3fzs1.js → index-BnWh6jkG.js} +1 -1
  41. package/dist/assets/{index-Bc_IaWe7.js → index-CmwhODrM.js} +1 -1
  42. package/dist/assets/{index-Do02L044.js → index-D6mBgqj7.js} +1 -1
  43. package/dist/assets/{index-CXW8X8EW.js → index-DggrqRzx.js} +1 -1
  44. package/dist/assets/{index-HLRCpKmY.js → index-DiVw76Ih.js} +1 -1
  45. package/dist/assets/index-Dn7twftJ.js +2 -0
  46. package/dist/assets/{index-DDo6Z3Ov.js → index-ijWns1Ex.js} +1 -1
  47. package/dist/assets/{index-DR_FOzBM.js → index-ng96S3Hy.js} +1 -1
  48. package/dist/assets/{infoDiagram-42DDH7IO-CzPZsFEc.js → infoDiagram-42DDH7IO-C9HYi6HU.js} +1 -1
  49. package/dist/assets/{ishikawaDiagram-UXIWVN3A-eEVseuO_.js → ishikawaDiagram-UXIWVN3A-D3Ae6xRc.js} +1 -1
  50. package/dist/assets/{journeyDiagram-VCZTEJTY-CmMKnKhj.js → journeyDiagram-VCZTEJTY-BMPDBa6W.js} +1 -1
  51. package/dist/assets/{jszip.min-JnHXMwa-.js → jszip.min-D6JfNfcl.js} +1 -1
  52. package/dist/assets/{kanban-definition-6JOO6SKY-CZMggR3M.js → kanban-definition-6JOO6SKY-BXEtzhr-.js} +1 -1
  53. package/dist/assets/{layout-DVqRDfNO.js → layout-CbMMhBh2.js} +1 -1
  54. package/dist/assets/{linear-BHB3KNeC.js → linear-DivVFiS7.js} +1 -1
  55. package/dist/assets/{mermaid.core-DOjmjAg3.js → mermaid.core-Dq-d8oPN.js} +2 -2
  56. package/dist/assets/{min-DxJCEK6c.js → min-CXI1r_lz.js} +1 -1
  57. package/dist/assets/{mindmap-definition-QFDTVHPH-B6W3RjCJ.js → mindmap-definition-QFDTVHPH-CONBMUxc.js} +1 -1
  58. package/dist/assets/{pieDiagram-DEJITSTG-BRNQVuFX.js → pieDiagram-DEJITSTG-C0rsPXdi.js} +1 -1
  59. package/dist/assets/{quadrantDiagram-34T5L4WZ-CUCnCkJJ.js → quadrantDiagram-34T5L4WZ-DA2PNu4u.js} +1 -1
  60. package/dist/assets/{requirementDiagram-MS252O5E-Ds-5hLni.js → requirementDiagram-MS252O5E-DjsBvm40.js} +1 -1
  61. package/dist/assets/{sankeyDiagram-XADWPNL6-Cxi30RZc.js → sankeyDiagram-XADWPNL6-Drl_Kmzt.js} +1 -1
  62. package/dist/assets/{seqResourceLoaders-DH-Nl0yh.css → seqResourceLoaders-CjAnOisT.css} +1 -1
  63. package/dist/assets/seqResourceLoaders-L-Fzax-z.js +2 -0
  64. package/dist/assets/{sequenceDiagram-FGHM5R23-C6CukZv8.js → sequenceDiagram-FGHM5R23-Dcz5NXKY.js} +1 -1
  65. package/dist/assets/{stateDiagram-FHFEXIEX-iPJCU2Ja.js → stateDiagram-FHFEXIEX-7P3czdgX.js} +1 -1
  66. package/dist/assets/{stateDiagram-v2-QKLJ7IA2-DMFhwtNH.js → stateDiagram-v2-QKLJ7IA2-C3xgfAOE.js} +1 -1
  67. package/dist/assets/{timeline-definition-GMOUNBTQ-Dqd-tCUs.js → timeline-definition-GMOUNBTQ-BVe-eF-9.js} +1 -1
  68. package/dist/assets/util-DUb-88OI.js +1 -0
  69. package/dist/assets/{vendor-antd-D1L_UwKJ.js → vendor-antd-VJVAjRBJ.js} +1 -1
  70. package/dist/assets/{vendor-codemirror-DOZOjrWx.js → vendor-codemirror-D2yaEhu3.js} +1 -1
  71. package/dist/assets/{vendor-mdxeditor-8ZUcYZ6G.js → vendor-mdxeditor-DKI8QSRd.js} +2 -2
  72. package/dist/assets/{vendor-qrcode-Pw_LHfBZ.js → vendor-qrcode-CDB9Y_Vp.js} +1 -1
  73. package/dist/assets/{vendor-virtuoso-AhfR22q5.js → vendor-virtuoso-DEFa9UCG.js} +1 -1
  74. package/dist/assets/{vennDiagram-DHZGUBPP-CrOJisSD.js → vennDiagram-DHZGUBPP-C8KL2OR8.js} +1 -1
  75. package/dist/assets/{wardley-RL74JXVD-By8Ltw9G.js → wardley-RL74JXVD-Dm4mxyoW.js} +1 -1
  76. package/dist/assets/{wardleyDiagram-NUSXRM2D-5SnzlvF9.js → wardleyDiagram-NUSXRM2D-BoA34gDh.js} +1 -1
  77. package/dist/assets/{xychartDiagram-5P7HB3ND-CJ4uNjoK.js → xychartDiagram-5P7HB3ND-66ynIBzj.js} +1 -1
  78. package/dist/index.html +4 -4
  79. package/package.json +1 -1
  80. package/server/lib/approval-policy.js +5 -2
  81. package/server/lib/ask/perm-bridge.js +4 -0
  82. package/server/lib/ask/perm-request-bridge.js +1 -1
  83. package/server/lib/audio-stream.js +267 -0
  84. package/server/lib/auto-approve.js +26 -5
  85. package/server/lib/sdk-manager.js +19 -10
  86. package/server/lib/terminal-ws-ping.js +42 -0
  87. package/server/proxy.js +16 -9
  88. package/server/routes/ask-perm.js +17 -13
  89. package/server/routes/files-content.js +65 -0
  90. package/server/server.js +50 -6
  91. package/dist/assets/App-BUIwNK3C.js +0 -2
  92. package/dist/assets/App-C5xq-7nS.css +0 -1
  93. package/dist/assets/ArchivePreview-BuFE-N7z.js +0 -1
  94. package/dist/assets/Mobile-D2UvqCIN.js +0 -1
  95. package/dist/assets/ProxyStatsModal-CBdBgS9_.js +0 -1
  96. package/dist/assets/classDiagram-6PBFFD2Q-7MJg98xK.js +0 -1
  97. package/dist/assets/classDiagram-v2-HSJHXN6E-7MJg98xK.js +0 -1
  98. package/dist/assets/clone-Bddq99Xt.js +0 -1
  99. package/dist/assets/index-ev1Hmm1O.js +0 -2
  100. package/dist/assets/seqResourceLoaders-B8ZIXCeg.js +0 -2
@@ -0,0 +1,267 @@
1
+ /**
2
+ * Audio Stream — dedicated streaming response module for audio preview.
3
+ *
4
+ * Backs /api/audio-stream with single-range HTTP Range support. Unlike fileRaw
5
+ * (full buffer, 10MB cap), this streams via createReadStream and supports
6
+ * 206/416/304/If-Range, satisfying Safari/WebKit's byte-range requirement (it
7
+ * probes with `Range: bytes=0-1`).
8
+ *
9
+ * Design boundaries:
10
+ * - The sniffer only ever overrides to an audio/* MIME, never video/* (the ftyp
11
+ * brand cannot reliably tell audio m4a from video mp4); the extension MIME is
12
+ * the fallback.
13
+ * - parseByteRange supports suffix ranges and clamping, per RFC 9110 §14.
14
+ * - serveAudioStream wraps everything in a top-level try/catch with a
15
+ * res.headersSent guard so no sync fs error becomes an unhandled rejection
16
+ * that kills the process (see server.js:985).
17
+ */
18
+
19
+ import { openSync, readSync, closeSync, createReadStream } from 'node:fs';
20
+ import { reportSwallowed } from './error-report.js';
21
+
22
+ /**
23
+ * Extension → audio/* MIME. `.opus` is an Ogg container (RFC 7845 §9); `.m4a`
24
+ * uses audio/mp4 (RFC 4337); `.flac` uses audio/flac (RFC 9639).
25
+ */
26
+ const AUDIO_MIME = {
27
+ '.mp3': 'audio/mpeg',
28
+ '.wav': 'audio/wav',
29
+ '.ogg': 'audio/ogg',
30
+ '.oga': 'audio/ogg',
31
+ '.opus': 'audio/ogg',
32
+ '.m4a': 'audio/mp4',
33
+ '.aac': 'audio/aac',
34
+ '.flac': 'audio/flac',
35
+ };
36
+
37
+ /** Supported audio extensions (lowercase, leading dot). */
38
+ const AUDIO_EXTENSIONS = new Set(Object.keys(AUDIO_MIME));
39
+
40
+ /** How many head bytes readHead reads; large enough to span a typical ID3v2 tag. */
41
+ const SNIFF_BYTES = 4096;
42
+
43
+ /**
44
+ * Derive the lowercased extension from a real file path, cross-platform
45
+ * (basename via split(/[\\/]/), last dot).
46
+ * @param {string} filePath
47
+ * @returns {string} lowercase extension with leading dot, or ''
48
+ */
49
+ function audioExtOf(filePath) {
50
+ const base = String(filePath || '').split(/[\\/]/).pop() || '';
51
+ const dot = base.lastIndexOf('.');
52
+ return dot > 0 ? base.slice(dot).toLowerCase() : '';
53
+ }
54
+
55
+ /**
56
+ * Read the first SNIFF_BYTES for container sniffing. Uses
57
+ * openSync/readSync/finally closeSync and never readFileSync (a multi-GB audio
58
+ * file would blow up memory). Short reads / failures are non-fatal.
59
+ * @param {string} filePath
60
+ * @param {number} [size] file size (avoids over-reading a small file)
61
+ * @returns {Buffer|null} first N bytes, or null on failure
62
+ */
63
+ function readHead(filePath, size) {
64
+ let fd;
65
+ try {
66
+ fd = openSync(filePath, 'r');
67
+ const len = Math.min(SNIFF_BYTES, typeof size === 'number' && size >= 0 ? size : SNIFF_BYTES);
68
+ if (len <= 0) return null;
69
+ const buf = Buffer.alloc(len);
70
+ const n = readSync(fd, buf, 0, len, 0);
71
+ return n > 0 ? buf.subarray(0, n) : null;
72
+ } catch (err) {
73
+ reportSwallowed('audioStream.readHead', err);
74
+ return null;
75
+ } finally {
76
+ if (fd !== undefined) {
77
+ try { closeSync(fd); } catch (err) { reportSwallowed('audioStream.closeHead', err); }
78
+ }
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Sniff the real audio MIME from magic bytes; only ever returns audio/*, never
84
+ * video/*. Order: ADTS before the generic MP3 frame sync (both use a 0xFF sync,
85
+ * and ID3 can also prefix ADTS).
86
+ * @param {Buffer|null} buf head bytes
87
+ * @param {string} ext lowercase extension with leading dot (fallback)
88
+ * @returns {string} an audio/* MIME
89
+ */
90
+ function sniffAudioMime(buf, ext) {
91
+ const fallback = AUDIO_MIME[ext] || 'application/octet-stream';
92
+ if (!buf || buf.length < 2) return fallback;
93
+
94
+ // Ogg container: OggS; the first packet (~offset 28) distinguishes
95
+ // Opus/Vorbis/FLAC, but all already map to audio/ogg.
96
+ if (buf.length >= 4 && buf[0] === 0x4f && buf[1] === 0x67 && buf[2] === 0x67 && buf[3] === 0x53) {
97
+ return 'audio/ogg';
98
+ }
99
+ // Native FLAC: fLaC.
100
+ if (buf.length >= 4 && buf[0] === 0x66 && buf[1] === 0x4c && buf[2] === 0x61 && buf[3] === 0x43) {
101
+ return 'audio/flac';
102
+ }
103
+ // WAV: RIFF....WAVE.
104
+ if (buf.length >= 12 &&
105
+ buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 &&
106
+ buf[8] === 0x57 && buf[9] === 0x41 && buf[10] === 0x56 && buf[11] === 0x45) {
107
+ return 'audio/wav';
108
+ }
109
+ // MP4/M4A: ftyp at offset 4; the brand cannot reliably split audio from video,
110
+ // so this audio-only route always serves audio/mp4.
111
+ if (buf.length >= 8 && buf[4] === 0x66 && buf[5] === 0x74 && buf[6] === 0x79 && buf[7] === 0x70) {
112
+ return 'audio/mp4';
113
+ }
114
+ // ID3v2 tag: may prefix MP3 or ADTS AAC, so look past the tag for the frame sync.
115
+ if (buf.length >= 3 && buf[0] === 0x49 && buf[1] === 0x44 && buf[2] === 0x33) {
116
+ // ID3v2 size is syncsafe at offset 6-9; skip the tag to find the frame.
117
+ if (buf.length >= 10) {
118
+ const tagSize = ((buf[6] & 0x7f) << 21) | ((buf[7] & 0x7f) << 14) | ((buf[8] & 0x7f) << 7) | (buf[9] & 0x7f);
119
+ const frameAt = 10 + tagSize;
120
+ if (frameAt + 1 < buf.length) {
121
+ const b0 = buf[frameAt]; const b1 = buf[frameAt + 1];
122
+ if (b0 === 0xff && (b1 & 0xf6) === 0xf0) return 'audio/aac'; // ADTS (MPEG-2/4)
123
+ if (b0 === 0xff && (b1 & 0xe0) === 0xe0 && (b1 & 0x06) !== 0) return 'audio/mpeg'; // MP3, layer bits≠00
124
+ return 'audio/mpeg'; // ID3 with a non-ADTS frame defaults to MP3
125
+ }
126
+ }
127
+ // Tag larger than the sniff window: trust the extension rather than guess.
128
+ return fallback;
129
+ }
130
+ // ADTS AAC: FF F1/F9 (MPEG-4) or FF F0/F8 (MPEG-2), 12-bit sync, layer bits 00.
131
+ if (buf[0] === 0xff && (buf[1] & 0xf6) === 0xf0) {
132
+ return 'audio/aac';
133
+ }
134
+ // Bare MP3 frame: FF Ex/Fx with layer bits≠00.
135
+ if (buf[0] === 0xff && (buf[1] & 0xe0) === 0xe0 && (buf[1] & 0x06) !== 0) {
136
+ return 'audio/mpeg';
137
+ }
138
+ return fallback;
139
+ }
140
+
141
+ /**
142
+ * Parse a single-range Range header. Multi-range / malformed returns null (the
143
+ * caller ignores it and serves 200).
144
+ * @param {string|undefined} header Range header value
145
+ * @param {number} size total file bytes
146
+ * @returns {{start:number,end:number}|'unsatisfiable'|null}
147
+ */
148
+ function parseByteRange(header, size) {
149
+ if (!header || typeof header !== 'string') return null;
150
+ if (!Number.isSafeInteger(size) || size <= 0) return 'unsatisfiable'; // any range on an empty file is 416
151
+ const m = /^bytes=(\d*)-(\d*)$/i.exec(header.trim());
152
+ if (!m || (m[1] === '' && m[2] === '')) return null; // malformed / multi-range → ignore (200)
153
+
154
+ if (m[1] === '') {
155
+ // Suffix: bytes=-N
156
+ const n = Number(m[2]);
157
+ if (!Number.isSafeInteger(n) || n <= 0) return 'unsatisfiable';
158
+ return { start: Math.max(0, size - n), end: size - 1 };
159
+ }
160
+
161
+ const start = Number(m[1]);
162
+ if (!Number.isSafeInteger(start) || start >= size) return 'unsatisfiable';
163
+ const end = m[2] === '' ? size - 1 : Math.min(Number(m[2]), size - 1);
164
+ if (!Number.isSafeInteger(end) || end < start) return null; // invalid → ignore (200)
165
+ return { start, end };
166
+ }
167
+
168
+ /**
169
+ * Stream an audio response. Order: 304 (If-None-Match) → If-Range →
170
+ * Range (206) / 200. HEAD ignores Range and returns 200 headers only (and also
171
+ * sniffs, so its Content-Type matches GET).
172
+ * @param {import('node:http').IncomingMessage} req
173
+ * @param {import('node:http').ServerResponse} res
174
+ * @param {{filePath:string, stat:import('node:fs').Stats, ext:string}} ctx
175
+ */
176
+ function serveAudioStream(req, res, ctx) {
177
+ const { filePath, stat, ext } = ctx;
178
+ const size = stat.size;
179
+ const name = String(filePath || '').split(/[\\/]/).pop() || 'audio';
180
+ const etag = `"${size.toString(16)}-${Math.floor(stat.mtimeMs).toString(16)}"`;
181
+
182
+ // 304 takes priority over Range and needs no body or sniffed Content-Type.
183
+ if (req.headers['if-none-match'] && req.headers['if-none-match'] === etag) {
184
+ res.writeHead(304, { 'Cache-Control': 'private', 'ETag': etag });
185
+ res.end();
186
+ return;
187
+ }
188
+
189
+ const base = {
190
+ 'Content-Type': sniffAudioMime(readHead(filePath, size), ext),
191
+ 'Accept-Ranges': 'bytes',
192
+ 'Cache-Control': 'private',
193
+ 'ETag': etag,
194
+ 'Content-Disposition': `inline; filename*=UTF-8''${encodeURIComponent(name)}`,
195
+ 'X-Content-Type-Options': 'nosniff',
196
+ };
197
+
198
+ // HEAD: no stream, 200 headers (Range is GET-only and ignored).
199
+ if (req.method === 'HEAD') {
200
+ res.writeHead(200, { ...base, 'Content-Length': size });
201
+ res.end();
202
+ return;
203
+ }
204
+
205
+ // Empty file: serve a clean 200 with Content-Length 0; a 0-length
206
+ // createReadStream range (end=-1) would throw after headers are sent.
207
+ if (size === 0) {
208
+ res.writeHead(200, { ...base, 'Content-Length': 0 });
209
+ res.end();
210
+ return;
211
+ }
212
+
213
+ // If-Range: only an exact strong-ETag match continues with Range, else ignore it → 200.
214
+ const ifRange = req.headers['if-range'];
215
+ const rangeOk = !ifRange || ifRange === etag;
216
+ const range = rangeOk ? parseByteRange(req.headers.range, size) : null;
217
+
218
+ // 416: valid-but-unsatisfiable.
219
+ if (range === 'unsatisfiable') {
220
+ res.writeHead(416, {
221
+ 'Content-Range': `bytes */${size}`,
222
+ 'Content-Length': 0,
223
+ 'Accept-Ranges': 'bytes',
224
+ });
225
+ res.end();
226
+ return;
227
+ }
228
+
229
+ let status; let headers; let start; let end;
230
+ if (range) {
231
+ // 206: must carry Content-Range (Safari seek depends on it).
232
+ ({ start, end } = range);
233
+ status = 206;
234
+ headers = {
235
+ ...base,
236
+ 'Content-Range': `bytes ${start}-${end}/${size}`,
237
+ 'Content-Length': end - start + 1,
238
+ };
239
+ } else {
240
+ // 200: never carries Content-Range; the explicit end bound prevents a file
241
+ // that grows mid-request from exceeding Content-Length.
242
+ start = 0; end = size - 1;
243
+ status = 200;
244
+ headers = { ...base, 'Content-Length': size };
245
+ }
246
+
247
+ res.writeHead(status, headers);
248
+ const stream = createReadStream(filePath, { start, end });
249
+ // Headers are already sent by the time a read error can fire, so we can only
250
+ // abort the response mid-stream; report it for diagnosis.
251
+ stream.on('error', (err) => { reportSwallowed('audioStream.stream', err); res.destroy(); });
252
+ // Stop reading from disk if the client aborts (e.g. skips the preview).
253
+ res.on('close', () => { stream.destroy(); });
254
+ // If the socket was already destroyed before these listeners attached, the
255
+ // 'close' event already fired and never will again — destroy the stream now.
256
+ if (res.destroyed) { stream.destroy(); return; }
257
+ stream.pipe(res);
258
+ }
259
+
260
+ export {
261
+ AUDIO_MIME,
262
+ AUDIO_EXTENSIONS,
263
+ audioExtOf,
264
+ sniffAudioMime,
265
+ parseByteRange,
266
+ serveAudioStream,
267
+ };
@@ -18,7 +18,10 @@
18
18
  // Semantics of the settings (shared with the client):
19
19
  // plan: prefs.approvalModal.planAutoApproveSeconds (default 0 = off)
20
20
  // perm: prefs.autoApproveSeconds (default 3 when unset)
21
- // 0/off, N>0 = N seconds, -1 = instant (resolve immediately, no buffer).
21
+ // 0/off, N>0 = N seconds, -1 = instant (resolve immediately, no buffer),
22
+ // -2 = full auto-approve (完全免审批): instant like -1, and the npm-publish
23
+ // hard gate (approval-policy.js isPublishCommand) is lifted — perm only;
24
+ // a hand-edited plan -2 is treated as off.
22
25
  // AskUserQuestion hosting ("问答题自动托管") is a separate feature with minute
23
26
  // semantics and lives in ./ask-auto-answer.js — it is not routed through this module
24
27
  // (the 300s cap would silently disable its 10/20/30-minute tiers).
@@ -30,6 +33,10 @@ import { reportSwallowed } from './error-report.js';
30
33
  export const AUTO_APPROVE_BUFFER_MS = 1000;
31
34
  export const DEFAULT_PERM_AUTO_APPROVE_SECONDS = 3;
32
35
  export const AUTO_APPROVE_INSTANT = -1;
36
+ // 完全免审批 (full auto-approve): instant like -1, and additionally lifts the
37
+ // npm-publish hard gate (approval-policy.js isPublishCommand). Deliberately
38
+ // permission-only — a hand-edited planAutoApproveSeconds: -2 is treated as off.
39
+ export const AUTO_APPROVE_FULL = -2;
33
40
  // A hand-edited preferences.json can hold an absurdly large value. Besides being
34
41
  // pointless, a value above the 5-minute hard approval timeout would advertise an
35
42
  // autoApproveAt the deny timeout always beats (a lying countdown); and beyond
@@ -39,8 +46,8 @@ export const MAX_AUTO_APPROVE_SECONDS = 300;
39
46
 
40
47
  /**
41
48
  * Extract the configured seconds for a kind ('plan' | 'perm') from an effective
42
- * prefs object. Returns null when disabled (0 / invalid / negative other than -1 /
43
- * absurdly large).
49
+ * prefs object. Returns null when disabled (0 / invalid / negative other than
50
+ * -1 (and -2 for perm) / absurdly large).
44
51
  */
45
52
  export function effectiveAutoApproveSeconds(kind, prefs) {
46
53
  const raw = kind === 'plan'
@@ -49,11 +56,25 @@ export function effectiveAutoApproveSeconds(kind, prefs) {
49
56
  const seconds = Number(raw);
50
57
  if (!Number.isFinite(seconds)) return null;
51
58
  if (seconds === AUTO_APPROVE_INSTANT) return AUTO_APPROVE_INSTANT;
59
+ if (kind === 'perm' && seconds === AUTO_APPROVE_FULL) return AUTO_APPROVE_FULL;
52
60
  if (seconds <= 0) return null;
53
61
  if (seconds > MAX_AUTO_APPROVE_SECONDS) return null;
54
62
  return seconds;
55
63
  }
56
64
 
65
+ /**
66
+ * Whether a raw prefs value opts into automatic approval at all (instant tiers
67
+ * -1/-2, or a positive countdown). Used where only the opt-in matters, not the
68
+ * tier: the Read/Glob/Grep outside-cwd directory-grant paths and the
69
+ * PermissionRequest hook's silent-allow decision. Number()-normalizes so a
70
+ * hand-edited string value ("-1") keeps working like before.
71
+ */
72
+ export function isAutoApproveEnabledValue(raw) {
73
+ const seconds = Number(raw);
74
+ if (!Number.isFinite(seconds)) return false;
75
+ return seconds === AUTO_APPROVE_INSTANT || seconds === AUTO_APPROVE_FULL || seconds > 0;
76
+ }
77
+
57
78
  /**
58
79
  * Read prefs (project-fork aware) and compute the auto-approve deadline for a
59
80
  * pending approval. `projectKey` is the session cwd (SDK) or hook-reported cwd
@@ -75,7 +96,7 @@ export function computeAutoApprove(kind, projectKey, { now = Date.now(), readPre
75
96
  const effective = hasFork(prefs, key) ? resolveScoped(prefs, prefs.prefsByProject[key]) : prefs;
76
97
  const seconds = effectiveAutoApproveSeconds(kind, effective);
77
98
  if (seconds === null) return { enabled: false };
78
- const instant = seconds === AUTO_APPROVE_INSTANT;
99
+ const instant = seconds === AUTO_APPROVE_INSTANT || seconds === AUTO_APPROVE_FULL;
79
100
  return {
80
101
  enabled: true,
81
102
  instant,
@@ -99,7 +120,7 @@ export function autoApproveFireDelayMs(computed, now = Date.now()) {
99
120
  * pending entry: { autoApproveAt, seconds, cancelled, timer }.
100
121
  * `onFire` is invoked once when the deadline (+buffer) passes; callers must
101
122
  * re-check the entry is still pending and not cancelled inside onFire.
102
- * Instant (-1) fires SYNCHRONOUSLY — the caller MUST register the pending entry
123
+ * Instant (-1/-2) fires SYNCHRONOUSLY — the caller MUST register the pending entry
103
124
  * (and emit the pending frame) before calling this.
104
125
  */
105
126
  export function createAutoApproveState(computed, onFire) {
@@ -42,6 +42,8 @@ import {
42
42
  createAutoApproveState,
43
43
  cancelAutoApproveState,
44
44
  replayAutoApproveFields,
45
+ isAutoApproveEnabledValue,
46
+ AUTO_APPROVE_FULL,
45
47
  } from './auto-approve.js';
46
48
  import {
47
49
  computeAskAutoAnswer,
@@ -939,7 +941,8 @@ function _createSession(key, cwd) {
939
941
  // canUseTool is mounted in EVERY mode (including bypassPermissions) so the
940
942
  // npm-publish hard gate survives --d, mirroring perm-bridge.js's bypass
941
943
  // exemption. In bypass mode the callback early-allows everything except
942
- // publish commands and the two interactive tools (see _handleCanUseTool).
944
+ // publish commands and the two interactive tools (see _handleCanUseTool);
945
+ // the only publish exemption is the explicit full auto-approve tier (-2).
943
946
  canUseTool: _handleCanUseTool,
944
947
  ..._permissionMode === 'bypassPermissions' && { allowDangerouslySkipPermissions: true },
945
948
  };
@@ -2067,7 +2070,9 @@ function _createSession(key, cwd) {
2067
2070
  }
2068
2071
  }
2069
2072
 
2070
- // 2. npm publish is never auto-allowed, even under --d (safety floor).
2073
+ // 2. npm publish is not auto-allowed by default, even under --d (safety floor) —
2074
+ // the only exception is the explicit full auto-approve tier (-2) resolved in the
2075
+ // perm branch below.
2071
2076
  const isPublish = isPublishCommand(toolName, input);
2072
2077
 
2073
2078
  // 3. Bypass mode auto-approves everything except publish and the two
@@ -2180,8 +2185,7 @@ function _createSession(key, cwd) {
2180
2185
  // directory is not trusted for subsequent calls.
2181
2186
  if (toolName === 'Read' || toolName === 'Glob' || toolName === 'Grep') {
2182
2187
  const prefs = readPrefsRaw();
2183
- const autoApproveSeconds = Number(prefs.autoApproveSeconds);
2184
- const shouldGrantDir = autoApproveSeconds === -1 || autoApproveSeconds > 0;
2188
+ const shouldGrantDir = isAutoApproveEnabledValue(prefs.autoApproveSeconds);
2185
2189
  const sessionCwd = _cwd || process.env.CCV_PROJECT_DIR;
2186
2190
  if (sessionCwd && shouldGrantDir) {
2187
2191
  let targetDir = null;
@@ -2227,10 +2231,15 @@ function _createSession(key, cwd) {
2227
2231
  // unknown decision → fall through to normal approval flow
2228
2232
  } catch (err) { reportSwallowed('sdk-manager.waterfall.perm', err); }
2229
2233
  }
2230
- // npm publish is a hard safety floor: it must always wait for a HUMAN decision
2231
- // (the 5-minute deny timeout applies), never the server-side auto-approve fallback.
2232
- // Same exemption for unattended scheduled-task runs (ctx != null).
2233
- const permAuto = (isPublish || ctx) ? { enabled: false } : computeAutoApprove('perm', _cwd);
2234
+ // npm publish is a hard safety floor: it must wait for a HUMAN decision at
2235
+ // every tier EXCEPT the explicit full auto-approve (-2, 完全免审批), which
2236
+ // opts into letting high-risk commands through (intended for isolated
2237
+ // containers). Same exemption for unattended scheduled-task runs (ctx != null)
2238
+ // — those never auto-approve at any tier.
2239
+ const permComputed = computeAutoApprove('perm', _cwd);
2240
+ const permAuto = (ctx || (isPublish && permComputed.seconds !== AUTO_APPROVE_FULL))
2241
+ ? { enabled: false }
2242
+ : permComputed;
2234
2243
  const permPayload = { type: 'perm-hook-pending', id, toolName, input, cwd: _cwd, sessionId: effSessionId(), instanceKey, ...origin,
2235
2244
  autoApproveSeconds: permAuto.enabled ? permAuto.seconds : 0,
2236
2245
  ...(permAuto.enabled ? { autoApproveAt: permAuto.autoApproveAt } : {}) };
@@ -2316,8 +2325,8 @@ function _createSession(key, cwd) {
2316
2325
  };
2317
2326
  _pendingApprovals.set(id, entry);
2318
2327
  // Arm the server-side fallback AFTER the entry is in the map: instant (-1 for
2319
- // plan/perm, 0 minutes for ask hosting) fires synchronously and resolves through
2320
- // the same first-wins wrapper. Ask hosting arms its own state factory (minute
2328
+ // plan, -1/-2 for perm, 0 minutes for ask hosting) fires synchronously and resolves
2329
+ // through the same first-wins wrapper. Ask hosting arms its own state factory (minute
2321
2330
  // semantics) and resolves the pre-picked answers map; plan/perm keep the generic
2322
2331
  // auto-approve state. A null autoValue (no selectable option) never reaches here —
2323
2332
  // the ask caller passes autoMeta only when answers were actually picked, otherwise
@@ -0,0 +1,42 @@
1
+ /**
2
+ * App-level keepalive loop for /ws/terminal connections.
3
+ *
4
+ * Browsers cannot send WS control-frame pings, and a NAT/proxy can silently
5
+ * half-open this socket: the client watchdog (TerminalWsContext) uses these frames
6
+ * as its liveness signal, and without them a dead socket never fires onclose,
7
+ * freezing every push-only consumer on this channel (sdk-context-usage blood bar,
8
+ * approvals, queue state) until a page refresh.
9
+ *
10
+ * Extracted as its own module so the test seam (server-terminal-ws-ping.test.js)
11
+ * loads ONLY this helper — a full server.js import in the shared test process
12
+ * leaks module state into sibling server tests (same pattern as
13
+ * setTerminalWssForTests, which ws-instance-isolation.test.js drives the same way).
14
+ *
15
+ * Send-only on purpose: a dead connection is skipped (readyState gate) and the
16
+ * client-side watchdog owns close+reconnect, keeping the historical broadcast
17
+ * semantics (skip non-OPEN, heal on reconnect) unchanged.
18
+ */
19
+ import { reportSwallowed } from './error-report.js';
20
+
21
+ export const TERMINAL_WS_PING_MS = 25_000;
22
+
23
+ export function attachTerminalWsPing(ws, { setI = setInterval, clearI = clearInterval } = {}) {
24
+ // Send the FIRST ping immediately on connect, not after one full interval. The
25
+ // client resets its ping-seen evidence on every (re)connect; if the socket goes
26
+ // half-open during the first 25s window before any ping arrives, the watchdog
27
+ // would have no evidence and stay passive forever — a permanent freeze. An
28
+ // immediate first frame closes that window.
29
+ const sendPing = () => {
30
+ if (ws.readyState !== 1) return;
31
+ // A failed keepalive send is the server's only liveness signal for this socket —
32
+ // report it (dedup-capped per tag, so a dead socket does not flood every 25s).
33
+ try { ws.send(JSON.stringify({ type: 'ping', ts: Date.now() })); }
34
+ catch (err) { reportSwallowed('ws.terminal-ping', err); }
35
+ };
36
+ sendPing();
37
+ const pingTimer = setI(sendPing, TERMINAL_WS_PING_MS);
38
+ pingTimer.unref?.();
39
+ ws.on('close', () => clearI(pingTimer));
40
+ return pingTimer;
41
+ }
42
+
package/server/proxy.js CHANGED
@@ -333,7 +333,11 @@ async function handleLlmApiRequest(req, res, fullUrl, fetchOptions, body, proxyD
333
333
  // maxRetryDurationMs. res 'close' before the response is finished means the
334
334
  // client is gone → abort every in-flight/queued attempt via the engine.
335
335
  const clientAbort = new AbortController();
336
+ let settleSlowUpstream = () => {};
336
337
  res.on('close', () => {
338
+ // close also follows an error response ended by the outer catch. Always settle
339
+ // the advisory; only an unfinished response needs to abort upstream work.
340
+ settleSlowUpstream();
337
341
  if (!res.writableEnded) {
338
342
  try { clientAbort.abort(); } catch { /* best effort */ }
339
343
  }
@@ -375,7 +379,16 @@ async function handleLlmApiRequest(req, res, fullUrl, fetchOptions, body, proxyD
375
379
  if (slowTimer.unref) slowTimer.unref();
376
380
  }
377
381
  const clearSlowTimer = () => { if (slowTimer) { clearTimeout(slowTimer); slowTimer = null; } };
378
- clientAbort.signal.addEventListener('abort', clearSlowTimer, { once: true });
382
+ let slowResolved = false;
383
+ settleSlowUpstream = () => {
384
+ if (slowResolved) return;
385
+ slowResolved = true;
386
+ clearSlowTimer();
387
+ if (slowFired) {
388
+ __testing.emit({ type: 'resolved', requestId: slowReqId, cwd: slowCwd, instanceKey: slowInstance });
389
+ }
390
+ };
391
+ clientAbort.signal.addEventListener('abort', settleSlowUpstream, { once: true });
379
392
  // The timer measures time-to-HEADERS (fetch resolves at headers). Keep it armed
380
393
  // until the first BODY chunk so a headers-fast-then-stalled stream still counts
381
394
  // as slow (review P1-2). markFirstByte is the real settle point: it disarms the
@@ -385,10 +398,7 @@ async function handleLlmApiRequest(req, res, fullUrl, fetchOptions, body, proxyD
385
398
  const markFirstByte = () => {
386
399
  if (slowFirstByteSeen) return;
387
400
  slowFirstByteSeen = true;
388
- clearSlowTimer();
389
- if (slowFired) {
390
- __testing.emit({ type: 'resolved', requestId: slowReqId, cwd: slowCwd, instanceKey: slowInstance });
391
- }
401
+ settleSlowUpstream();
392
402
  };
393
403
 
394
404
  // 执行带重试的请求
@@ -414,10 +424,7 @@ async function handleLlmApiRequest(req, res, fullUrl, fetchOptions, body, proxyD
414
424
  // (markFirstByte). Clear+resolve only when no usable response came back
415
425
  // (network error / aborted / no response object) so the advisory never leaks.
416
426
  if (slowFirstByteSeen || !result || !result.response) {
417
- clearSlowTimer();
418
- if (slowFired) {
419
- __testing.emit({ type: 'resolved', requestId: slowReqId, cwd: slowCwd, instanceKey: slowInstance });
420
- }
427
+ settleSlowUpstream();
421
428
  }
422
429
  }
423
430
 
@@ -7,7 +7,7 @@ import { _projectName } from '../interceptor.js';
7
7
  import { readPrefsRaw } from '../lib/prefs-store.js';
8
8
  import { getCurrentProjectKey, hasFork, resolveScoped } from '../lib/project-prefs.js';
9
9
  import { reportSwallowed } from '../lib/error-report.js';
10
- import { computeAutoApprove, createAutoApproveState } from '../lib/auto-approve.js';
10
+ import { computeAutoApprove, createAutoApproveState, isAutoApproveEnabledValue, AUTO_APPROVE_FULL } from '../lib/auto-approve.js';
11
11
  import { isPublishCommand } from '../lib/approval-policy.js';
12
12
  import { computeAskAutoAnswer, createAskAutoAnswerState, pickAutoAnswers, replayAskAutoAnswerFields } from '../lib/ask-auto-answer.js';
13
13
 
@@ -537,11 +537,14 @@ function permHook(req, res, parsedUrl, isLocal, deps) {
537
537
  // itself at deadline + 1s buffer when no client did. autoCancelled is set by
538
538
  // the perm-hook-auto-cancel WS handler (the approval then stays pending for
539
539
  // a manual decision) and replayed to fresh clients.
540
- // npm publish is a hard safety floor: always wait for a human decision, never
541
- // the server-side auto-approve fallback (SDK path parity: sdk-manager.js).
542
- const autoMeta = isPublishCommand(toolName, input)
540
+ // npm publish is a hard safety floor: a human decision is required at every
541
+ // tier EXCEPT the explicit full auto-approve (-2, 完全免审批), which opts
542
+ // into letting high-risk commands through (intended for isolated
543
+ // containers). SDK path parity: sdk-manager.js.
544
+ const computedAuto = computeAutoApprove('perm', typeof cwd === 'string' && cwd ? cwd : undefined, { file: deps.getPrefsFile?.() });
545
+ const autoMeta = (isPublishCommand(toolName, input) && computedAuto.seconds !== AUTO_APPROVE_FULL)
543
546
  ? { enabled: false }
544
- : computeAutoApprove('perm', typeof cwd === 'string' && cwd ? cwd : undefined, { file: deps.getPrefsFile?.() });
547
+ : computedAuto;
545
548
 
546
549
  const hookEntry = {
547
550
  toolName, input, res, timer, createdAt: Date.now(),
@@ -566,7 +569,7 @@ function permHook(req, res, parsedUrl, isLocal, deps) {
566
569
  });
567
570
  }
568
571
 
569
- // Arm AFTER the entry is in the map AND the pending frame is out: instant (-1)
572
+ // Arm AFTER the entry is in the map AND the pending frame is out: instant (-1/-2)
570
573
  // fires synchronously and resolves through the entry, so clients observe the
571
574
  // order pending → resolved (never a ghost panel for an already-answered hook).
572
575
  if (autoMeta.enabled) {
@@ -674,13 +677,14 @@ function permRequestHook(req, res, parsedUrl, isLocal, deps) {
674
677
  const effective = scoped ? resolveScoped(prefs, prefs.prefsByProject[projectKey]) : prefs;
675
678
  const autoApproveSeconds = Number(effective.autoApproveSeconds);
676
679
 
677
- // autoApproveSeconds: 0 = off/manual, >0 = countdown, -1 = instant.
678
- // For PermissionRequest the prompt is already imminent; we only suppress it
679
- // when the user has explicitly enabled auto-approval. Both instant (-1) and
680
- // countdown (>0) are treated as allow here because the user has already
681
- // opted into automatic approval; the countdown variant simply adds a visible
682
- // delay in the UI, which is irrelevant for a headless hook.
683
- const shouldAutoAllow = autoApproveSeconds === -1 || autoApproveSeconds > 0;
680
+ // autoApproveSeconds: 0 = off/manual, >0 = countdown, -1 = instant, -2 =
681
+ // full auto-approve. For PermissionRequest the prompt is already imminent;
682
+ // we only suppress it when the user has explicitly enabled auto-approval.
683
+ // Both instant tiers (-1/-2) and countdown (>0) are treated as allow here
684
+ // because the user has already opted into automatic approval; the countdown
685
+ // variant simply adds a visible delay in the UI, which is irrelevant for a
686
+ // headless hook.
687
+ const shouldAutoAllow = isAutoApproveEnabledValue(autoApproveSeconds);
684
688
 
685
689
  res.writeHead(200, { 'Content-Type': 'application/json' });
686
690
  res.end(JSON.stringify({ decision: shouldAutoAllow ? 'allow' : 'ask' }));
@@ -10,6 +10,7 @@ import { loadWorkspaces } from '../workspace-registry.js';
10
10
  import { listLivePtys } from '../pty-manager.js';
11
11
  import { reportSwallowed } from '../lib/error-report.js';
12
12
  import { isBinaryBuffer, getUtf16Encoding } from '../lib/binary-sniff.js';
13
+ import { AUDIO_EXTENSIONS, audioExtOf, serveAudioStream } from '../lib/audio-stream.js';
13
14
  import { discoverClaudeMdCandidates, readCandidateById } from '../lib/claude-md-discovery.js';
14
15
  import { getClaudeConfigDir } from '../../findcc.js';
15
16
  import { _projectName } from '../interceptor.js';
@@ -47,6 +48,8 @@ const FILE_RAW_MIME = {
47
48
  '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
48
49
  '.gif': 'image/gif', '.svg': 'image/svg+xml', '.ico': 'image/x-icon',
49
50
  '.webp': 'image/webp', '.bmp': 'image/bmp', '.avif': 'image/avif',
51
+ '.apng': 'image/apng', '.jfif': 'image/jpeg',
52
+ '.tif': 'image/tiff', '.tiff': 'image/tiff', '.heic': 'image/heic', '.heif': 'image/heif',
50
53
  '.html': 'text/html', '.htm': 'text/html',
51
54
  '.css': 'text/css', '.js': 'text/javascript', '.mjs': 'text/javascript',
52
55
  '.json': 'application/json', '.map': 'application/json', '.txt': 'text/plain',
@@ -871,6 +874,67 @@ function targetFiles(req, res, parsedUrl, isLocal, deps) {
871
874
  }
872
875
  }
873
876
 
877
+ // Audio preview endpoint: streams audio with single-range 206/416/304 support so
878
+ // browsers (esp. Safari, which probes with Range: bytes=0-1) can seek. Unlike fileRaw
879
+ // it never buffers the whole file (multi-GB audio), and unlike fileDownload it serves
880
+ // inline with a real audio/* MIME. Shares the same permission/path contract as fileDownload.
881
+ function audioStream(req, res, parsedUrl) {
882
+ try {
883
+ const reqPath = parsedUrl.searchParams.get('path');
884
+ if (!reqPath) {
885
+ res.writeHead(400, { 'Content-Type': 'application/json' });
886
+ res.end(JSON.stringify({ error: 'Invalid path' }));
887
+ return;
888
+ }
889
+ // Same path contract as fileDownloadWithRoot: relative paths with .. are rejected.
890
+ const isAbs = /^([a-zA-Z]:[\\/]|[\\/])/.test(reqPath);
891
+ if (!isAbs && reqPath.includes('..')) {
892
+ res.writeHead(400, { 'Content-Type': 'application/json' });
893
+ res.end(JSON.stringify({ error: 'Invalid path' }));
894
+ return;
895
+ }
896
+ const cwd = _viewRootOrReply(req, res, parsedUrl);
897
+ if (!cwd) return;
898
+ const absPath = isAbs ? reqPath : resolve(cwd, reqPath);
899
+ const policy = isReadAllowed(absPath);
900
+ if (!policy.ok) {
901
+ const status = reasonToStatus(policy.reason);
902
+ const errLabel = status === 404 ? 'File not found'
903
+ : status === 400 ? 'Invalid path'
904
+ : 'Forbidden';
905
+ const body = { error: errLabel, reason: policy.reason };
906
+ if (policy.allowedRoots) body.allowedRoots = policy.allowedRoots;
907
+ res.writeHead(status, { 'Content-Type': 'application/json' });
908
+ res.end(JSON.stringify(body));
909
+ return;
910
+ }
911
+ const targetFile = policy.real;
912
+ const stat = statSync(targetFile);
913
+ if (!stat.isFile()) {
914
+ res.writeHead(400, { 'Content-Type': 'application/json' });
915
+ res.end(JSON.stringify({ error: 'Not a file' }));
916
+ return;
917
+ }
918
+ // Extension is derived from the real path (not the caller's name) so case and
919
+ // symlink-renamed files classify consistently; reject non-audio before sniffing.
920
+ const ext = audioExtOf(targetFile);
921
+ if (!AUDIO_EXTENSIONS.has(ext)) {
922
+ res.writeHead(400, { 'Content-Type': 'application/json' });
923
+ res.end(JSON.stringify({ error: 'Unsupported audio path' }));
924
+ return;
925
+ }
926
+ serveAudioStream(req, res, { filePath: targetFile, stat, ext });
927
+ } catch (err) {
928
+ // A throw here (EACCES stat race, null-byte path, sniff read error) must not
929
+ // become an unhandled rejection that kills the process (server.js:985).
930
+ if (res.headersSent) { reportSwallowed('audioStream.headersSent', err); res.destroy(); return; }
931
+ const status = ERROR_STATUS_MAP[err.code] || 500;
932
+ const message = status === 500 ? `Cannot read file: ${err.message}` : err.message;
933
+ res.writeHead(status, { 'Content-Type': 'application/json' });
934
+ res.end(JSON.stringify({ error: message }));
935
+ }
936
+ }
937
+
874
938
  export const filesContentRoutes = [
875
939
  { method: 'GET', match: 'exact', path: '/api/plan-file', handler: planFile },
876
940
  { method: 'GET', match: 'exact', path: '/api/file-content', handler: fileContentGet },
@@ -879,6 +943,7 @@ export const filesContentRoutes = [
879
943
  { predicate: (url, method) => (url === '/api/file-raw' || url.startsWith('/api/file-raw/')) && (method === 'GET' || method === 'HEAD'), handler: fileRaw },
880
944
  { predicate: (url, method) => url === '/api/archive-raw' && (method === 'GET' || method === 'HEAD'), handler: archiveRaw },
881
945
  { predicate: (url, method) => url === '/api/download-file' && (method === 'GET' || method === 'HEAD'), handler: fileDownload },
946
+ { predicate: (url, method) => url === '/api/audio-stream' && (method === 'GET' || method === 'HEAD'), handler: audioStream },
882
947
  { method: 'POST', match: 'exact', path: '/api/file-content', handler: fileContentPost },
883
948
  { method: 'GET', match: 'exact', path: '/api/target-files', handler: targetFiles },
884
949
  ];