refactor(webserver): extract SPA dist serving to the frontend-static fallback seat
The webserver's built-in static dist serving becomes a single-owner fallback seat (registerFallback/applyIndexTaps); the SPA server moves to the new @deepseek-ai/dsh-frontend-static plugin so the composing application owns its dist as composition, not carrier config. distIndex leaves the webserver schema; unclaimed fallback answers 404.
This commit is contained in:
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* @deepseek-ai/dsh-frontend-static — SPA dist server over the webserver
|
||||
* fallback seat: serves the built frontend directory with the semantics the
|
||||
* Web shell locked at step1 — traversal outside the dist root is 403, any
|
||||
* miss falls back to index.html with HTTP 200 (SPA routing), unknown
|
||||
* extensions ship as octet-stream, non-GET/HEAD is 405. Every index response
|
||||
* runs through the webserver's registered index taps (boot-manifest
|
||||
* injection). 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-frontend-static
|
||||
*/
|
||||
|
||||
import type { ServerResponse } from 'node:http'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { dirname, extname, join, normalize, resolve, sep } from 'node:path'
|
||||
import type { Context } from 'cordis'
|
||||
import z from 'schemastery'
|
||||
import type {} from '@deepseek-ai/dsh-host-webserver'
|
||||
|
||||
/** Stable Cordis plugin name. */
|
||||
export const name = 'frontend-static'
|
||||
|
||||
/** Service required before the fallback seat can be claimed. */
|
||||
export const inject = ['httpServer']
|
||||
|
||||
/** 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 MIME: Record<string, string> = {
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.js': 'text/javascript; charset=utf-8',
|
||||
'.css': 'text/css; charset=utf-8',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.json': 'application/json',
|
||||
'.map': 'application/json',
|
||||
}
|
||||
|
||||
/**
|
||||
* Serve one GET/HEAD static request from the dist root.
|
||||
* @param pathname - decoded URL pathname of the request.
|
||||
* @param res - the node:http response to write.
|
||||
* @param distRoot - absolute dist root directory (resolved by the caller).
|
||||
* @param distIndex - absolute path of index.html inside distRoot.
|
||||
* @param renderIndex - produces the index.html body (index-tap injection) for
|
||||
* `/` and every SPA fallback.
|
||||
*/
|
||||
export async function serveStatic(
|
||||
pathname: string, res: ServerResponse, distRoot: string, distIndex: string,
|
||||
renderIndex: () => Promise<string>,
|
||||
): Promise<void> {
|
||||
const target = resolve(normalize(join(distRoot, 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)) {
|
||||
res.writeHead(403)
|
||||
res.end()
|
||||
return
|
||||
}
|
||||
const serveIndex = async (): Promise<void> => {
|
||||
const body = await renderIndex()
|
||||
res.writeHead(200, { 'content-type': MIME['.html'] })
|
||||
res.end(body)
|
||||
}
|
||||
if (target === distRoot || target === distIndex) {
|
||||
await serveIndex()
|
||||
return
|
||||
}
|
||||
try {
|
||||
const body = await readFile(target)
|
||||
res.writeHead(200, { 'content-type': MIME[extname(target)] ?? 'application/octet-stream' })
|
||||
res.end(body)
|
||||
} catch {
|
||||
// Miss (ENOENT/EISDIR) falls back to index.html with 200 (SPA routing).
|
||||
await serveIndex()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Claim the webserver fallback seat and serve the dist.
|
||||
* @param ctx - plugin context carrying the httpServer service.
|
||||
* @param config - validated {@link Config}.
|
||||
*/
|
||||
export function apply(ctx: Context, config: Config): void {
|
||||
const distIndex = config.distIndex
|
||||
const distRoot = dirname(distIndex)
|
||||
const renderIndex = async (): Promise<string> =>
|
||||
ctx.httpServer.applyIndexTaps(await readFile(distIndex, 'utf8'))
|
||||
ctx.effect(() => ctx.httpServer.registerFallback(async (req, res) => {
|
||||
// Non-GET/HEAD without a matching named route is 405 (fallback-only
|
||||
// semantics: named routes own their method handling).
|
||||
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
||||
res.writeHead(405)
|
||||
res.end()
|
||||
return
|
||||
}
|
||||
/* v8 ignore next -- node:http always sets url on server requests */
|
||||
const rawPath = new URL(req.url ?? '/', 'http://x').pathname
|
||||
await serveStatic(decodeURIComponent(rawPath), res, distRoot, distIndex, renderIndex)
|
||||
}), 'frontend-static: fallback seat')
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* Package-owned invariant companion for `@deepseek-ai/dsh-frontend-static`.
|
||||
* @module @deepseek-ai/dsh-frontend-static/invariant
|
||||
*/
|
||||
|
||||
import type { Context } from 'cordis'
|
||||
// Empty type import carries the Loader's Fiber#entry merge read below.
|
||||
import type {} from '@cordisjs/plugin-loader'
|
||||
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
|
||||
|
||||
const PACKAGE_NAME = '@deepseek-ai/dsh-frontend-static'
|
||||
|
||||
/** Cordis companion plugin name. */
|
||||
export const name = 'frontend-static-invariant'
|
||||
/** Service required before the companion can register. */
|
||||
export const inject = ['invariants']
|
||||
|
||||
/**
|
||||
* Owned relation: the fallback seat and the owning fiber must stay symmetric —
|
||||
* after the fiber holding the seat unloads, the seat must be claimable again
|
||||
* (a stale fallback would keep serving a disposed plugin's dist). Checked on
|
||||
* every fiber teardown by probing the registerFallback single-owner contract:
|
||||
* when this package's plugin is not mounted, a claim+release cycle must
|
||||
* succeed twice; residue from a leaked disposer makes the second claim throw.
|
||||
*/
|
||||
const install: InvariantInstaller = (ctx, fail) => {
|
||||
ctx.on('internal/plugin', (fiber) => {
|
||||
// Only audit teardowns of this package's own rows: while a live
|
||||
// frontend-static row legitimately holds the seat, the probe would
|
||||
// false-positive on the legitimate owner.
|
||||
if (fiber.entry?.options.name !== PACKAGE_NAME) return
|
||||
const server = ctx.get('httpServer') as
|
||||
| { registerFallback(handler: () => void): () => void }
|
||||
| undefined
|
||||
if (server === undefined) return // torn down with the webserver itself
|
||||
// The probe handlers are registered and immediately released, never invoked.
|
||||
/* v8 ignore next 4 -- the arrow bodies are dead by design */
|
||||
try {
|
||||
server.registerFallback(() => {})()
|
||||
server.registerFallback(() => {})()
|
||||
} catch {
|
||||
fail('frontend-static fallback disposer left the seat claimed — seat ownership and fiber lifecycle diverged')
|
||||
}
|
||||
}, { global: true })
|
||||
}
|
||||
|
||||
/**
|
||||
* Register this package's invariant companion.
|
||||
* @param ctx - Cordis context carrying the invariant service.
|
||||
* @returns the installed registration's disposer after setup succeeds.
|
||||
*/
|
||||
export const apply = (ctx: Context): Promise<() => void> =>
|
||||
Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
|
||||
Reference in New Issue
Block a user