Files
deepseek-harness/packages/host/frontend-static/src/index.ts
T
imccyu 71753fdf91 refactor(connection): add connection auth provider for remote connection (#8266)
* refactor(connection): extract peer authentication providers

* test(connection): cover provider lifecycle and satisfy package gates

* fix(packaging): publish authentication provider locale resources

* test(auth): use runtime login output and cover gateway admission

* fix(auth): preserve Worker requests and migrate Desktop fixtures

* refactor(auth): centralize route admission with required policy

* fix(release): align authentication providers with rc.2

* refactor(connection): keep peer lookup and source policy private

* test(gateway): cover centralized upgrade rejections

* fix(ci): authenticate homepage compression probe

* refactor(auth): let Token own API socket lifecycle

* fix(auth): prevent caching admission refusals and clarify ownership

* refactor(web): collect provider entry URLs after readiness

* refactor(webserver): name the shared entry URL event

* refactor(connection): provide authentication as a nested service

* fix(web-app): restore startup publication defaults

* fix(auth): scope web events and preserve callback flows

* docs(auth): record the implemented provider architecture

* fix(auth): require owner access for administrative routes
2026-11-12 23:14:32 +08:00

154 lines
6.9 KiB
TypeScript

/**
* @deepseek-ai/dsh-host-frontend-static — SPA dist server over the webserver
* fallback seat: a webserver resource serving the built frontend directory
* with explicit index entry points. A readable index renders at the dist root
* and configured index path; missing paths return 404, traversal outside the
* dist root is 403, unknown extensions ship as octet-stream, and non-GET/HEAD
* is 405. An HTTP index request first passes Connection's browser
* authentication and renders for its admitted Peer; an in-process read renders
* for the Peer its caller admitted. Both renders go through the webserver's
* index render (structured injection rows, then raw taps). Non-index assets
* stay public; every file other than the index carries a weak ETag with
* `cache-control: no-cache` and answers a matching `If-None-Match` with 304,
* while the index carries no cache headers. The dist location is workspace
* knowledge of the composing application, so `distIndex` is typically
* supplied through a `!!js` expression, never hardcoded by a deployment.
* @module @deepseek-ai/dsh-host-frontend-static
*/
import { createHash } from 'node:crypto'
import { readFile } from 'node:fs/promises'
import { dirname, extname, join, normalize, resolve, sep } from 'node:path'
import type { Context } from '@deepseek-ai/cordis'
import z from '@deepseek-ai/schemastery'
import type { PeerScope } from '@deepseek-ai/dsh-client-connection'
import type {} from '@deepseek-ai/dsh-host-webserver'
/** Stable Cordis plugin name. */
export const name = 'frontend-static'
/** Services required before the authenticated fallback seat can be claimed. */
export const inject = ['webServer', 'connection']
/** Plugin config: the dist anchor. */
export interface Config {
/** Absolute path of index.html inside the dist root. */
distIndex: string
}
export const Config: z<Config> = z.object({
distIndex: z.string().required(),
})
const HTML_MIME = 'text/html; charset=utf-8'
const MIME: Record<string, string> = {
'.html': HTML_MIME,
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
// Launchers require an image Content-Type for the install icons.
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.json': 'application/json',
'.map': 'application/json',
'.webmanifest': 'application/manifest+json',
// The packed VFS image. Served as its own bytes, never as a Content-Encoding:
// the worker inflates the body itself, and a transport-level encoding would
// leave it inflating an already-decoded archive.
'.gz': 'application/gzip',
}
const STATIC_MISS_CODES: ReadonlySet<string | undefined> = new Set([
'ENOENT',
'EISDIR',
'ENOTDIR',
])
/** A Response body that is `bytes` itself, without the copy a buffer body gets. */
function bytesBody(bytes: Uint8Array): ReadableStream<Uint8Array> {
return new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(bytes)
controller.close()
},
})
}
/**
* Answer one GET or HEAD dist request; the webserver answers any other method
* with 405 before a resource runs. A malformed percent-escape or a filesystem
* failure other than a missing or non-file target rejects.
* @param request - the request; only its method and URL path are read.
* @param distRoot - absolute dist root directory (resolved by the caller).
* @param distIndex - absolute path of index.html inside distRoot.
* @param renderIndex - present for index requests to turn the raw index.html
* into the served document; omitted for ordinary static files.
* @returns the dist response; a HEAD response carries the GET status and
* headers without a body. A file other than the index carries
* `cache-control: no-cache` and a weak ETag from a SHA-1 of its bytes, and a
* request whose `If-None-Match` equals that ETag receives an empty 304.
*/
async function serveStatic(
request: Request, distRoot: string, distIndex: string,
renderIndex?: (html: string) => string,
): Promise<Response> {
const target = resolve(normalize(join(distRoot, decodeURIComponent(new URL(request.url).pathname))))
// Traversal rejection: the target must be distRoot itself (`/`) or stay under
// it. `sep`, not '/': resolve() emits backslash paths on Windows, where a '/'
// suffix would reject every legitimate subpath as traversal.
if (target !== distRoot && !target.startsWith(distRoot + sep)) return new Response(null, { status: 403 })
let body: string | Uint8Array<ArrayBuffer>
let headers: Record<string, string>
try {
if (renderIndex !== undefined) {
const html = await readFile(distIndex, 'utf8')
request.signal.throwIfAborted()
body = renderIndex(html)
headers = { 'content-type': HTML_MIME }
} else {
body = await readFile(target)
// Weak: gzip changes the transferred bytes.
const cache = { 'cache-control': 'no-cache', etag: `W/"${createHash('sha1').update(body).digest('base64url')}"` }
if (request.headers.get('if-none-match') === cache.etag) return new Response(null, { status: 304, headers: cache })
headers = { 'content-type': MIME[extname(target)] ?? 'application/octet-stream', ...cache }
}
} catch (error) {
// Only absent or non-file targets are 404; other filesystem failures reach
// the caller, which the webserver answers with 400 over HTTP.
if (!STATIC_MISS_CODES.has((error as NodeJS.ErrnoException).code)) throw error
return new Response(null, { status: 404 })
}
if (request.method === 'HEAD') return new Response(null, { status: 200, headers })
return new Response(typeof body === 'string' ? body : bytesBody(body), { status: 200, headers })
}
/**
* Claim the webserver fallback seat with a resource serving the dist.
* @param ctx - plugin context carrying the webServer and connection services.
* @param config - validated {@link Config}.
*/
export function apply(ctx: Context, config: Config): void {
const distIndex = config.distIndex
const distRoot = dirname(distIndex)
ctx.effect(() => ctx.webServer.registerFallback({
auth: (request) => {
const target = resolve(normalize(join(distRoot, decodeURIComponent(request.url.pathname))))
return target === distRoot || target === distIndex ? 'required' : 'anonymous'
},
resource: (request, peer) => {
request.signal.throwIfAborted()
const target = resolve(normalize(join(distRoot, decodeURIComponent(new URL(request.url).pathname))))
if (target !== distRoot && target !== distIndex) return serveStatic(request, distRoot, distIndex)
// WebServer admits every index request before invoking this resource.
const pagePeer = peer as PeerScope
const render = (html: string): string => {
request.signal.throwIfAborted()
pagePeer.signal.throwIfAborted()
return ctx.webServer.renderIndex(html, pagePeer)
.replace(/<head(?:\s[^>]*)?>/i, open => `${open}<base href="./">`)
}
return serveStatic(request, distRoot, distIndex, render)
},
}), 'frontend-static: fallback seat')
}