webserver.spec.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs'
  2. import { Server as NetServer } from 'node:net'
  3. import { tmpdir } from 'node:os'
  4. import { join } from 'node:path'
  5. import { afterEach, describe, expect, it, vi } from 'vitest'
  6. import { startWebServer, type RunningWebServer } from '../src/index.ts'
  7. /** dist fixture: index.html + one asset of each MIME class + a subdir. */
  8. function makeDist(): { distIndex: string; distRoot: string } {
  9. const distRoot = mkdtempSync(join(tmpdir(), 'dsh-webserver-'))
  10. writeFileSync(join(distRoot, 'index.html'), '<html>INDEX</html>')
  11. writeFileSync(join(distRoot, 'app.js'), 'console.log(1)')
  12. writeFileSync(join(distRoot, 'app.css'), 'body{}')
  13. writeFileSync(join(distRoot, 'logo.svg'), '<svg/>')
  14. writeFileSync(join(distRoot, 'data.json'), '{}')
  15. writeFileSync(join(distRoot, 'app.js.map'), '{}')
  16. writeFileSync(join(distRoot, 'blob.bin'), 'BIN')
  17. mkdirSync(join(distRoot, 'sub'))
  18. writeFileSync(join(distRoot, 'sub', 'page.html'), '<html>SUB</html>')
  19. return { distIndex: join(distRoot, 'index.html'), distRoot }
  20. }
  21. const echoingApi = {
  22. fetch: async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
  23. const req = input instanceof Request ? input : new Request(input, init)
  24. if (req.url.endsWith('/api/echo')) {
  25. return Response.json({ method: req.method, body: await req.text(), header: req.headers.get('x-probe') })
  26. }
  27. if (req.url.endsWith('/api/empty')) return new Response(null, { status: 204 })
  28. if (req.url.endsWith('/api/big')) {
  29. // Chunks far above any socket highWaterMark force res.write to return false.
  30. const big = new Uint8Array(4 * 1024 * 1024).fill(65)
  31. const stream = new ReadableStream<Uint8Array>({
  32. start(controller) {
  33. controller.enqueue(big)
  34. controller.enqueue(big)
  35. controller.close()
  36. },
  37. })
  38. return new Response(stream, { headers: { 'content-type': 'application/octet-stream' } })
  39. }
  40. if (req.url.endsWith('/api/sse')) {
  41. const encoder = new TextEncoder()
  42. const stream = new ReadableStream<Uint8Array>({
  43. start(controller) {
  44. controller.enqueue(encoder.encode('data: one\n\n'))
  45. controller.enqueue(encoder.encode('data: two\n\n'))
  46. controller.close()
  47. },
  48. })
  49. return new Response(stream, { headers: { 'content-type': 'text/event-stream' } })
  50. }
  51. if (req.url.endsWith('/api/throw-string')) {
  52. // Non-Error rejection: the guard must wrap it for onError.
  53. throw 'string failure'
  54. }
  55. if (req.url.endsWith('/api/explode-mid-stream')) {
  56. // Headers go out with the first chunk, then the source errors: the
  57. // guard's headersSent leg must destroy the socket, not writeHead again.
  58. // The error is deferred a tick so the 200 + first chunk actually flush
  59. // to the client before the teardown.
  60. const stream = new ReadableStream<Uint8Array>({
  61. start(controller) {
  62. controller.enqueue(new TextEncoder().encode('data: first\n\n'))
  63. setTimeout(() => { controller.error(new Error('stream exploded')) }, 20)
  64. },
  65. })
  66. return new Response(stream, { headers: { 'content-type': 'text/event-stream' } })
  67. }
  68. if (req.url.endsWith('/api/abort-probe')) {
  69. // Endless SSE that only ends when the request signal aborts.
  70. const stream = new ReadableStream<Uint8Array>({
  71. start(controller) {
  72. req.signal.addEventListener('abort', () => {
  73. try {
  74. controller.close()
  75. } catch { /* already closed by teardown: nothing else can reach this */ }
  76. }, { once: true })
  77. controller.enqueue(new TextEncoder().encode('data: open\n\n'))
  78. },
  79. })
  80. return new Response(stream, { headers: { 'content-type': 'text/event-stream' } })
  81. }
  82. return new Response('nope', { status: 404 })
  83. },
  84. }
  85. let server: RunningWebServer | undefined
  86. afterEach(async () => {
  87. await server?.close()
  88. server = undefined
  89. })
  90. async function boot(onError: (err: Error) => void = () => undefined): Promise<string> {
  91. const { distIndex } = makeDist()
  92. server = await startWebServer({ host: '127.0.0.1', port: 0, distIndex, apiHandler: echoingApi }, onError)
  93. return `http://127.0.0.1:${String(server.port)}`
  94. }
  95. describe('startWebServer', () => {
  96. it('reports the listening port and closes idempotently', async () => {
  97. const { distIndex } = makeDist()
  98. server = await startWebServer({ host: '127.0.0.1', port: 0, distIndex, apiHandler: echoingApi }, () => undefined)
  99. expect(server.port).toBeGreaterThan(0)
  100. const first = server.close()
  101. const second = server.close()
  102. expect(second).toBe(first)
  103. await first
  104. server = undefined
  105. })
  106. it.each(['127.0.0.1', '0.0.0.0'])('forwards bind address %s without opening a socket', async (host) => {
  107. const { distIndex } = makeDist()
  108. const port = 3080
  109. const listen = vi.spyOn(NetServer.prototype, 'listen').mockImplementation(function (
  110. this: NetServer, ...args: unknown[]
  111. ): NetServer {
  112. const callback = args.at(-1)
  113. if (typeof callback !== 'function') throw new TypeError('listen callback missing')
  114. queueMicrotask(callback as () => void)
  115. return this
  116. })
  117. const address = vi.spyOn(NetServer.prototype, 'address').mockReturnValue({ address: host, family: 'IPv4', port })
  118. try {
  119. const inertServer = await startWebServer({ host, port, distIndex, apiHandler: echoingApi }, () => undefined)
  120. expect(listen).toHaveBeenCalledWith(port, host, expect.any(Function))
  121. await inertServer.close()
  122. } finally {
  123. address.mockRestore()
  124. listen.mockRestore()
  125. }
  126. })
  127. it('rejects when the port is already taken', async () => {
  128. const { distIndex } = makeDist()
  129. server = await startWebServer({ host: '127.0.0.1', port: 0, distIndex, apiHandler: echoingApi }, () => undefined)
  130. const { port } = server
  131. await expect(startWebServer({ host: '127.0.0.1', port, distIndex, apiHandler: echoingApi }, () => undefined))
  132. .rejects.toMatchObject({ code: 'EADDRINUSE' })
  133. })
  134. })
  135. describe.skipIf(process.platform === 'win32')('static serving', () => {
  136. it('serves index at /, subpaths by MIME, octet-stream for unknown, SPA fallback on miss', async () => {
  137. const base = await boot()
  138. const index = await fetch(`${base}/`)
  139. expect(index.status).toBe(200)
  140. expect(index.headers.get('content-type')).toBe('text/html; charset=utf-8')
  141. expect(await index.text()).toBe('<html>INDEX</html>')
  142. expect((await fetch(`${base}/app.js`)).headers.get('content-type')).toBe('text/javascript; charset=utf-8')
  143. expect((await fetch(`${base}/app.css`)).headers.get('content-type')).toBe('text/css; charset=utf-8')
  144. expect((await fetch(`${base}/logo.svg`)).headers.get('content-type')).toBe('image/svg+xml')
  145. expect((await fetch(`${base}/data.json`)).headers.get('content-type')).toBe('application/json')
  146. expect((await fetch(`${base}/app.js.map`)).headers.get('content-type')).toBe('application/json')
  147. expect((await fetch(`${base}/blob.bin`)).headers.get('content-type')).toBe('application/octet-stream')
  148. expect(await (await fetch(`${base}/sub/page.html`)).text()).toBe('<html>SUB</html>')
  149. const miss = await fetch(`${base}/routes/deep/link`)
  150. expect(miss.status).toBe(200)
  151. expect(await miss.text()).toBe('<html>INDEX</html>')
  152. })
  153. it('403s traversal outside the dist root and 405s non-GET/HEAD', async () => {
  154. const base = await boot()
  155. // %2e%2e would be dot-collapsed by WHATWG URL parsing on both ends; an
  156. // encoded slash keeps the segment intact until the server's decodeURIComponent.
  157. const traversal = await fetch(`${base}/..%2f..%2fetc%2fpasswd`)
  158. expect(traversal.status).toBe(403)
  159. const put = await fetch(`${base}/index.html`, { method: 'PUT', body: 'x' })
  160. expect(put.status).toBe(405)
  161. })
  162. it('answers HEAD like GET (no 405)', async () => {
  163. const base = await boot()
  164. const head = await fetch(`${base}/`, { method: 'HEAD' })
  165. expect(head.status).toBe(200)
  166. })
  167. })
  168. describe.skipIf(process.platform === 'win32')('web plugin surfaces (boot injection + bundle endpoint + events channel)', () => {
  169. const FETCH_ID = '@deepseek-ai/dsh-client-ui-layout'
  170. const graphValue = {
  171. rev: 'graphrev00001',
  172. entries: [
  173. { id: '@deepseek-ai/dsh-client-connection', url: '/plugins/@deepseek-ai/dsh-client-connection/client.js?rev=eeee2222ffff', rev: 'eeee2222ffff', immediately: true },
  174. { id: FETCH_ID, url: `/plugins/${FETCH_ID}/client.js?rev=aaaa0000bbbb`, rev: 'aaaa0000bbbb', inject: [] },
  175. ],
  176. }
  177. /** Captures the server's onRebuilt subscription so tests can fire registry notifications by hand. */
  178. interface RebuiltHarness {
  179. notify: (id: string, rev: string) => void
  180. unsubscribed: boolean
  181. }
  182. async function bootWithPlugins(harness?: RebuiltHarness): Promise<string> {
  183. const { distIndex, distRoot } = makeDist()
  184. writeFileSync(join(distRoot, 'bundle.js'), 'window.DSHClientProxy.loadPlugin({})')
  185. const webPlugins = {
  186. graph: () => graphValue,
  187. clientPath: (id: string) => id === FETCH_ID ? join(distRoot, 'bundle.js') : undefined,
  188. onRebuilt: (listener: (id: string, rev: string) => void) => {
  189. if (harness !== undefined) harness.notify = listener
  190. return () => {
  191. if (harness !== undefined) harness.unsubscribed = true
  192. }
  193. },
  194. }
  195. server = await startWebServer(
  196. { host: '127.0.0.1', port: 0, distIndex, apiHandler: echoingApi, webPlugins }, () => undefined,
  197. )
  198. return `http://127.0.0.1:${String(server.port)}`
  199. }
  200. it('injects the window.__DSH_BOOT__ graph into / and SPA fallbacks; asset requests stay verbatim', async () => {
  201. const base = await bootWithPlugins()
  202. const index = await (await fetch(`${base}/`)).text()
  203. expect(index).toContain('window.__DSH_BOOT__')
  204. const manifest = /window\.__DSH_BOOT__ = (.*?)<\/script>/.exec(index)?.[1]
  205. expect(JSON.parse(manifest ?? '')).toEqual(graphValue)
  206. const fallback = await (await fetch(`${base}/routes/deep/link`)).text()
  207. expect(fallback).toContain('window.__DSH_BOOT__')
  208. const direct = await (await fetch(`${base}/index.html`)).text()
  209. expect(direct).toContain('window.__DSH_BOOT__')
  210. expect(await (await fetch(`${base}/app.js`)).text()).toBe('console.log(1)')
  211. })
  212. it('serves registered client bundles with no-cache (rev query ignored) and 404s unknown ids (no SPA fallback)', async () => {
  213. const base = await bootWithPlugins()
  214. const bundle = await fetch(`${base}/plugins/${FETCH_ID}/client.js?rev=whatever`)
  215. expect(bundle.status).toBe(200)
  216. expect(bundle.headers.get('content-type')).toBe('text/javascript; charset=utf-8')
  217. expect(bundle.headers.get('cache-control')).toBe('no-cache')
  218. expect(await bundle.text()).toContain('DSHClientProxy')
  219. expect((await fetch(`${base}/plugins/unknown/client.js`)).status).toBe(404)
  220. })
  221. it('404s a registered id whose bundle file is unreadable (unbuilt dist must fail loud, not fall back to HTML)', async () => {
  222. const { distIndex } = makeDist()
  223. const webPlugins = {
  224. graph: () => graphValue,
  225. clientPath: () => '/nonexistent/lib/client.js',
  226. onRebuilt: () => () => undefined,
  227. }
  228. server = await startWebServer(
  229. { host: '127.0.0.1', port: 0, distIndex, apiHandler: echoingApi, webPlugins }, () => undefined,
  230. )
  231. const res = await fetch(`http://127.0.0.1:${String(server.port)}/plugins/${FETCH_ID}/client.js`)
  232. expect(res.status).toBe(404)
  233. })
  234. it('keeps all plugin surfaces off without the webPlugins option', async () => {
  235. const base = await boot()
  236. expect(await (await fetch(`${base}/`)).text()).toBe('<html>INDEX</html>')
  237. // No plugin routes: fall through to static SPA fallback semantics.
  238. const res = await fetch(`${base}/plugins/x/client.js`)
  239. expect(res.status).toBe(200)
  240. expect(await res.text()).toBe('<html>INDEX</html>')
  241. const events = await fetch(`${base}/plugins/events`)
  242. expect(await events.text()).toBe('<html>INDEX</html>')
  243. })
  244. it('GET /plugins/events opens SSE with the current graph frame; a registry rebuild notification broadcasts', async () => {
  245. const harness: RebuiltHarness = { notify: () => { throw new Error('onRebuilt never subscribed') }, unsubscribed: false }
  246. const base = await bootWithPlugins(harness)
  247. const events = await fetch(`${base}/plugins/events`)
  248. expect(events.status).toBe(200)
  249. expect(events.headers.get('content-type')).toBe('text/event-stream')
  250. const reader = events.body?.getReader()
  251. const decoder = new TextDecoder()
  252. let buffer = ''
  253. async function readUntil(marker: string): Promise<void> {
  254. while (!buffer.includes(marker)) {
  255. const chunk = await reader?.read()
  256. if (chunk?.done !== false) throw new Error('SSE stream ended early')
  257. buffer += decoder.decode(chunk.value, { stream: true })
  258. }
  259. }
  260. await readUntil('"type":"graph"')
  261. expect(buffer).toContain(': connected')
  262. const graphLine = /data: (.*)\n\n/.exec(buffer)?.[1]
  263. expect(JSON.parse(graphLine ?? '')).toEqual({ type: 'graph', graph: graphValue })
  264. // The registry's bundle watch observed a rebuild: the server relays it as an SSE frame.
  265. harness.notify(FETCH_ID, 'cccc1111dddd')
  266. await readUntil('"type":"rebuilt"')
  267. expect(buffer).toContain(JSON.stringify({ type: 'rebuilt', id: FETCH_ID, rev: 'cccc1111dddd' }))
  268. await reader?.cancel()
  269. // Shutdown unsubscribes the relay (no broadcast into a closed channel).
  270. await server?.close()
  271. server = undefined
  272. expect(harness.unsubscribed).toBe(true)
  273. })
  274. })
  275. describe('request-handling guard (one bad request must not kill the process)', () => {
  276. it('400s malformed %-escapes, reports to onError, and stays alive', async () => {
  277. const errors: Error[] = []
  278. const base = await boot(err => errors.push(err))
  279. for (const path of ['/%', '/%c0', '/%zz%']) {
  280. expect((await fetch(`${base}${path}`)).status).toBe(400)
  281. }
  282. expect(errors.length).toBe(3)
  283. expect(errors[0]?.name).toBe('URIError')
  284. // The barrage left the server serving.
  285. expect((await fetch(`${base}/`)).status).toBe(200)
  286. })
  287. it('wraps a non-Error throw for onError and still answers 400', async () => {
  288. const errors: Error[] = []
  289. const base = await boot(err => errors.push(err))
  290. expect((await fetch(`${base}/api/throw-string`, { method: 'POST' })).status).toBe(400)
  291. expect(errors[0]).toBeInstanceOf(Error)
  292. expect(errors[0]?.message).toBe('string failure')
  293. })
  294. it('destroys the socket when the failure lands after headers went out', async () => {
  295. const errors: Error[] = []
  296. const base = await boot(err => errors.push(err))
  297. const response = await fetch(`${base}/api/explode-mid-stream`)
  298. expect(response.status).toBe(200) // headers made it out before the explosion
  299. await expect(response.text()).rejects.toThrow() // then the socket is torn down
  300. expect(errors.length).toBe(1)
  301. expect((await fetch(`${base}/`)).status).toBe(200)
  302. })
  303. })
  304. describe('/api bridge', () => {
  305. it('forwards method, headers, and body; relays status and body back', async () => {
  306. const base = await boot()
  307. const response = await fetch(`${base}/api/echo`, {
  308. method: 'POST',
  309. headers: { 'content-type': 'application/json', 'x-probe': 'p1' },
  310. body: JSON.stringify({ n: 1 }),
  311. })
  312. expect(response.status).toBe(200)
  313. expect(await response.json()).toEqual({ method: 'POST', body: '{"n":1}', header: 'p1' })
  314. })
  315. it('relays a bodyless response', async () => {
  316. const base = await boot()
  317. const response = await fetch(`${base}/api/empty`, { method: 'POST' })
  318. expect(response.status).toBe(204)
  319. expect(await response.text()).toBe('')
  320. })
  321. it('streams SSE frames through chunk by chunk', async () => {
  322. const base = await boot()
  323. const response = await fetch(`${base}/api/sse`)
  324. expect(response.headers.get('content-type')).toBe('text/event-stream')
  325. expect(await response.text()).toBe('data: one\n\ndata: two\n\n')
  326. })
  327. it('waits for drain when a streamed chunk overfills the socket buffer', async () => {
  328. // 4 MiB chunks dwarf the socket highWaterMark, so res.write returns false
  329. // and the bridge parks on 'drain'; reading the body to completion proves
  330. // the loop resumed instead of dropping the remainder.
  331. const base = await boot()
  332. const response = await fetch(`${base}/api/big`)
  333. const body = new Uint8Array(await response.arrayBuffer())
  334. expect(body.length).toBe(8 * 1024 * 1024)
  335. expect(body[0]).toBe(65)
  336. expect(body[body.length - 1]).toBe(65)
  337. })
  338. it('releases a drain wait when the client disconnects mid-chunk', async () => {
  339. // The 'close' leg of the drain race: abort while the socket buffer is
  340. // still full so the parked write wakes via 'close', not 'drain'.
  341. const base = await boot()
  342. const ac = new AbortController()
  343. const response = await fetch(`${base}/api/big`, { signal: ac.signal })
  344. const reader = response.body?.getReader()
  345. const first = await reader?.read()
  346. expect(first?.value?.length).toBeGreaterThan(0)
  347. ac.abort()
  348. // afterEach close() completing is the leak assertion, same as abort-probe.
  349. await new Promise((resolve) => { setTimeout(resolve, 50) })
  350. })
  351. it('aborts the bridged request when the client disconnects mid-SSE', async () => {
  352. const base = await boot()
  353. const ac = new AbortController()
  354. const response = await fetch(`${base}/api/abort-probe`, { signal: ac.signal })
  355. const reader = response.body?.getReader()
  356. expect(reader).toBeDefined()
  357. const first = await reader?.read()
  358. expect(new TextDecoder().decode(first?.value)).toContain('open')
  359. ac.abort()
  360. // server-side abort propagation has no client-observable handshake beyond
  361. // the closed connection; close() would hang on a leaked live SSE socket,
  362. // so afterEach completing IS the assertion that the bridge released it.
  363. await new Promise((resolve) => { setTimeout(resolve, 50) })
  364. })
  365. })