dsh-annotate-upper 0.0.0-stage → 0.1.15-fork.1

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.
package/lib/index.js ADDED
@@ -0,0 +1,1277 @@
1
+ /**
2
+ * dsh-annotate — Host half.
3
+ *
4
+ * Three jobs in service of one promise: open the sidebar, pick a local web
5
+ * server that is already running, annotate it, send the comments.
6
+ *
7
+ * 1. `detect` — find loopback web servers that are really listening and
8
+ * answering, with their page titles, plus a hint on how to start one when
9
+ * nothing is up.
10
+ * 2. A **loopback preview origin**: one ephemeral server per session/app, on
11
+ * `localhost` or `127.0.0.1` with a hostname different from the harness.
12
+ * The browser sees the app's own paths, so root-absolute scripts, styles and
13
+ * SPA routes work with no prefix, while the preview's DOM and web storage
14
+ * stay isolated from the harness. A shim and the overlay are injected into
15
+ * every HTML document, WebSocket upgrades are relayed per target, and
16
+ * cookies are namespaced and partitioned.
17
+ * 3. Optional process control for people who prefer the plugin to start the
18
+ * server (`command` / `port` / `base`).
19
+ *
20
+ * The client reaches all of it at `POST /__dsh-annotate/api`.
21
+ */
22
+
23
+ import http from 'node:http'
24
+ import https from 'node:https'
25
+ import { randomUUID } from 'node:crypto'
26
+ import { execFile } from 'node:child_process'
27
+ import { readFileSync, realpathSync, statSync } from 'node:fs'
28
+ import { readFile, readdir, realpath, stat } from 'node:fs/promises'
29
+ import { basename, dirname, extname, isAbsolute, join, resolve, sep } from 'node:path'
30
+ import { fileURLToPath, pathToFileURL } from 'node:url'
31
+
32
+ export const name = 'dsh-annotate'
33
+
34
+ export const inject = ['webServer', 'subprocess', 'timer']
35
+
36
+ const ROUTE = '/__dsh-annotate'
37
+ const DEFAULT_PORT = 5180
38
+ const DEFAULT_BASE = '/app'
39
+ const DEFAULT_COMMAND = 'npm run dev:panel'
40
+ const WS_RELAY_PATH = '/__dsh_anno_ws'
41
+ const LOG_LIMIT = 400
42
+ const PREVIEW_IDLE_MS = 24 * 60 * 60_000
43
+
44
+ /** Ports people actually run dev servers on, probed even when the OS tells us
45
+ * nothing (no lsof, locked-down container). */
46
+ const COMMON_PORTS = [5173, 3000, 4173, 5180, 8080, 8000, 5000, 5500, 9000, 3001, 1234, 4200, 4321, 5174, 6006, 7000, 8001, 8888]
47
+
48
+ /** COMMON_PORTS is a preference order, not a list of answers: anything absent
49
+ * from it ranks last and then by port number. */
50
+ const commonRank = (port) => {
51
+ const index = COMMON_PORTS.indexOf(port)
52
+ return index === -1 ? COMMON_PORTS.length : index
53
+ }
54
+
55
+ /** Where a built or hand-written page lives, relative to the session workspace,
56
+ * in the order they are offered. A static page needs no dev server at all. */
57
+ const STATIC_DIRS = ['', 'dist', 'build', 'out', 'public']
58
+ const STATIC_PAGE_LIMIT = 24
59
+ /** Bound on one static response, so a stray large file cannot be buffered into
60
+ * the proxy's memory. */
61
+ const STATIC_FILE_LIMIT = 64 * 1024 * 1024
62
+ const STATIC_MIME = {
63
+ '.html': 'text/html; charset=utf-8',
64
+ '.htm': 'text/html; charset=utf-8',
65
+ '.js': 'text/javascript; charset=utf-8',
66
+ '.mjs': 'text/javascript; charset=utf-8',
67
+ '.css': 'text/css; charset=utf-8',
68
+ '.json': 'application/json; charset=utf-8',
69
+ '.map': 'application/json; charset=utf-8',
70
+ '.txt': 'text/plain; charset=utf-8',
71
+ '.csv': 'text/csv; charset=utf-8',
72
+ '.xml': 'application/xml; charset=utf-8',
73
+ '.svg': 'image/svg+xml',
74
+ '.png': 'image/png',
75
+ '.jpg': 'image/jpeg',
76
+ '.jpeg': 'image/jpeg',
77
+ '.gif': 'image/gif',
78
+ '.webp': 'image/webp',
79
+ '.avif': 'image/avif',
80
+ '.ico': 'image/x-icon',
81
+ '.woff': 'font/woff',
82
+ '.woff2': 'font/woff2',
83
+ '.ttf': 'font/ttf',
84
+ '.otf': 'font/otf',
85
+ '.wasm': 'application/wasm',
86
+ '.pdf': 'application/pdf',
87
+ '.mp4': 'video/mp4',
88
+ '.webm': 'video/webm',
89
+ }
90
+ const staticMime = (file) => STATIC_MIME[extname(file).toLowerCase()] || 'application/octet-stream'
91
+ const isHtmlFile = (file) => /\.html?$/i.test(file)
92
+
93
+ /** Both paths are absolute and already resolved, so a prefix test is exact. */
94
+ function insideRoot(target, root) {
95
+ if (!target || !root) return false
96
+ if (target === root) return true
97
+ return target.startsWith(root.endsWith(sep) ? root : root + sep)
98
+ }
99
+
100
+ /** Dot segments are VCS metadata, environment files and editor state; none of
101
+ * them belong in a preview, and `..` fails this test too. */
102
+ const hasHiddenSegment = (pathname) => pathname.split('/').some((part) => part.startsWith('.'))
103
+
104
+ const HOP_BY_HOP = new Set([
105
+ 'connection',
106
+ 'keep-alive',
107
+ 'proxy-authenticate',
108
+ 'proxy-authorization',
109
+ 'te',
110
+ 'trailer',
111
+ 'transfer-encoding',
112
+ ])
113
+
114
+ /** Headers that would stop a proxied page from being framed or injected. */
115
+ const UNFRAMEABLE = new Set([
116
+ 'x-frame-options',
117
+ 'content-security-policy',
118
+ 'content-security-policy-report-only',
119
+ 'cross-origin-opener-policy',
120
+ 'cross-origin-embedder-policy',
121
+ 'cross-origin-resource-policy',
122
+ ])
123
+
124
+ /** The page shim, shipped next to this file and inlined into every proxied
125
+ * HTML document. Loaded once; a missing file degrades to no shim. */
126
+ const SHIM_SRC = (() => {
127
+ try {
128
+ return readFileSync(new URL('./shim.js', import.meta.url), 'utf8')
129
+ } catch (error) {
130
+ console.warn('dsh-annotate: page shim unavailable —', String((error && error.message) || error))
131
+ return ''
132
+ }
133
+ })()
134
+
135
+ const OVERLAY_SRC = (() => {
136
+ try {
137
+ return readFileSync(new URL('./overlay.js', import.meta.url), 'utf8')
138
+ } catch (error) {
139
+ console.warn('dsh-annotate: overlay unavailable —', String((error && error.message) || error))
140
+ return ''
141
+ }
142
+ })()
143
+ const escapeHtml = (value) => String(value).replace(/[&<>"']/g, (char) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[char]))
144
+ function isLocalTarget(url) {
145
+ return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password &&
146
+ ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)
147
+ }
148
+
149
+ const encodeTarget = (origin) => Buffer.from(origin, 'utf8').toString('base64url')
150
+ const decodeTarget = (value) => Buffer.from(String(value), 'base64url').toString('utf8')
151
+
152
+ /** `127.0.0.1:3099` -> 3099, `[::1]:3099` -> 3099, `localhost` -> 0.
153
+ * `String(host).split(':')[1]` is wrong for bracketed IPv6 literals. */
154
+ function hostPort(host) {
155
+ const text = String(host || '')
156
+ const close = text.lastIndexOf(']')
157
+ const colon = text.lastIndexOf(':')
158
+ if (colon === -1 || (close !== -1 && colon < close)) return 0
159
+ const value = Number(text.slice(colon + 1))
160
+ return Number.isInteger(value) && value > 0 && value < 65536 ? value : 0
161
+ }
162
+
163
+ /** The origin the browser actually used for this request. Behind a
164
+ * TLS-terminating reverse proxy the socket is plain http, so an explicit
165
+ * forwarded scheme wins over the socket. */
166
+ function requestOrigin(req) {
167
+ const forwarded = String(req.headers['x-forwarded-proto'] || '').split(',')[0].trim()
168
+ const scheme = forwarded === 'https' || forwarded === 'http' ? forwarded : req.socket.encrypted ? 'https' : 'http'
169
+ return `${scheme}://${req.headers.host}`
170
+ }
171
+
172
+ const originOf = (value) => {
173
+ try {
174
+ const url = new URL(value)
175
+ return url.protocol === 'dsh-app:' && url.host === 'app' && !url.username && !url.password ? 'dsh-app://app' : url.origin
176
+ } catch (error) {
177
+ void error
178
+ return null
179
+ }
180
+ }
181
+
182
+ function clearFrameKey(url) {
183
+ if (!url.searchParams.has('__dsh_anno_key')) return
184
+ // URLSearchParams.delete/set would normalize every other query value too,
185
+ // changing full-URL annotation identities and signed application URLs.
186
+ url.search = url.search.slice(1).split('&').filter((part) => !new URLSearchParams(part).has('__dsh_anno_key')).join('&')
187
+ }
188
+
189
+ function addFrameKey(url, key) {
190
+ clearFrameKey(url)
191
+ url.search += (url.search ? '&' : '?') + '__dsh_anno_key=' + encodeURIComponent(key)
192
+ }
193
+
194
+ /** A preview server must never become a readable gateway for an unrelated page.
195
+ * Chromium sends fetch metadata; Firefox and Safari send none, so fall back to
196
+ * the browser's own Origin/Referer. */
197
+ function allowedPreviewRequest(req, parentOrigin, previewOrigin) {
198
+ const parents = [parentOrigin, previewOrigin]
199
+ const fetchSite = req.headers['sec-fetch-site']
200
+ const fetchDest = req.headers['sec-fetch-dest']
201
+ if (fetchSite === 'cross-site' && fetchDest !== 'iframe') return false
202
+ // A framed load can legitimately be cross-site (the harness may be on
203
+ // 127.0.0.1 while the preview is on localhost), so it must name its parent.
204
+ if (fetchDest === 'iframe' || fetchSite === 'cross-site') return parents.includes(originOf(req.headers.referer))
205
+ if (fetchSite) return true
206
+ // Browsers that send no fetch metadata still send Origin (for any readable
207
+ // cross-origin request) or Referer. A page from anywhere else is rejected;
208
+ // a request with no provenance at all is local tooling (curl, a test, a
209
+ // health check), which cannot be told apart from a navigation and is allowed.
210
+ const declared = originOf(req.headers.origin) || originOf(req.headers.referer)
211
+ return declared === null || parents.includes(declared)
212
+ }
213
+
214
+ function normalizeBase(value) {
215
+ const raw = String(value === undefined || value === null ? DEFAULT_BASE : value).trim()
216
+ if (!raw || raw === '/') return '/'
217
+ const withLead = raw.startsWith('/') ? raw : '/' + raw
218
+ return withLead.endsWith('/') ? withLead : withLead + '/'
219
+ }
220
+
221
+ /** Process control is off unless a command is configured; when it is on, the
222
+ * only working directory accepted is an existing absolute directory. */
223
+ function existingDirectory(root) {
224
+ if (typeof root !== 'string' || !root || !isAbsolute(root)) return null
225
+ try {
226
+ const real = realpathSync(root)
227
+ return statSync(real).isDirectory() ? real : null
228
+ } catch (error) {
229
+ void error
230
+ return null
231
+ }
232
+ }
233
+
234
+ function resolveCommand(config) {
235
+ if (Array.isArray(config.argv) && config.argv.length > 0) return config.argv.map(String)
236
+ const text = String(config.command === undefined ? DEFAULT_COMMAND : config.command).trim()
237
+ return text.split(/\s+/).filter(Boolean)
238
+ }
239
+
240
+ function readJson(req, limit = 1_000_000) {
241
+ return new Promise((resolve, reject) => {
242
+ let raw = ''
243
+ req.on('data', (chunk) => {
244
+ raw += chunk
245
+ if (raw.length > limit) {
246
+ reject(new Error('request too large'))
247
+ req.destroy()
248
+ }
249
+ })
250
+ req.on('end', () => {
251
+ try {
252
+ resolve(raw ? JSON.parse(raw) : {})
253
+ } catch (error) {
254
+ reject(error)
255
+ }
256
+ })
257
+ req.on('error', reject)
258
+ })
259
+ }
260
+
261
+ function send(res, status, value) {
262
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
263
+ res.end(JSON.stringify(value))
264
+ }
265
+
266
+ /** Run a one-shot command, never throwing. */
267
+ function run(file, args, timeout = 4000) {
268
+ return new Promise((resolve) => {
269
+ execFile(file, args, { timeout, encoding: 'utf8', maxBuffer: 4_000_000 }, (error, stdout) => {
270
+ resolve(error && !stdout ? '' : String(stdout || ''))
271
+ })
272
+ })
273
+ }
274
+
275
+ /** Loopback TCP listeners, three ways, none of them required. When the tool
276
+ * knows the owning process, so does the caller: `pids` is what lets a service
277
+ * be claimed by the workspace it was started from. */
278
+ async function listeningPorts() {
279
+ const ports = new Set()
280
+ const pids = new Map()
281
+
282
+ // Linux: /proc needs no process spawn, but names no owner either.
283
+ for (const file of ['/proc/net/tcp', '/proc/net/tcp6']) {
284
+ try {
285
+ const text = await readFile(file, 'utf8')
286
+ for (const line of text.split('\n').slice(1)) {
287
+ const parts = line.trim().split(/\s+/)
288
+ if (parts.length < 4 || parts[3] !== '0A') continue // 0A = LISTEN
289
+ const port = parseInt(parts[1].split(':')[1], 16)
290
+ if (port > 0) ports.add(port)
291
+ }
292
+ } catch (error) {
293
+ void error
294
+ }
295
+ }
296
+
297
+ // macOS/BSD: lsof knows the addresses, so loopback-only is decidable, and it
298
+ // is also the only source of the owning PID on either platform.
299
+ const lsof = await run('lsof', ['-nP', '-iTCP', '-sTCP:LISTEN'])
300
+ for (const line of lsof.split('\n')) {
301
+ if (!/LISTEN/.test(line)) continue
302
+ const match = line.match(/(?:127\.0\.0\.1|\*|\[::1\]|localhost):(\d+)/)
303
+ if (!match) continue
304
+ const port = Number(match[1])
305
+ ports.add(port)
306
+ const owner = Number(line.trim().split(/\s+/)[1])
307
+ if (Number.isInteger(owner) && owner > 0) pids.set(port, owner)
308
+ }
309
+
310
+ // Anything else: netstat is ubiquitous.
311
+ if (ports.size === 0) {
312
+ const netstat = await run('netstat', ['-an'])
313
+ for (const line of netstat.split('\n')) {
314
+ if (!/LISTEN/.test(line)) continue
315
+ const match = line.match(/[.:](\d+)\s/)
316
+ if (match) ports.add(Number(match[1]))
317
+ }
318
+ }
319
+
320
+ return { ports: [...ports].filter((value) => Number.isInteger(value) && value > 0 && value < 65536), pids }
321
+ }
322
+
323
+ function titleOf(html) {
324
+ const match = html.match(/<title[^>]*>([\s\S]{0,200}?)<\/title>/i)
325
+ return match ? match[1].replace(/\s+/g, ' ').trim() : ''
326
+ }
327
+
328
+ async function probePort(value, timeoutMs) {
329
+ for (const hostname of ['127.0.0.1', '[::1]']) {
330
+ try {
331
+ const res = await fetch(`http://${hostname}:${value}/`, {
332
+ redirect: 'manual', signal: AbortSignal.timeout(timeoutMs),
333
+ headers: { accept: 'text/html,application/xhtml+xml' },
334
+ })
335
+ const type = String(res.headers.get('content-type') || '')
336
+ if (res.status >= 400 || (type && !type.includes('html'))) { await res.body?.cancel(); continue }
337
+ const html = type.includes('html') ? (await res.text()).slice(0, 120_000) : ''
338
+ if (!type) await res.body?.cancel()
339
+ return { port: value, url: `http://${hostname}:${value}/`, href: res.url,
340
+ title: titleOf(html) || `${hostname}:${value}`, status: res.status }
341
+ } catch { /* Try IPv6 when a dev server listens only on ::1. */ }
342
+ }
343
+ return null
344
+ }
345
+
346
+ /** Where each listening process was started. `/proc` answers without a spawn;
347
+ * lsof covers macOS and BSD. No answer only means the service cannot be
348
+ * claimed by a workspace — never that it is unusable. */
349
+ async function processCwds(pids) {
350
+ const cwds = new Map()
351
+ const rest = []
352
+ for (const pid of pids) {
353
+ try {
354
+ cwds.set(pid, realpathSync(`/proc/${pid}/cwd`))
355
+ } catch (error) {
356
+ void error
357
+ rest.push(pid)
358
+ }
359
+ }
360
+ if (rest.length) {
361
+ const text = await run('lsof', ['-a', '-p', rest.join(','), '-d', 'cwd', '-Fn'])
362
+ let pid = 0
363
+ for (const line of text.split('\n')) {
364
+ if (line.startsWith('p')) pid = Number(line.slice(1))
365
+ else if (line.startsWith('n') && pid) cwds.set(pid, line.slice(1))
366
+ }
367
+ }
368
+ return cwds
369
+ }
370
+
371
+ /** Ports the workspace asks for itself — `--port 5180` in a script, `port:` in
372
+ * a Vite config. A hint only: the port still has to be listening to appear. */
373
+ async function declaredProjectPorts(root) {
374
+ const declared = new Set()
375
+ if (!root) return declared
376
+ const sources = []
377
+ try {
378
+ sources.push(await readFile(join(root, 'package.json'), 'utf8'))
379
+ } catch (error) {
380
+ void error
381
+ }
382
+ for (const name of ['vite.config.ts', 'vite.config.js', 'vite.config.mts', 'vite.config.mjs', 'vite.config.cts', 'vite.config.cjs']) {
383
+ try {
384
+ sources.push(await readFile(join(root, name), 'utf8'))
385
+ } catch (error) {
386
+ void error
387
+ }
388
+ }
389
+ for (const text of sources) {
390
+ for (const [, value] of text.matchAll(/--port[=\s]+(\d{2,5})/g)) declared.add(Number(value))
391
+ for (const [, value] of text.matchAll(/\bPORT\s*[:=]\s*['"]?(\d{2,5})/g)) declared.add(Number(value))
392
+ for (const [, value] of text.matchAll(/\bport\s*:\s*(\d{2,5})/g)) declared.add(Number(value))
393
+ }
394
+ return declared
395
+ }
396
+
397
+ /** HTML pages the workspace already contains, so a project that needs no server
398
+ * — or whose server is not running — can still be annotated. */
399
+ async function staticCandidates(root) {
400
+ const pages = []
401
+ if (!root) return pages
402
+ const seen = new Set()
403
+ for (const dir of STATIC_DIRS) {
404
+ const base = dir ? join(root, dir) : root
405
+ let entries
406
+ try {
407
+ entries = await readdir(base, { withFileTypes: true })
408
+ } catch (error) {
409
+ void error
410
+ continue
411
+ }
412
+ const names = entries.filter((entry) => entry.isFile() && isHtmlFile(entry.name)).map((entry) => entry.name)
413
+ names.sort((a, b) => (a.toLowerCase() === 'index.html' ? 0 : 1) - (b.toLowerCase() === 'index.html' ? 0 : 1) || a.localeCompare(b))
414
+ for (const name of names) {
415
+ if (pages.length >= STATIC_PAGE_LIMIT) return pages
416
+ let real
417
+ try {
418
+ real = await realpath(join(base, name))
419
+ } catch (error) {
420
+ void error
421
+ continue
422
+ }
423
+ if (seen.has(real)) continue
424
+ seen.add(real)
425
+ pages.push({ rel: dir ? `${dir}/${name}` : name, path: real })
426
+ }
427
+ }
428
+ return pages
429
+ }
430
+
431
+ /** The file a static request resolves to: inside the root, a regular file, and
432
+ * never a directory. Symlinks are resolved before the containment test. */
433
+ async function existingFile(file, root) {
434
+ let real
435
+ try {
436
+ real = await realpath(file)
437
+ } catch (error) {
438
+ void error
439
+ return null
440
+ }
441
+ if (!insideRoot(real, root)) return null
442
+ try {
443
+ const info = await stat(real)
444
+ if (!info.isFile()) return null
445
+ return { path: real, size: info.size }
446
+ } catch (error) {
447
+ void error
448
+ return null
449
+ }
450
+ }
451
+
452
+ /** Read-only file server for one directory: the loopback origin a static page
453
+ * needs before the preview proxy can read and inject into it. */
454
+ async function serveStatic(req, res, root) {
455
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
456
+ res.writeHead(405, { allow: 'GET, HEAD' })
457
+ res.end()
458
+ return
459
+ }
460
+ let pathname
461
+ try {
462
+ pathname = decodeURIComponent(new URL(req.url, 'http://127.0.0.1').pathname)
463
+ } catch (error) {
464
+ void error
465
+ res.writeHead(400)
466
+ res.end()
467
+ return
468
+ }
469
+ if (hasHiddenSegment(pathname)) {
470
+ res.writeHead(403)
471
+ res.end()
472
+ return
473
+ }
474
+ const requested = resolve(root, '.' + (pathname.charAt(0) === '/' ? pathname : '/' + pathname))
475
+ if (!insideRoot(requested, root)) {
476
+ res.writeHead(403)
477
+ res.end()
478
+ return
479
+ }
480
+ // The file itself, then a directory's index, then — for a client-side route
481
+ // with no extension — the root page, which is what keeps an SPA navigable.
482
+ let target = await existingFile(requested, root)
483
+ if (!target) target = await existingFile(join(requested, 'index.html'), root)
484
+ if (!target && !extname(pathname) && String(req.headers.accept || '').includes('html')) {
485
+ target = await existingFile(join(root, 'index.html'), root)
486
+ }
487
+ if (!target) {
488
+ res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
489
+ res.end('not found')
490
+ return
491
+ }
492
+ if (target.size > STATIC_FILE_LIMIT) {
493
+ res.writeHead(413, { 'content-type': 'text/plain; charset=utf-8' })
494
+ res.end('file too large for a preview')
495
+ return
496
+ }
497
+ res.writeHead(200, {
498
+ 'content-type': staticMime(target.path),
499
+ 'content-length': String(target.size),
500
+ 'cache-control': 'no-store',
501
+ })
502
+ if (req.method === 'HEAD') {
503
+ res.end()
504
+ return
505
+ }
506
+ res.end(await readFile(target.path))
507
+ }
508
+
509
+ /** A `file://` target (or a plain local path) is previewable when it is an HTML
510
+ * file. Any local page the user explicitly points at is allowed, so a page kept
511
+ * outside the session workspace can still be annotated; relative scripts and
512
+ * styles resolve from its own directory. */
513
+ function resolveFileTarget(raw, root) {
514
+ void root
515
+ const text = String(raw || '').trim()
516
+ if (!text) return { code: 'notLocalTarget' }
517
+ let path
518
+ if (/^file:/i.test(text)) {
519
+ let url
520
+ try {
521
+ url = new URL(text)
522
+ } catch (error) {
523
+ void error
524
+ return { code: 'notLocalTarget' }
525
+ }
526
+ if (url.host) {
527
+ // UNC share: file://server/share/a.html → \\server\share\a.html
528
+ path = '\\\\' + url.host + decodeURIComponent(url.pathname).replace(/\//g, '\\')
529
+ } else {
530
+ try {
531
+ path = fileURLToPath(url)
532
+ } catch (error) {
533
+ void error
534
+ return { code: 'staticUnavailable' }
535
+ }
536
+ }
537
+ } else {
538
+ // A plain filesystem path: Windows drive, UNC or POSIX absolute.
539
+ path = text
540
+ }
541
+ let real
542
+ try {
543
+ real = realpathSync(path)
544
+ } catch (error) {
545
+ void error
546
+ return { code: 'staticUnavailable' }
547
+ }
548
+ let info
549
+ try {
550
+ info = statSync(real)
551
+ } catch (error) {
552
+ void error
553
+ return { code: 'staticUnavailable' }
554
+ }
555
+ if (!info.isFile()) return { code: 'staticUnavailable' }
556
+ if (!isHtmlFile(real)) return { code: 'notHtmlFile' }
557
+ return { dir: dirname(real), name: basename(real), path: real }
558
+ }
559
+
560
+ /** How to start something, read from the session workspace. */
561
+ async function startupHint(root) {
562
+ if (!root) return null
563
+ try {
564
+ const pkg = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'))
565
+ const scripts = pkg && typeof pkg.scripts === 'object' && pkg.scripts ? Object.keys(pkg.scripts) : []
566
+ const wanted = ['dev', 'start', 'dev:panel', 'serve', 'preview']
567
+ const picked = wanted.filter((name) => scripts.includes(name))
568
+ if (picked.length === 0) return { runner: null, commands: [] }
569
+ let runner = 'npm'
570
+ let build = (name) => (name === 'start' ? 'npm start' : `npm run ${name}`)
571
+ for (const [file, name, make] of [
572
+ ['pnpm-lock.yaml', 'pnpm', (s) => (s === 'dev' ? 'pnpm dev' : s === 'start' ? 'pnpm start' : `pnpm run ${s}`)],
573
+ ['yarn.lock', 'yarn', (s) => `yarn ${s}`],
574
+ ['bun.lockb', 'bun', (s) => `bun run ${s}`],
575
+ ['bun.lock', 'bun', (s) => `bun run ${s}`],
576
+ ]) {
577
+ try {
578
+ await readFile(join(root, file))
579
+ runner = name
580
+ build = make
581
+ break
582
+ } catch (error) {
583
+ void error
584
+ }
585
+ }
586
+ return { runner, commands: picked.map((name) => ({ script: name, command: build(name) })) }
587
+ } catch (error) {
588
+ void error
589
+ return null
590
+ }
591
+ }
592
+
593
+ export function apply(ctx, config = {}) {
594
+ // ---- optional process control (off unless configured) --------------------
595
+ const configuredCommand = config.command !== undefined || Array.isArray(config.argv)
596
+ const port = Number(config.port) || DEFAULT_PORT
597
+ const base = normalizeBase(config.base)
598
+ const argv = resolveCommand(config)
599
+ const command = argv.join(' ')
600
+ const previewUrl = `http://127.0.0.1:${port}${base}`
601
+ const readyTimeoutMs = Number(config.readyTimeoutMs) || 45_000
602
+ const runs = new Map()
603
+
604
+ // ---- proxy ---------------------------------------------------------------
605
+ const probeTimeoutMs = Number(config.detect?.probeTimeoutMs) || 300
606
+ const detectCacheMs = Number(config.detect?.cacheMs) || 60_000
607
+ const extraPorts = Array.isArray(config.detect?.extraPorts) ? config.detect.extraPorts.map(Number) : []
608
+ const staticPorts = config.detect?.staticPorts === false ? [] : COMMON_PORTS
609
+ const staticFiles = config.detect?.staticFiles === true
610
+ const detections = new Map()
611
+ const previews = new Map()
612
+ const previewActivity = new Map()
613
+ const staticServers = new Map()
614
+ let disposed = false
615
+
616
+ const closeUnusedStatic = (dir) => {
617
+ if (!dir || [...previewActivity.values()].some((entry) => entry.dir === dir)) return
618
+ const promise = staticServers.get(dir)
619
+ staticServers.delete(dir)
620
+ if (promise) void promise.then((entry) => entry.close()).catch(() => {})
621
+ }
622
+ const closePreview = (key) => {
623
+ const promise = previews.get(key)
624
+ const activity = previewActivity.get(key)
625
+ previews.delete(key)
626
+ previewActivity.delete(key)
627
+ if (promise) void promise.then((entry) => entry.close()).catch(() => {})
628
+ closeUnusedStatic(activity?.dir)
629
+ }
630
+ const reapPreviews = () => {
631
+ const now = Date.now()
632
+ for (const [key, activity] of previewActivity) {
633
+ for (const [lease, until] of activity.leases) {
634
+ if (until <= now) activity.leases.delete(lease)
635
+ }
636
+ if (!activity.leases.size && now - activity.at >= PREVIEW_IDLE_MS) closePreview(key)
637
+ }
638
+ }
639
+ ctx.effect(() => {
640
+ const timer = setInterval(reapPreviews, 30_000)
641
+ timer.unref?.()
642
+ return () => {
643
+ disposed = true
644
+ clearInterval(timer)
645
+ for (const key of previews.keys()) closePreview(key)
646
+ for (const dir of staticServers.keys()) closeUnusedStatic(dir)
647
+ }
648
+ })
649
+
650
+ /** One read-only file server per directory, started the first time a page in
651
+ * it is previewed. It exists so a static file has a loopback origin for the
652
+ * proxy to read: an iframe cannot be injected through `file://`. */
653
+ const staticServer = async (dir) => {
654
+ let promise = staticServers.get(dir)
655
+ if (!promise) {
656
+ promise = (async () => {
657
+ const server = http.createServer((req, res) => {
658
+ // Only the exact address this server bound may read it, so a
659
+ // DNS-rebinding page cannot reach the workspace through this origin.
660
+ if (req.headers.host !== `127.0.0.1:${server.address().port}`) { res.writeHead(403); res.end(); return }
661
+ void serveStatic(req, res, dir).catch((error) => {
662
+ void error
663
+ try { res.destroy() } catch (inner) { void inner }
664
+ })
665
+ })
666
+ const sockets = new Set()
667
+ server.on('connection', (socket) => { sockets.add(socket); socket.once('close', () => sockets.delete(socket)) })
668
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve) })
669
+ const entry = { origin: `http://127.0.0.1:${server.address().port}`, close() { for (const socket of sockets) socket.destroy(); server.close() } }
670
+ if (disposed) entry.close()
671
+ return entry
672
+ })()
673
+ staticServers.set(dir, promise)
674
+ promise.catch(() => { if (staticServers.get(dir) === promise) staticServers.delete(dir) })
675
+ }
676
+ return promise
677
+ }
678
+
679
+ const entryFor = (sid) => {
680
+ const key = sid || '__root__'
681
+ let entry = runs.get(key)
682
+ if (!entry) {
683
+ entry = { sid: key, handle: null, log: [], offsetOut: 0, offsetErr: 0, exited: true, exitCode: null, root: null, starting: false }
684
+ runs.set(key, entry)
685
+ }
686
+ return entry
687
+ }
688
+
689
+ const drain = (entry) => {
690
+ if (!entry.handle) return
691
+ try {
692
+ const out = entry.handle.collected.stdout
693
+ const err = entry.handle.collected.stderr
694
+ if (out) {
695
+ const read = out.readFrom(entry.offsetOut)
696
+ entry.offsetOut = read.nextOffset
697
+ if (read.text) entry.log.push(...read.text.split(/\r?\n/).filter((line) => line.trim() !== ''))
698
+ }
699
+ if (err) {
700
+ const read = err.readFrom(entry.offsetErr)
701
+ entry.offsetErr = read.nextOffset
702
+ if (read.text) entry.log.push(...read.text.split(/\r?\n/).filter((line) => line.trim() !== ''))
703
+ }
704
+ if (entry.log.length > LOG_LIMIT) entry.log.splice(0, entry.log.length - LOG_LIMIT)
705
+ } catch (error) {
706
+ void error
707
+ }
708
+ }
709
+
710
+ const reachable = async (url) => {
711
+ try {
712
+ const res = await fetch(url, { signal: AbortSignal.timeout(1500) })
713
+ return res.status > 0
714
+ } catch (error) {
715
+ return false
716
+ }
717
+ }
718
+
719
+ const start = async (sid, root) => {
720
+ const entry = entryFor(sid)
721
+ if (entry.handle && !entry.exited) return { ok: true, running: true, url: previewUrl, base, port, command }
722
+ if (!configuredCommand) return { ok: false, code: 'noCommand', error: 'no start command configured' }
723
+ if (!root) return { ok: false, code: 'noRoot', error: 'workspace directory unknown' }
724
+ if (entry.starting) return { ok: false, code: 'starting', error: 'a service is already starting for this workspace' }
725
+ if (await reachable(previewUrl)) {
726
+ return { ok: false, code: 'portBusy', error: 'that port is already in use and does not belong to this workspace' }
727
+ }
728
+ entry.root = root
729
+ entry.log = []
730
+ entry.offsetOut = 0
731
+ entry.offsetErr = 0
732
+ entry.exited = false
733
+ entry.exitCode = null
734
+ entry.starting = true
735
+ try {
736
+ entry.handle = ctx.subprocess.spawn({
737
+ argv,
738
+ cwd: root,
739
+ stdio: { stdin: 'ignore', stdout: { maxBytes: 4_000_000 }, stderr: { maxBytes: 4_000_000 } },
740
+ graceMs: 8000,
741
+ })
742
+ } catch (error) {
743
+ entry.exited = true
744
+ entry.starting = false
745
+ return { ok: false, code: 'startFailed', detail: { error: String((error && error.message) || error) }, error: String((error && error.message) || error) }
746
+ }
747
+ entry.handle.done
748
+ .then((out) => {
749
+ entry.exited = true
750
+ entry.exitCode = out && typeof out.exitCode === 'number' ? out.exitCode : null
751
+ })
752
+ .catch(() => {
753
+ entry.exited = true
754
+ entry.exitCode = null
755
+ })
756
+
757
+ const deadline = Date.now() + readyTimeoutMs
758
+ while (Date.now() < deadline) {
759
+ drain(entry)
760
+ if (await reachable(previewUrl)) {
761
+ entry.starting = false
762
+ return { ok: true, running: true, url: previewUrl, base, port, command, log: entry.log.slice(-40) }
763
+ }
764
+ if (entry.exited) {
765
+ entry.starting = false
766
+ return { ok: false, code: 'exited', detail: { code: entry.exitCode === null ? '?' : entry.exitCode }, error: 'dev server exited', log: entry.log.slice(-40) }
767
+ }
768
+ await new Promise((resolve) => setTimeout(resolve, 700))
769
+ }
770
+ entry.starting = false
771
+ entry.handle?.terminate()
772
+ entry.exited = true
773
+ return { ok: false, code: 'readyTimeout', detail: { seconds: Math.round(readyTimeoutMs / 1000) }, error: 'timed out waiting for the dev server', log: entry.log.slice(-40) }
774
+ }
775
+
776
+ const stop = (sid) => {
777
+ const entry = entryFor(sid)
778
+ if (!entry.handle || entry.exited) return { ok: true, running: false }
779
+ try {
780
+ entry.handle.terminate()
781
+ } catch (error) {
782
+ void error
783
+ }
784
+ entry.exited = true
785
+ entry.handle = null
786
+ entry.log.push('· stopped')
787
+ return { ok: true, running: false }
788
+ }
789
+
790
+ const detect = async (sid, args, req) => {
791
+ const key = sid || '__root__'
792
+ const cached = detections.get(key)
793
+ if (!args?.force && cached && Date.now() - cached.at < detectCacheMs) return cached.value
794
+
795
+ const root = existingDirectory(args && args.root)
796
+ const selfPort = hostPort(req.headers.host)
797
+ const previewPorts = new Set((await Promise.all([...previews.values()])).map((entry) => Number(new URL(entry.origin).port)))
798
+ for (const entry of await Promise.all(staticServers.values())) previewPorts.add(Number(new URL(entry.origin).port))
799
+ const { ports: found, pids } = await listeningPorts()
800
+ const declared = await declaredProjectPorts(root)
801
+ const cwds = await processCwds([...new Set(pids.values())])
802
+ // A service belongs to the workspace when the process listening on it was
803
+ // started inside that workspace.
804
+ const owned = new Set([...pids].filter(([, pid]) => insideRoot(cwds.get(pid), root)).map(([port]) => port))
805
+ const candidates = [...new Set([...found, ...extraPorts, ...staticPorts])]
806
+ .filter((value) => Number.isInteger(value) && value > 0 && value < 65536 && value !== selfPort && !previewPorts.has(value))
807
+ .sort((a, b) => commonRank(a) - commonRank(b) || a - b)
808
+
809
+ const probed = []
810
+ for (let i = 0; i < candidates.length; i += 32) {
811
+ probed.push(...await Promise.all(candidates.slice(i, i + 32).map((value) => probePort(value, probeTimeoutMs))))
812
+ }
813
+ // The workspace's own services first, then the ports it asks for, then the
814
+ // common-port preference: one list, in the order people want to see it.
815
+ const services = probed.filter(Boolean)
816
+ .map((service) => ({ ...service, project: owned.has(service.port), declared: declared.has(service.port) }))
817
+ .sort((a, b) => Number(b.project) - Number(a.project) || Number(b.declared) - Number(a.declared) || commonRank(a.port) - commonRank(b.port) || a.port - b.port)
818
+ const value = {
819
+ ok: true,
820
+ services,
821
+ files: staticFiles ? await staticCandidates(root) : [],
822
+ hint: await startupHint(root),
823
+ scanned: candidates.length,
824
+ at: Date.now(),
825
+ }
826
+ detections.set(key, { at: Date.now(), value })
827
+ return value
828
+ }
829
+
830
+ const handler = async (req, res) => {
831
+ if (req.headers.origin && req.headers.origin !== requestOrigin(req)) { send(res, 403, { ok: false, code: 'originNotAllowed', error: 'origin not allowed' }); return }
832
+ if (req.method !== 'POST') {
833
+ send(res, 405, { ok: false, code: 'methodNotAllowed', error: 'method not allowed' })
834
+ return
835
+ }
836
+ try {
837
+ const body = await readJson(req)
838
+ const method = body && body.method
839
+ const args = (body && body.args) || {}
840
+ const sid = args.sid
841
+ if (disposed) return send(res, 503, { ok: false, error: 'plugin is shutting down' })
842
+ const entry = entryFor(sid)
843
+ drain(entry)
844
+ if (method === 'state') {
845
+ return send(res, 200, {
846
+ ok: true,
847
+ running: Boolean(entry.handle && !entry.exited),
848
+ starting: entry.starting,
849
+ url: previewUrl,
850
+ base,
851
+ command: configuredCommand ? command : null,
852
+ autoStart: configuredCommand,
853
+ root: entry.root,
854
+ port,
855
+ log: entry.log.slice(-60),
856
+ exitCode: entry.exitCode,
857
+ })
858
+ }
859
+ if (method === 'preview') {
860
+ reapPreviews()
861
+ let raw = String(args.url || '')
862
+ // Accept a plain local path (Windows drive / UNC / POSIX) as well as a
863
+ // file:// URL; the panel may send either when the user pastes a path.
864
+ if (/^file:/i.test(raw) === false && (/^[a-zA-Z]:[\\/]/.test(raw) || /^\\\\/.test(raw) || (raw.startsWith('/') && !raw.startsWith('//')))) {
865
+ try { raw = pathToFileURL(raw).href } catch (error) { void error }
866
+ }
867
+ let target
868
+ let suffix
869
+ let dir = null
870
+ let fileRoot = null
871
+ if (/^file:/i.test(raw)) {
872
+ const resolved = resolveFileTarget(raw, existingDirectory(args.root))
873
+ if (resolved.code) return send(res, 400, { ok: false, code: resolved.code, error: 'that file cannot be previewed' })
874
+ const server = await staticServer(resolved.dir)
875
+ dir = resolved.dir
876
+ // The page's own directory is the static root, so its relative scripts
877
+ // and styles resolve exactly as they do on disk.
878
+ target = new URL(server.origin + '/')
879
+ const fileUrl = new URL(raw)
880
+ fileRoot = new URL('.', fileUrl).href
881
+ suffix = '/' + encodeURIComponent(resolved.name) + fileUrl.search + fileUrl.hash
882
+ } else {
883
+ try { target = new URL(raw) } catch (error) { void error; target = null }
884
+ if (!target || !isLocalTarget(target) || Number(target.port) === hostPort(req.headers.host)) return send(res, 400, { ok: false, code: 'notLocalTarget', error: 'local development services only; Harness itself cannot be previewed' })
885
+ suffix = target.pathname + target.search + target.hash
886
+ }
887
+ // Desktop forwards API requests to its HTTP backend, while the actual
888
+ // frame parent remains the privileged dsh-app document.
889
+ const parentOrigin = args.parentOrigin === 'dsh-app://app' ? args.parentOrigin : requestOrigin(req)
890
+ const key = String(sid) + ':' + parentOrigin + ':' + target.origin + ':' + (fileRoot || '')
891
+ if (!previews.has(key)) {
892
+ if (previews.size >= 24) {
893
+ closeUnusedStatic(dir)
894
+ return send(res, 429, { ok: false, code: 'tooManyPreviews', error: 'too many active previews; close another preview and retry' })
895
+ }
896
+ const activity = { at: Date.now(), leases: new Map(), dir, sid }
897
+ previewActivity.set(key, activity)
898
+ const promise = createPreview(target, String(sid || ''), parentOrigin, fileRoot, () => { activity.at = Date.now() })
899
+ previews.set(key, promise)
900
+ promise.catch(() => { if (previews.get(key) === promise) closePreview(key) })
901
+ }
902
+ const activity = previewActivity.get(key)
903
+ activity.at = Date.now()
904
+ if (typeof args.lease === 'string' && args.lease) activity.leases.set(args.lease, Date.now() + PREVIEW_IDLE_MS)
905
+ const entry = await previews.get(key)
906
+ if (disposed) { entry.close(); return send(res, 503, { ok: false, error: 'plugin is shutting down' }) }
907
+ const frameUrl = new URL(entry.origin + suffix)
908
+ if (entry.frameKey) addFrameKey(frameUrl, entry.frameKey)
909
+ return send(res, 200, { ok: true, url: frameUrl.href, origin: entry.origin })
910
+ }
911
+ if (method === 'retainPreview' || method === 'releasePreview') {
912
+ for (const [key, promise] of previews) {
913
+ const activity = previewActivity.get(key)
914
+ if (activity?.sid !== sid || !activity.leases.has(args.lease)) continue
915
+ const preview = await promise
916
+ if (previews.get(key) !== promise || !activity.leases.has(args.lease)) continue
917
+ if (preview.origin !== args.origin) continue
918
+ if (method === 'releasePreview') {
919
+ // The tab was hidden or another session took focus: drop the lease
920
+ // but keep the loopback server alive so the same origin (and its
921
+ // cookies / login state) is reused when the user comes back. It is
922
+ // reaped after PREVIEW_IDLE_MS, on session archive, or on close.
923
+ activity.leases.delete(args.lease)
924
+ activity.at = Date.now()
925
+ } else {
926
+ activity.at = Date.now()
927
+ activity.leases.set(args.lease, Date.now() + PREVIEW_IDLE_MS)
928
+ }
929
+ return send(res, 200, { ok: true })
930
+ }
931
+ return send(res, 200, { ok: method === 'releasePreview' })
932
+ }
933
+ if (method === 'closePreview') {
934
+ for (const [key, promise] of previews) {
935
+ const activity = previewActivity.get(key)
936
+ if (!activity || activity.sid !== sid) continue
937
+ if (args.origin) {
938
+ const preview = await promise
939
+ if (preview.origin !== args.origin) continue
940
+ }
941
+ closePreview(key)
942
+ }
943
+ return send(res, 200, { ok: true })
944
+ }
945
+ if (method === 'detect') return send(res, 200, await detect(sid, args, req))
946
+ if (method === 'start') return send(res, 200, await start(sid, existingDirectory(args.root)))
947
+ if (method === 'stop') return send(res, 200, stop(sid))
948
+ return send(res, 200, { ok: false, error: 'unknown method: ' + String(method) })
949
+ } catch (error) {
950
+ return send(res, 500, { ok: false, error: String((error && error.message) || error) })
951
+ }
952
+ }
953
+
954
+ ctx.effect(() => ctx.webServer.register({ kind: 'prefix', path: ROUTE, handler }))
955
+ // Archiving a session discards its previews: the tab is gone for good, so the
956
+ // loopback server and its logged-in cookies should not linger.
957
+ ctx.effect(() => ctx.on('workspace/session-archived', (request) => {
958
+ const sid = request?.sessionId || request?.session?.id || request?.id
959
+ if (sid === undefined || sid === null) return
960
+ for (const [key] of previews) {
961
+ const activity = previewActivity.get(key)
962
+ if (activity && activity.sid === String(sid)) closePreview(key)
963
+ }
964
+ }))
965
+ ctx.effect(() => () => {
966
+ for (const entry of runs.values()) {
967
+ if (entry.handle && !entry.exited) {
968
+ try {
969
+ entry.handle.terminate()
970
+ } catch (error) {
971
+ void error
972
+ }
973
+ }
974
+ }
975
+ })
976
+ ctx.logger?.('dsh-annotate')?.info?.(
977
+ `dsh-annotate: loopback preview origins on demand, ws relay at ${WS_RELAY_PATH}, api ${ROUTE}`
978
+ )
979
+ }
980
+
981
+ // ---------------------------------------------------------------------------
982
+ // Proxy
983
+ // ---------------------------------------------------------------------------
984
+
985
+ const cookiePrefix = (enc) => `anno_${enc}_`
986
+
987
+ /** Cookies the browser holds for the harness must never reach the proxied app,
988
+ * and the app's own cookies must not escape into the harness. */
989
+ function splitCookies(header, enc) {
990
+ const prefix = cookiePrefix(enc)
991
+ const forwarded = []
992
+ for (const part of String(header || '').split(';')) {
993
+ const trimmed = part.trim()
994
+ const eq = trimmed.indexOf('=')
995
+ const name = eq === -1 ? '' : trimmed.slice(0, eq)
996
+ if (!name || !name.startsWith(prefix)) continue
997
+ forwarded.push(`${name.slice(prefix.length)}=${trimmed.slice(eq + 1)}`)
998
+ }
999
+ return forwarded.join('; ')
1000
+ }
1001
+
1002
+ /** Namespace the app's cookies and re-scope them to the preview origin.
1003
+ * The preview is plain http on loopback, so `SameSite=None` requires `Secure`
1004
+ * and, in Chromium, partitioned storage. */
1005
+ function rewriteSetCookie(value, enc, target) {
1006
+ const prefix = cookiePrefix(enc)
1007
+ const parts = String(value).split(';').map((part) => part.trim())
1008
+ const first = parts[0]
1009
+ const eq = first.indexOf('=')
1010
+ const name = eq === -1 ? first : first.slice(0, eq)
1011
+ const payload = eq === -1 ? '' : first.slice(eq + 1)
1012
+ const out = [`${prefix}${name}=${payload}`]
1013
+ let cookiePath = '/'
1014
+ for (const attribute of parts.slice(1)) {
1015
+ const lower = attribute.toLowerCase()
1016
+ if (lower.startsWith('domain=')) continue
1017
+ if (lower.startsWith('path=')) { cookiePath = attribute.slice(5).startsWith('/') ? attribute.slice(5) : '/'; continue }
1018
+ if (lower.startsWith('samesite=') || lower === 'secure' || lower === 'partitioned') continue
1019
+ out.push(attribute)
1020
+ }
1021
+ out.push(`Path=${cookiePath}`)
1022
+ out.push('SameSite=None', 'Secure', 'Partitioned')
1023
+ return out.join('; ')
1024
+ }
1025
+
1026
+ /**
1027
+ * The preview server serves the app at its own paths, so no document URL needs
1028
+ * rewriting and no import map is needed. Injecting a second import map would in
1029
+ * fact be harmful: a document may only have one, and ours would win over the
1030
+ * app's. Only the annotation config, the shim and the overlay are added.
1031
+ */
1032
+ function injectIntoHtml(html, config) {
1033
+ // Inline scripts inherit the document's encoding. Keep our source ASCII so
1034
+ // localized labels and config survive pages without a charset declaration
1035
+ // (or with a legacy charset), without changing the application's encoding.
1036
+ const script = (source) => source.replace(/[^\x00-\x7f]/g, (character) =>
1037
+ '\\u' + character.charCodeAt(0).toString(16).padStart(4, '0'))
1038
+ const head =
1039
+ `<script>window.__DSH_ANNO__=${script(JSON.stringify(config).replace(/</g, '\\u003c'))};</script>` +
1040
+ `<script>${script(SHIM_SRC)}</script>` +
1041
+ (config.isolated ? `<script>${script(OVERLAY_SRC)}</script>` : '')
1042
+ return /<head[^>]*>/i.test(html)
1043
+ ? html.replace(/<head[^>]*>/i, (match) => match + head)
1044
+ : /<html[^>]*>/i.test(html)
1045
+ ? html.replace(/<html[^>]*>/i, (match) => match + head)
1046
+ : head + html
1047
+ }
1048
+
1049
+ function proxyHttp(req, res, preview) {
1050
+ const incoming = new URL(req.url, 'http://localhost')
1051
+ const { target, enc, tail, search } = {
1052
+ target: preview.target,
1053
+ enc: encodeTarget(preview.target.origin),
1054
+ tail: incoming.pathname,
1055
+ search: incoming.search,
1056
+ }
1057
+ const origin = target.origin
1058
+
1059
+ const headers = {}
1060
+ for (const [key, value] of Object.entries(req.headers)) {
1061
+ const lower = key.toLowerCase()
1062
+ if (lower === 'host' || HOP_BY_HOP.has(lower)) continue
1063
+ if (lower === 'accept-encoding') continue // keep bodies readable for rewriting
1064
+ // A development preview must show edits even when its server advertises
1065
+ // immutable assets or answers a stale validator with 304.
1066
+ if ((req.method === 'GET' || req.method === 'HEAD') && (lower === 'if-none-match' || lower === 'if-modified-since')) continue
1067
+ if (lower === 'cookie') {
1068
+ const forwarded = splitCookies(value, enc)
1069
+ if (forwarded) headers.cookie = forwarded
1070
+ continue
1071
+ }
1072
+ if (lower === 'origin') {
1073
+ headers.origin = origin
1074
+ continue
1075
+ }
1076
+ if (lower === 'referer') {
1077
+ // The preview keeps the app's own paths, so only the origin changes.
1078
+ try {
1079
+ const ref = new URL(value)
1080
+ if (preview.frameKey) clearFrameKey(ref)
1081
+ headers.referer = origin + ref.pathname + ref.search
1082
+ } catch (error) { void error }
1083
+ continue
1084
+ }
1085
+ headers[key] = value
1086
+ }
1087
+ headers.host = target.host
1088
+ headers['accept-encoding'] = 'identity'
1089
+ headers['cache-control'] = 'no-cache'
1090
+
1091
+ const upstream = (target.protocol === 'https:' ? https : http).request(
1092
+ {
1093
+ protocol: target.protocol,
1094
+ hostname: target.hostname.replace(/^\[|\]$/g, ''),
1095
+ port: target.port || (target.protocol === 'https:' ? 443 : 80),
1096
+ method: req.method,
1097
+ path: tail + search,
1098
+ headers,
1099
+ },
1100
+ (upstreamRes) => {
1101
+ const type = String(upstreamRes.headers['content-type'] || '')
1102
+ const out = {}
1103
+ for (const [key, value] of Object.entries(upstreamRes.headers)) {
1104
+ const lower = key.toLowerCase()
1105
+ if (HOP_BY_HOP.has(lower)) continue
1106
+ if (UNFRAMEABLE.has(lower)) continue
1107
+ if (lower === 'content-length' || lower === 'content-encoding') continue
1108
+ if (lower === 'set-cookie') {
1109
+ out['set-cookie'] = (Array.isArray(value) ? value : [value]).map((one) => rewriteSetCookie(one, enc, target))
1110
+ continue
1111
+ }
1112
+ if (lower === 'location' && typeof value === 'string') {
1113
+ // An absolute upstream redirect must stay on the preview origin or
1114
+ // the next document will lose the shim and annotation overlay.
1115
+ try {
1116
+ const destination = new URL(value, origin + tail + search)
1117
+ if (destination.origin === origin) {
1118
+ // The initial custom-scheme iframe has no Referer on a redirect
1119
+ // either. Keep its capability on local redirects only.
1120
+ if (preview.frameKey && req.headers['sec-fetch-dest'] === 'iframe') addFrameKey(destination, preview.frameKey)
1121
+ out.location = destination.pathname + destination.search + destination.hash
1122
+ } else out.location = value
1123
+ } catch { out.location = value }
1124
+ continue
1125
+ }
1126
+ out[key] = value
1127
+ }
1128
+ out['cache-control'] = 'no-store'
1129
+ delete out.expires
1130
+
1131
+ if (!type.includes('text/html')) {
1132
+ res.writeHead(upstreamRes.statusCode ?? 502, out)
1133
+ upstreamRes.pipe(res)
1134
+ return
1135
+ }
1136
+
1137
+ // HTML: inject config, shim and overlay before any app script runs.
1138
+ const chunks = []
1139
+ upstreamRes.on('data', (chunk) => chunks.push(chunk))
1140
+ upstreamRes.on('end', () => {
1141
+ const html = Buffer.concat(chunks).toString('utf8')
1142
+ const body = Buffer.from(
1143
+ injectIntoHtml(html, { upstream: origin, page: preview.fileRoot ? new URL('.' + tail + search, preview.fileRoot).href : null, fileRoot: preview.fileRoot, prefix: '/', relay: WS_RELAY_PATH, enc, isolated: true, parentOrigin: preview.parentOrigin, session: preview.sid }),
1144
+ 'utf8'
1145
+ )
1146
+ out['content-length'] = String(body.length)
1147
+ res.writeHead(upstreamRes.statusCode ?? 200, out)
1148
+ res.end(body)
1149
+ })
1150
+ upstreamRes.on('error', () => res.end())
1151
+ }
1152
+ )
1153
+
1154
+ upstream.setTimeout(15000, () => upstream.destroy(new Error('connection timed out')))
1155
+ upstream.on('error', (error) => {
1156
+ if (!res.headersSent) res.writeHead(502, { 'content-type': 'text/html; charset=utf-8' })
1157
+ res.end(
1158
+ `<body style="font:12px ui-monospace,SFMono-Regular,Menlo,monospace;padding:20px;color:#666">${escapeHtml(error.message)}` +
1159
+ `<script>parent.postMessage({source:'dsh-annotate-page',type:'error',code:'upstreamUnreachable'},${JSON.stringify(preview.parentOrigin)})</script></body>`
1160
+ )
1161
+ })
1162
+ res.on('close', () => {
1163
+ if (!res.writableEnded) upstream.destroy()
1164
+ })
1165
+ req.pipe(upstream)
1166
+ }
1167
+
1168
+ function proxyUpgrade(req, socket, head) {
1169
+ const url = new URL(req.url || '/', 'http://127.0.0.1')
1170
+ const enc = url.searchParams.get('to') || ''
1171
+ const targetPath = url.searchParams.get('path') || '/'
1172
+ let target
1173
+ try {
1174
+ target = new URL(decodeTarget(enc))
1175
+ if (!isLocalTarget(target)) throw new Error('local targets only')
1176
+ } catch (error) {
1177
+ void error
1178
+ socket.destroy()
1179
+ return
1180
+ }
1181
+
1182
+ const headers = {}
1183
+ for (const [key, value] of Object.entries(req.headers)) {
1184
+ const lower = key.toLowerCase()
1185
+ if (lower === 'host' || lower === 'authorization' || HOP_BY_HOP.has(lower)) continue
1186
+ if (lower === 'cookie') {
1187
+ const forwarded = splitCookies(value, enc)
1188
+ if (forwarded) headers.cookie = forwarded
1189
+ continue
1190
+ }
1191
+ if (lower === 'origin') {
1192
+ headers.origin = target.origin
1193
+ continue
1194
+ }
1195
+ headers[key] = value
1196
+ }
1197
+ headers.host = target.host
1198
+ headers.connection = 'Upgrade'
1199
+ headers.upgrade = 'websocket'
1200
+
1201
+ const upstream = (target.protocol === 'https:' ? https : http).request({
1202
+ protocol: target.protocol,
1203
+ hostname: target.hostname.replace(/^\[|\]$/g, ''),
1204
+ port: target.port || (target.protocol === 'https:' ? 443 : 80),
1205
+ method: req.method,
1206
+ path: targetPath.startsWith('/') ? targetPath : new URL(targetPath).pathname + new URL(targetPath).search,
1207
+ headers,
1208
+ })
1209
+ upstream.on('upgrade', (upstreamRes, upstreamSocket, upstreamHead) => {
1210
+ const lines = [`HTTP/1.1 ${upstreamRes.statusCode ?? 101} ${upstreamRes.statusMessage ?? 'Switching Protocols'}`]
1211
+ for (const [key, value] of Object.entries(upstreamRes.headers)) {
1212
+ if (HOP_BY_HOP.has(key.toLowerCase())) continue
1213
+ if (Array.isArray(value)) for (const one of value) lines.push(`${key}: ${one}`)
1214
+ else lines.push(`${key}: ${value}`)
1215
+ }
1216
+ lines.push('connection: Upgrade')
1217
+ socket.write(lines.join('\r\n') + '\r\n\r\n')
1218
+ if (upstreamHead && upstreamHead.length) socket.write(upstreamHead)
1219
+ if (head && head.length) upstreamSocket.write(head)
1220
+ upstreamSocket.pipe(socket)
1221
+ socket.pipe(upstreamSocket)
1222
+ const close = () => {
1223
+ upstreamSocket.destroy()
1224
+ socket.destroy()
1225
+ }
1226
+ upstreamSocket.on('error', close)
1227
+ upstreamSocket.on('close', close)
1228
+ socket.on('error', close)
1229
+ socket.on('close', close)
1230
+ })
1231
+ upstream.on('response', (upstreamRes) => {
1232
+ const lines = [`HTTP/1.1 ${upstreamRes.statusCode ?? 400} ${upstreamRes.statusMessage ?? 'Bad Request'}`]
1233
+ for (const [key, value] of Object.entries(upstreamRes.headers)) lines.push(`${key}: ${value}`)
1234
+ socket.write(lines.join('\r\n') + '\r\n\r\n')
1235
+ socket.destroy()
1236
+ })
1237
+ upstream.on('error', () => socket.destroy())
1238
+ upstream.end()
1239
+ }
1240
+
1241
+ /** A dedicated loopback origin preserves app paths and separates app DOM and
1242
+ * storage from Harness. Nothing outside loopback may be used as an upstream.
1243
+ * Servers are keyed by session + app and disposed with the plugin. */
1244
+ async function createPreview(target, sid, parentOrigin, fileRoot, touch) {
1245
+ const hostname = new URL(parentOrigin).hostname === 'localhost' ? '127.0.0.1' : 'localhost'
1246
+ // A directory can contain several pages; derive each document's identity
1247
+ // from its own path instead of caching the first file opened in this session.
1248
+ const frameKey = parentOrigin === 'dsh-app://app' ? randomUUID() : null
1249
+ const preview = { target: new URL(target.origin), sid, parentOrigin, fileRoot, frameKey }
1250
+ const originOfPreview = () => `http://${hostname}:${server.address().port}`
1251
+ const server = http.createServer((req, res) => {
1252
+ // Only the preview's own hostname is served, so a DNS-rebinding page cannot
1253
+ // reach the app through this origin.
1254
+ if (req.headers.host !== `${hostname}:${server.address().port}`) { res.writeHead(403); res.end(); return }
1255
+ const frameUrl = new URL(req.url, originOfPreview())
1256
+ // Chromium omits the custom-scheme Referer on a desktop iframe load.
1257
+ // Authorize that initial navigation with an unguessable per-preview key,
1258
+ // retaining provenance checks for unrelated pages and subresource fetches.
1259
+ const keyedFrame = frameKey && req.headers['sec-fetch-dest'] === 'iframe' && frameUrl.searchParams.get('__dsh_anno_key') === frameKey
1260
+ if (!keyedFrame && !allowedPreviewRequest(req, parentOrigin, originOfPreview())) { res.writeHead(403); res.end(); return }
1261
+ if (frameKey) clearFrameKey(frameUrl)
1262
+ req.url = frameUrl.pathname + frameUrl.search
1263
+ touch()
1264
+ proxyHttp(req, res, preview)
1265
+ })
1266
+ const sockets = new Set()
1267
+ server.on('connection', (socket) => { sockets.add(socket); socket.once('close', () => sockets.delete(socket)) })
1268
+ server.on('upgrade', (req, socket, head) => {
1269
+ if (req.headers.origin !== originOfPreview()) { socket.destroy(); return }
1270
+ touch()
1271
+ const path = req.url
1272
+ req.url = WS_RELAY_PATH + '?to=' + encodeTarget(target.origin) + '&path=' + encodeURIComponent(path)
1273
+ proxyUpgrade(req, socket, head)
1274
+ })
1275
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, hostname, resolve) })
1276
+ return { server, frameKey, origin: `http://${hostname}:${server.address().port}`, close() { for (const socket of sockets) socket.destroy(); server.close() } }
1277
+ }