frontend-static.spec.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. /**
  2. * REAL-composition coverage: a test-only cordis.yml booted through the
  3. * vendored Loader mounts the webserver and frontend-static rows, and every
  4. * assertion observes the served HTTP surface — asset serving, explicit index
  5. * entry points with index taps, 404 misses, traversal rejection, 405 on non-
  6. * GET/HEAD, and seat release on fiber disposal (HMR safety).
  7. */
  8. import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
  9. import { tmpdir } from 'node:os'
  10. import { join } from 'node:path'
  11. import { pathToFileURL } from 'node:url'
  12. import { afterEach, describe, expect, it } from 'vitest'
  13. import { Context } from '@deepseek-ai/cordis'
  14. import Loader from '@deepseek-ai/cordis-plugin-loader'
  15. import Include from '@deepseek-ai/cordis-plugin-include'
  16. import HttpServer from '@deepseek-ai/dsh-host-webserver'
  17. import * as FrontendStatic from '../src/index.ts'
  18. let root: string | undefined
  19. let context: Context | undefined
  20. afterEach(async () => {
  21. await context?.fiber.dispose()
  22. context = undefined
  23. if (root !== undefined) await rm(root, { recursive: true, force: true })
  24. root = undefined
  25. })
  26. /** Write a dist fixture and a two-row cordis.yml, then boot it through the real Loader. */
  27. async function loadComposition(): Promise<Context> {
  28. root = await mkdtemp(join(tmpdir(), 'dsh-frontend-static-'))
  29. const dist = join(root, 'dist')
  30. await mkdir(dist)
  31. const distIndex = join(dist, 'index.html')
  32. await writeFile(distIndex, '<head></head><body>shell</body>')
  33. await writeFile(join(dist, 'app.js'), 'export {}')
  34. await writeFile(join(dist, 'blob.bin'), 'BLOB')
  35. await writeFile(join(dist, 'manifest.webmanifest'), '{}')
  36. await mkdir(join(dist, 'empty'))
  37. const configPath = join(root, 'cordis.yml')
  38. await writeFile(configPath, [
  39. "- name: '@deepseek-ai/dsh-host-webserver'",
  40. ' config:',
  41. " host: '127.0.0.1'",
  42. ' port: 0',
  43. '- id: frontend',
  44. " name: '@deepseek-ai/dsh-host-frontend-static'",
  45. ' config:',
  46. ` distIndex: '${distIndex}'`,
  47. '',
  48. ].join('\n'))
  49. context = new Context()
  50. context.baseUrl = pathToFileURL(root).href + '/'
  51. await context.plugin(Loader)
  52. context.loader.builtins.include = Include
  53. const modules = new Map<string, unknown>([
  54. ['@deepseek-ai/dsh-host-webserver', HttpServer],
  55. ['@deepseek-ai/dsh-host-frontend-static', FrontendStatic],
  56. ])
  57. context.loader.internal = {
  58. version: 'v2',
  59. async import(specifier: string) {
  60. if (!modules.has(specifier)) throw new Error(`unexpected Loader import: ${specifier}`)
  61. return modules.get(specifier)
  62. },
  63. } as unknown as NonNullable<typeof context.loader.internal>
  64. await context.loader.create({
  65. name: 'cordis:include',
  66. config: { path: pathToFileURL(configPath).href },
  67. })
  68. await context.loader.await()
  69. return context
  70. }
  71. /** GET (by default) one path against the running server; returns status, content-type, and a body prefix. */
  72. async function request(port: number, path: string, init?: RequestInit): Promise<{ status: number; type: string | null; body: string }> {
  73. const response = await fetch(`http://127.0.0.1:${String(port)}${path}`, init)
  74. return {
  75. status: response.status,
  76. type: response.headers.get('content-type'),
  77. // Window wide enough to keep index body markers visible behind the
  78. // served prelude (base anchor + injection rows + boot-readiness tail).
  79. body: (await response.text()).slice(0, 200),
  80. }
  81. }
  82. describe('real Loader composition', () => {
  83. it('serves explicit index entries and files while preserving HTTP error semantics', { timeout: 60_000 }, async () => {
  84. const loaded = await loadComposition()
  85. const unloaded = [...loaded.loader.entries()]
  86. .filter(entry => entry.fiber === undefined && !entry.disabled)
  87. .map(entry => entry.options.name)
  88. expect(unloaded).toEqual([])
  89. const server = loaded.webServer
  90. const port = server.port
  91. // Real assets with their MIME types; a live rebuild is served on the next read.
  92. expect(await request(port, '/app.js')).toMatchObject({ status: 200, type: 'text/javascript; charset=utf-8', body: 'export {}' })
  93. expect(await request(port, '/manifest.webmanifest')).toMatchObject({
  94. status: 200,
  95. type: 'application/manifest+json',
  96. body: '{}',
  97. })
  98. expect(await request(port, '/app.js', { method: 'HEAD' })).toEqual({
  99. status: 200,
  100. type: 'text/javascript; charset=utf-8',
  101. body: '',
  102. })
  103. await writeFile(join(root!, 'dist', 'app.js'), 'export const rebuilt = true')
  104. expect(await request(port, '/app.js')).toMatchObject({ status: 200, body: 'export const rebuilt = true' })
  105. // Unknown extension ships as octet-stream.
  106. expect(await request(port, '/blob.bin')).toMatchObject({ status: 200, type: 'application/octet-stream', body: 'BLOB' })
  107. // Only the root and index path render index.html through registered taps.
  108. const untap = server.tapIndex(html => html.replace('<head>', '<head><script>window.__T__=1</script>'))
  109. for (const path of ['/', '/index.html', '/?fixture']) {
  110. const got = await request(port, path)
  111. expect(got.status).toBe(200)
  112. expect(got.type).toBe('text/html; charset=utf-8')
  113. expect(got.body).toContain('__T__')
  114. expect(got.body).toContain('shell')
  115. }
  116. expect(await request(port, '/', { method: 'HEAD' })).toEqual({
  117. status: 200,
  118. type: 'text/html; charset=utf-8',
  119. body: '',
  120. })
  121. untap()
  122. expect((await request(port, '/')).body).not.toContain('__T__')
  123. // A missing configured index follows the same empty-404 contract for both
  124. // of its public entry paths and for both supported methods.
  125. await rm(join(root!, 'dist', 'index.html'))
  126. for (const path of ['/', '/index.html']) {
  127. const get = await request(port, path)
  128. const head = await request(port, path, { method: 'HEAD' })
  129. expect(get).toEqual({ status: 404, type: null, body: '' })
  130. expect(head).toEqual(get)
  131. }
  132. // Ordinary unknown paths and static-resource misses are empty 404s for
  133. // both GET and HEAD; neither class can be mistaken for the HTML shell.
  134. const ordinaryMisses = ['/no/such/route', '/api/no/such/route', '/empty', '/app.js/child']
  135. const assetMisses = [
  136. '/missing.js',
  137. '/missing.css',
  138. '/missing.mjs',
  139. '/missing.js.map',
  140. '/missing.webmanifest',
  141. '/missing.manifest',
  142. ]
  143. for (const path of [...ordinaryMisses, ...assetMisses]) {
  144. const get = await request(port, path)
  145. const head = await request(port, path, { method: 'HEAD' })
  146. expect(get).toEqual({ status: 404, type: null, body: '' })
  147. expect(head).toEqual(get)
  148. }
  149. // Traversal outside the dist root is 403, non-GET/HEAD is 405, and a
  150. // malformed filesystem target still reaches the webserver's 400 guard.
  151. expect((await request(port, '/..%2f..%2fetc%2fpasswd')).status).toBe(403)
  152. expect((await request(port, '/app.js', { method: 'POST' })).status).toBe(405)
  153. expect((await request(port, '/bad%00path')).status).toBe(400)
  154. // HMR safety: disposing the frontend row releases the fallback seat (the
  155. // unclaimed webserver answers 404) and the seat is claimable again.
  156. const frontendEntry = [...loaded.loader.entries()].find(e => e.options.id === 'frontend')
  157. expect(frontendEntry).toBeDefined()
  158. await frontendEntry!.fiber?.dispose()
  159. expect((await request(port, '/no/such/route')).status).toBe(404)
  160. expect(() => server.registerFallback(() => {})).not.toThrow()
  161. })
  162. })