fix(webview): resolve a relative base against the document directory

rebaseRelativeBase resolved a relative <base> against the proxy root, so
a document served from a subdirectory of its dashboard (for example
/webview/<cap>/app/page.html with <base href="./">) pointed at
/webview/<cap>/ and loaded its assets one level too high. Pass the
request's wildcard path into rewriteHtml and resolve the base against
the document URL, which keeps the proxy root for the landing page.
This commit is contained in:
ArizeSky committed 2026-11-16 16:11:58 +08:00
1 parent 238853f96a
commit cc413afdd1
6 files changed
+66 -9

No files matched your search

+1 -1
View File
@@ -2,4 +2,4 @@
"aicodeman": patch
---
Web tabs whose dashboard ships a relative `<base href>` render again. The proxy rewrites the document URL to strip its `/webview/<cap>/` prefix, and a relative base is resolved against that URL — so `./` (what Vite builds emit, DeepSeek Harness among them) pointed at Codeman's root: every module script 404'd and the page painted its background with nothing on it. The rewrite now resolves such a base against the proxy prefix before the mask runs; a cross-origin base is left exactly as the author wrote it.
Web tabs whose dashboard ships a relative `<base href>` render again. The proxy rewrites the document URL to strip its `/webview/<cap>/` prefix, and a relative base is resolved against that URL — so `./` (what Vite builds emit, DeepSeek Harness among them) pointed at Codeman's root: every module script 404'd and the page painted its background with nothing on it. The rewrite now resolves such a base against the document's own directory inside the proxy prefix before the mask runs (a page at `/webview/<cap>/app/page.html` gets `/webview/<cap>/app/`, not the proxy root); a cross-origin base is left exactly as the author wrote it.
+5 -3
View File
@@ -146,9 +146,11 @@ layers cooperate so a dashboard talking to its own backend just works:
1. `<base href>` handles relative URLs in the markup. A page that ships its own
**relative** base (`<base href="./">`, what a Vite build emits) has it resolved
against the proxy prefix first: the page's URL is masked a few paragraphs below,
a base is resolved against that URL, so `./` would otherwise point at Codeman's
root and 404 every module script behind an otherwise-painted page.
against the document's own directory inside the proxy prefix first, so a
document at `/webview/<cap>/app/page.html` gets `/webview/<cap>/app/` rather
than the proxy root: the page's URL is masked a few paragraphs below, a base is
resolved against that URL, so `./` would otherwise point at Codeman's root and
404 every module script behind an otherwise-painted page.
2. Attribute rewriting handles root-absolute `src`/`href`/`action` in the page the
proxy serves — and root-absolute dynamic `import("/...")` specifiers in the
initial HTML. The import is the one URL no other layer can reach: `<base>` does
+3 -1
View File
@@ -643,7 +643,9 @@ async function proxyRequest(
// Buffer only HTML, only under the cap: `<base>` injection needs the whole
// document, and buffering an unbounded upstream body is a memory hazard.
const html = await response.text();
return reply.send(html.length <= MAX_WEBVIEW_HTML_REWRITE_BYTES ? rewriteHtml(html, cap, basePath) : html);
return reply.send(
html.length <= MAX_WEBVIEW_HTML_REWRITE_BYTES ? rewriteHtml(html, cap, basePath, wildcard) : html
);
}
return reply.send(Readable.fromWeb(response.body as Parameters<typeof Readable.fromWeb>[0]));
+17 -4
View File
@@ -753,11 +753,17 @@ try{
* already-absolute path resolves to itself. Cross-origin bases are the author
* pointing at a CDN and are left exactly as written.
*
* The document path matters: a base in `/webview/<cap>/app/page.html` is
* relative to `/webview/<cap>/app/`, not to the proxy root, or a page served
* from a subdirectory would resolve its assets one level too high.
*
* @param html - document with attributes already rebased.
* @param prefix - proxy prefix the document was served from.
* @param documentPath - upstream path of the document, without the leading slash.
* @returns the document with a relative base href made absolute.
*/
function rebaseRelativeBase(html: string, prefix: string): string {
function rebaseRelativeBase(html: string, prefix: string, documentPath: string): string {
const documentUrl = `http://codeman.invalid${prefix}${documentPath.replace(/^\/+/, '')}`;
return html.replace(
/(<base\b[^>]*?\bhref\s*=\s*)(["'])([^"']*)\2/i,
(match: string, head: string, quote: string, href: string) => {
@@ -765,7 +771,7 @@ function rebaseRelativeBase(html: string, prefix: string): string {
try {
// A stand-in origin: only the path is kept, and a different origin here
// is exactly the "absolute base" case this must not touch.
resolved = new URL(href, `http://codeman.invalid${prefix}`);
resolved = new URL(href, documentUrl);
} catch {
return match;
}
@@ -783,8 +789,14 @@ function rebaseRelativeBase(html: string, prefix: string): string {
* Three layers, because no single one is sufficient: `<base>` for parser-resolved
* relative URLs, attribute rewriting for root-absolute markup, and the shim for
* URLs built at runtime.
*
* @param html - the upstream document.
* @param capability - capability the document is being served under.
* @param basePath - reverse-proxy mount prefix (`''` at root).
* @param documentPath - upstream path of the document, without the leading slash.
* Used to resolve the page's own relative `<base>` against its directory.
*/
export function rewriteHtml(html: string, capability: string, basePath = ''): string {
export function rewriteHtml(html: string, capability: string, basePath = '', documentPath = ''): string {
const prefix = proxyPrefixFor(capability, basePath);
// Fresh regexes per call: module-level /g patterns carry `lastIndex` between calls.
@@ -801,7 +813,8 @@ export function rewriteHtml(html: string, capability: string, basePath = ''): st
// own loading spinner never resolves. Rewriting the specifier here is the
// only layer that can.
.replace(/\bimport\s*\(\s*(["'])\/(?!\/)/g, (_match, quote: string) => `import(${quote}${prefix}`),
prefix
prefix,
documentPath
);
// A page that ships its own <base> keeps it (overriding it would break the
+27
View File
@@ -417,6 +417,33 @@ describe('managed DeepSeek web cookie', () => {
});
});
describe('proxy HTML rewrite', () => {
// The request path is what the page's relative URLs are relative to. Proving
// it here (rather than only on rewriteHtml) pins that proxyRequest passes it.
it("resolves the document's relative base against its own directory", async () => {
const server = http.createServer((_req, res) => {
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
res.end('<html><head><base href="./"></head><body>app</body></html>');
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (!address || typeof address === 'string') throw new Error('upstream has no address');
try {
const created = (await create({ name: 'App', url: `http://127.0.0.1:${address.port}/app/page.html` })).json()
.data;
const opened = (await app.inject({ method: 'POST', url: `/api/webviews/${created.id}/open` })).json().data;
const cap = capabilityFromProxyPath(opened.embedUrl)!;
const res = await app.inject({ method: 'GET', url: `/webview/${cap}/app/page.html` });
expect(res.statusCode).toBe(200);
expect(res.body).toContain(`<base href="/webview/${cap}/app/">`);
} finally {
await new Promise<void>((resolve) => server.close(() => resolve()));
}
});
});
describe('POST /api/webviews/probe', () => {
it('reports an unreachable target as a normal answer, not a 500', async () => {
// Port 1 is reserved and refuses instantly.
+13
View File
@@ -395,6 +395,19 @@ describe('rewriteHtml', () => {
expect(out).toContain(`<base target="_blank" href="${PREFIX}sub/">`);
});
// A document served from a subdirectory resolves its relative base against
// ITS directory, not the proxy root: `/webview/<cap>/app/page.html` with
// `<base href="./">` must point at `/webview/<cap>/app/`.
it("resolves a relative <base> against the document's own directory", () => {
const out = rewriteHtml('<html><head><base href="./"></head></html>', CAP, '', 'app/page.html');
expect(out).toContain(`<base href="${PREFIX}app/">`);
});
it('resolves a ../ base from the document directory', () => {
const out = rewriteHtml('<html><head><base href="../assets/"></head></html>', CAP, '', 'app/sub/page.html');
expect(out).toContain(`<base href="${PREFIX}app/assets/">`);
});
it('leaves a cross-origin <base> exactly as the author wrote it', () => {
const out = rewriteHtml('<html><head><base href="https://cdn.example/x/"></head></html>', CAP);
expect(out).toContain('<base href="https://cdn.example/x/">');