Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

deploy: owner app shell — artifact-style top bar with a docked iterate chat

Regan Bell346388d3fe7c
diff --git a/src/api/routes/deployments.ts b/src/api/routes/deployments.ts
index 7af8045e7..bff8821ef 100644
--- a/src/api/routes/deployments.ts
+++ b/src/api/routes/deployments.ts
@@ -19,7 +19,7 @@ import type { ApiCtx, BaseCtx, Route } from "./route.ts";
import { CONFIG_DEFAULTS } from "../../config.ts";
import { resolveShareTarget as resolveShareTargetGrammar } from "../artifact-share.ts";
import { mintDeployOwnerToken, verifyDeployGitAccess, verifyDeployOwnerToken } from "../../deploy/access-token.ts";
-import { EDIT_WIDGET_JS, EDIT_WIDGET_PATH_PREFIX, editWidgetTag } from "../../deploy/edit-widget.ts";
+import { APP_SHELL_PATH_PREFIX, appShellHtml } from "../../deploy/app-shell.ts";
import { principalDestination } from "../../reach/reach.ts";
import { portalSessionSub } from "../../deploy/viewer-session.ts";
import { proxyHeaders } from "../../util/http-proxy.ts";
@@ -245,28 +245,12 @@ function checkDeploymentHttp2Session(connection: DeploymentHttp2Connection): voi
}
}
-function htmlInjection(
- inject: string | undefined,
- method: string,
- statusCode: number,
- headers: Record<string, string | string[]>,
-): string | null {
- if (!inject || method !== "GET") return null;
- if (statusCode !== 200) return null;
- const contentType = headers["content-type"];
- if (typeof contentType !== "string" || !/^text\/html\b/i.test(contentType)) return null;
- if (headers["content-encoding"]) return null;
- delete headers["content-length"];
- return inject;
-}
-
function proxyReachHttp2(
ctx: BaseCtx,
endpoint: Awaited<ReturnType<App["reachDeployment"]>> & { status: "ok" },
subPath: string,
headers: Record<string, string | string[]>,
bufferedBody: Buffer | null,
- inject?: string,
): void {
const { req, res, deps, url, method } = ctx;
const { host, port, tls } = endpoint.endpoint;
@@ -311,7 +295,6 @@ function proxyReachHttp2(
current = up;
connection.activeStreams++;
let responseStarted = false;
- let pendingInject: string | null = null;
let failureHandled = false;
const fail = (error?: unknown): void => {
if (failureHandled) return;
@@ -345,7 +328,7 @@ function proxyReachHttp2(
up.once("close", () => {
releaseDeploymentHttp2Stream(origin, connection);
if (!responseStarted || !up.readableEnded || up.rstCode !== http2Constants.NGHTTP2_NO_ERROR) fail();
- else if (!failureHandled && !res.destroyed && !res.writableEnded) res.end(pendingInject ?? undefined);
+ else if (!failureHandled && !res.destroyed && !res.writableEnded) res.end();
});
up.setTimeout(deps.deployDialTimeoutMs ?? CONFIG_DEFAULTS.deployDialTimeoutMs, () => {
if (failureHandled) return;
@@ -365,7 +348,6 @@ function proxyReachHttp2(
armThrottleShield(`${host}:${port}`, Number(responseHeaders[":status"] ?? 0), up);
const status = Number(responseHeaders[":status"] ?? 502);
const safeHeaders = gatewaySafeResponseHeaders(responseHeaders);
- pendingInject = htmlInjection(inject, method, status, safeHeaders);
res.writeHead(status, safeHeaders);
up.pipe(res, { end: false });
});
@@ -381,7 +363,6 @@ async function proxyReach(
ctx: BaseCtx,
reach: Awaited<ReturnType<App["reachDeployment"]>>,
subPath: string,
- inject?: string,
): Promise<void> {
const { req, res, deps, url, method } = ctx;
if (res.destroyed) return;
@@ -408,7 +389,6 @@ async function proxyReach(
host: hostHeader,
...reach.endpoint.proxyHeaders,
};
- if (inject) headers["accept-encoding"] = "identity";
if (/(?:^|,)\s*chunked\s*$/i.test(String(req.headers["transfer-encoding"] ?? ""))) {
const chunks: Buffer[] = [];
let size = 0;
@@ -428,7 +408,7 @@ async function proxyReach(
}
if (res.destroyed) return;
if (reach.endpoint.httpVersion === "2") {
- proxyReachHttp2(ctx, reach, subPath, headers, bufferedBody, inject);
+ proxyReachHttp2(ctx, reach, subPath, headers, bufferedBody);
return;
}
const up = requestFn({ hostname: host, port, path: subPath + url.search, method, headers }, (upRes) => {
@@ -436,16 +416,8 @@ async function proxyReach(
upRes.on("error", () => res.destroy());
armThrottleShield(upstreamKey, upRes.statusCode ?? 0, upRes);
const headers = gatewaySafeResponseHeaders(upRes.headers);
- const pendingInject = htmlInjection(inject, method, upRes.statusCode ?? 502, headers);
res.writeHead(upRes.statusCode ?? 502, headers);
- if (pendingInject === null) {
- upRes.pipe(res);
- } else {
- upRes.pipe(res, { end: false });
- upRes.on("end", () => {
- if (!res.destroyed && !res.writableEnded) res.end(pendingInject);
- });
- }
+ upRes.pipe(res);
});
up.setTimeout(deps.deployDialTimeoutMs ?? CONFIG_DEFAULTS.deployDialTimeoutMs, () => {
if (!res.headersSent) sendJson(res, 504, { error: "gateway_timeout", message: "deployment did not respond" });
@@ -690,12 +662,7 @@ export async function proxyDeploymentSubdomain(ctx: BaseCtx): Promise<boolean> {
const session = await verifyDeployOwnerToken(gateSecret, ownerCookieValue, slug);
if (session && (await app.canManageDeployment(slug, session.sub))) ownerSub = session.sub;
}
- if (ownerSub && ctx.method === "GET" && pathname.startsWith(EDIT_WIDGET_PATH_PREFIX)) {
- if (pathname === "/__claw__/widget.js") {
- res.writeHead(200, { "content-type": "text/javascript; charset=utf-8", "cache-control": "no-store" });
- res.end(EDIT_WIDGET_JS);
- return true;
- }
+ if (ownerSub && ctx.method === "GET" && pathname.startsWith(APP_SHELL_PATH_PREFIX)) {
if (pathname === "/__claw__/version") {
const d = await app.getDeployment(slug);
if (!d) sendJson(res, 404, { error: "not_found" });
@@ -705,17 +672,30 @@ export async function proxyDeploymentSubdomain(ctx: BaseCtx): Promise<boolean> {
sendJson(res, 404, { error: "not_found" });
return true;
}
- const fetchDest = String(req.headers["sec-fetch-dest"] ?? "");
- const isDocumentLoad = fetchDest === "" || fetchDest === "document";
- const inject =
- ownerSub && isDocumentLoad && deps.deployAppsLoginUrl ? editWidgetTag(deps.deployAppsLoginUrl, slug) : undefined;
if (ownerSub) {
if (signInAttempted && ctx.method === "GET") {
cleanUrlRedirect();
return true;
}
+ // A top-level document load gets the owner shell: a slim top bar over the app
+ // (framed same-origin) with a slide-out chat column for iterating on it. The
+ // frame's own load carries sec-fetch-dest: iframe, so it proxies straight through.
+ const isTopDocument = String(req.headers["sec-fetch-dest"] ?? "") === "document";
+ if (ctx.method === "GET" && isTopDocument && deps.deployAppsLoginUrl) {
+ const accent = deps.config ? (await deps.config.getBrandingDurable(orgScope(deps)))?.accent : undefined;
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
+ res.end(
+ appShellHtml({
+ slug,
+ portalUrl: deps.deployAppsLoginUrl,
+ path: safePathname + url.search,
+ ...(accent ? { accent } : {}),
+ }),
+ );
+ return true;
+ }
const reach = await app.reachDeployment(slug, "", { bypassAcl: true });
- await proxyReach(ctx, reach, pathname, inject);
+ await proxyReach(ctx, reach, pathname);
return true;
}
const sessionSecret = deps.deployAppsSessionSecret;
diff --git a/src/deploy/app-shell.ts b/src/deploy/app-shell.ts
new file mode 100644
index 000000000..3efc6ed6a
--- /dev/null
+++ b/src/deploy/app-shell.ts
@@ -0,0 +1,201 @@
+export const APP_SHELL_PATH_PREFIX = "/__claw__/";
+
+function escAttr(value: string): string {
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
+}
+
+/**
+ * The owner shell: a Claude-artifacts-style top bar over the deployed app, with a
+ * slide-out chat column for iterating on it. Served only to a signed-in owner on
+ * top-level document loads; the app itself renders untouched inside a same-origin
+ * iframe (its sub-resource and iframe requests carry a non-document sec-fetch-dest,
+ * so the gateway proxies them straight through).
+ */
+export function appShellHtml(opts: { slug: string; portalUrl: string; path: string; accent?: string }): string {
+ const slug = escAttr(opts.slug);
+ const path = escAttr(opts.path);
+ const accent = /^[#a-zA-Z0-9(),.% -]{1,64}$/.test(opts.accent ?? "") ? (opts.accent as string) : "#4f46e5";
+ return `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<meta name="robots" content="noindex">
+<title>${slug}</title>
+<style>
+ /* qm web-ui tokens (mini-lit default theme + shell.css) */
+ :root {
+ --background: oklch(1 0 0);
+ --foreground: oklch(0.145 0 0);
+ --secondary: oklch(0.97 0 0);
+ --muted-foreground: oklch(0.556 0 0);
+ --border: oklch(0.922 0 0);
+ --brand-accent: ${accent};
+ --radius-sm: 8px;
+ --app-font: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
+ color-scheme: light dark;
+ }
+ @media (prefers-color-scheme: dark) {
+ :root {
+ --background: oklch(0.145 0 0);
+ --foreground: oklch(0.985 0 0);
+ --secondary: oklch(0.269 0 0);
+ --muted-foreground: oklch(0.708 0 0);
+ --border: oklch(0.269 0 0);
+ }
+ }
+ html, body { height: 100%; margin: 0; }
+ body { display: flex; flex-direction: column; font-family: var(--app-font); font-size: 14px; line-height: 1.5;
+ -webkit-font-smoothing: antialiased; background: var(--background); color: var(--foreground); }
+ header { display: flex; align-items: center; gap: 10px; height: 44px; padding: 0 10px 0 16px; flex: none;
+ box-sizing: border-box; user-select: none;
+ border-bottom: 1px solid color-mix(in srgb, var(--border) 68%, transparent);
+ background: color-mix(in srgb, var(--background) 94%, var(--secondary)); }
+ header .name { font-size: 14px; font-weight: 650; line-height: 1.25; color: var(--foreground);
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+ header .ver { color: var(--muted-foreground); font-size: 12px; line-height: 1.25; padding: 1px 8px;
+ border: 1px solid var(--border); border-radius: 999px; }
+ header .grow { flex: 1; }
+ header button { appearance: none; border: 1px solid var(--border); background: var(--background);
+ color: var(--foreground); border-radius: var(--radius-sm); padding: 5px 11px; font: inherit;
+ font-size: 13px; cursor: pointer; white-space: nowrap; }
+ header button:hover { background: var(--secondary); }
+ header .chat-btn[data-on="1"] { background: var(--brand-accent); border-color: var(--brand-accent); color: #fff; }
+ header .upd { display: none; border-color: color-mix(in srgb, var(--brand-accent) 45%, var(--border));
+ color: var(--brand-accent); font-weight: 600; }
+ header .upd.show { display: inline-block; }
+ header .hide-btn { border: none; background: none; color: var(--muted-foreground); font-size: 15px; padding: 5px 7px; }
+ header .hide-btn:hover { color: var(--foreground); background: none; }
+ main { display: flex; flex: 1; min-height: 0; }
+ #app { flex: 1; border: 0; width: 100%; height: 100%; background: var(--background); }
+ aside { display: none; flex: none; width: 420px; min-width: 320px; max-width: 70vw; position: relative;
+ border-left: 1px solid var(--border);
+ background: color-mix(in srgb, var(--secondary) 42%, var(--background)); }
+ aside.open { display: flex; }
+ aside .drag { position: absolute; left: -3px; top: 0; bottom: 0; width: 6px; cursor: col-resize; }
+ #chat { border: 0; flex: 1; width: 100%; height: 100%; }
+ #peek { position: fixed; top: 8px; right: 8px; z-index: 10; display: none; cursor: pointer;
+ border: 1px solid var(--border); background: color-mix(in srgb, var(--background) 88%, transparent);
+ color: var(--muted-foreground); border-radius: 999px; padding: 3px 11px;
+ font-family: var(--app-font); font-size: 12px; }
+ #peek:hover { color: var(--foreground); }
+ body.bare header, body.bare aside { display: none; }
+ body.bare #peek { display: block; }
+</style>
+</head>
+<body>
+<header>
+ <span class="name">${slug}</span>
+ <span class="ver" id="ver"></span>
+ <span class="grow"></span>
+ <button type="button" class="upd" id="upd">Updated &#8635; Reload</button>
+ <button type="button" class="chat-btn" id="chat-toggle">&#10022; Chat</button>
+ <button type="button" class="hide-btn" id="hide" title="Hide bar" aria-label="Hide bar">&#10005;</button>
+</header>
+<main>
+ <iframe id="app" src="${path}" title="${slug}"></iframe>
+ <aside id="panel"><div class="drag" id="drag"></div><iframe id="chat" title="Chat about ${slug}"></iframe></aside>
+</main>
+<button type="button" id="peek">${slug} &#9662;</button>
+<script>
+(() => {
+ if (window.top !== window.self) { document.body.className = "bare"; return; }
+ window.__qmAppShell = true;
+ const slug = ${JSON.stringify(opts.slug)};
+ const portal = ${JSON.stringify(opts.portalUrl.replace(/\/$/, ""))};
+ const app = document.getElementById("app");
+ const panel = document.getElementById("panel");
+ const chat = document.getElementById("chat");
+ const toggle = document.getElementById("chat-toggle");
+ const upd = document.getElementById("upd");
+ const verEl = document.getElementById("ver");
+ const peek = document.getElementById("peek");
+ const hide = document.getElementById("hide");
+ const drag = document.getElementById("drag");
+ const openKey = "qmChat:" + slug;
+
+ // --- chat panel ---
+ const setOpen = (on) => {
+ if (on && !chat.src) chat.src = portal + "/app-edit?slug=" + encodeURIComponent(slug) + "&embed=1";
+ panel.classList.toggle("open", on);
+ toggle.dataset.on = on ? "1" : "0";
+ try { localStorage.setItem(openKey, on ? "1" : "0"); } catch {}
+ };
+ toggle.addEventListener("click", () => setOpen(!panel.classList.contains("open")));
+ let wantOpen = false;
+ try { wantOpen = localStorage.getItem(openKey) === "1"; } catch {}
+ if (wantOpen) setOpen(true);
+
+ // --- panel resize ---
+ drag.addEventListener("pointerdown", (e) => {
+ e.preventDefault();
+ drag.setPointerCapture(e.pointerId);
+ app.style.pointerEvents = "none"; chat.style.pointerEvents = "none";
+ const move = (ev) => { panel.style.width = Math.max(320, window.innerWidth - ev.clientX) + "px"; };
+ const stop = () => {
+ drag.removeEventListener("pointermove", move);
+ app.style.pointerEvents = ""; chat.style.pointerEvents = "";
+ };
+ drag.addEventListener("pointermove", move);
+ drag.addEventListener("pointerup", stop, { once: true });
+ });
+
+ // --- hide / peek ---
+ hide.addEventListener("click", () => { document.body.className = "bare"; });
+ peek.addEventListener("click", () => { document.body.className = ""; });
+
+ // --- keep the address bar and title in step with the app ---
+ let lastHref = null;
+ const sync = () => {
+ try {
+ const loc = app.contentWindow.location;
+ if (loc.href === "about:blank" || loc.href === lastHref) return;
+ lastHref = loc.href;
+ history.replaceState(null, "", loc.pathname + loc.search + loc.hash);
+ const t = app.contentDocument && app.contentDocument.title;
+ document.title = t || slug;
+ } catch {}
+ };
+ setInterval(sync, 500);
+ app.addEventListener("load", sync);
+
+ // --- new-version handling ---
+ // Chat open = you're iterating and waiting on your own change: reload the app
+ // frame automatically (the chat column is untouched, so the thread survives).
+ // Chat closed = the update came from elsewhere: offer a pill, never yank the
+ // page out from under someone mid-interaction.
+ let base = null;
+ const reloadApp = (v) => {
+ base = v;
+ upd.classList.remove("show");
+ try { app.contentWindow.location.reload(); } catch { app.src = app.src; }
+ };
+ const poll = async () => {
+ if (document.hidden) return;
+ try {
+ const r = await fetch("/__claw__/version", { cache: "no-store" });
+ if (!r.ok) return;
+ const d = await r.json();
+ if (typeof d.version !== "number") return;
+ verEl.textContent = "v" + d.version;
+ if (base === null) base = d.version;
+ else if (d.version !== base) {
+ if (panel.classList.contains("open")) reloadApp(d.version);
+ else upd.classList.add("show");
+ }
+ } catch {}
+ };
+ void poll();
+ setInterval(poll, 5000);
+ upd.addEventListener("click", () => {
+ void fetch("/__claw__/version", { cache: "no-store" })
+ .then((r) => r.json())
+ .then((d) => reloadApp(typeof d.version === "number" ? d.version : base))
+ .catch(() => reloadApp(base));
+ });
+})();
+</script>
+</body>
+</html>
+`;
+}
diff --git a/src/deploy/edit-widget.ts b/src/deploy/edit-widget.ts
deleted file mode 100644
index df5adaf19..000000000
--- a/src/deploy/edit-widget.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-export const EDIT_WIDGET_PATH_PREFIX = "/__claw__/";
-
-export function editWidgetTag(portalUrl: string, slug: string): string {
- const esc = (value: string): string => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
- return `\n<script src="/__claw__/widget.js" defer data-portal="${esc(portalUrl)}" data-slug="${esc(slug)}"></script>`;
-}
-
-export const EDIT_WIDGET_JS = `(() => {
- const script = document.currentScript;
- if (!script || window.__clawEditWidget) return;
- window.__clawEditWidget = true;
- const portal = script.dataset.portal || "";
- const slug = script.dataset.slug || "";
- if (!portal || !slug) return;
-
- const host = document.createElement("div");
- const root = host.attachShadow({ mode: "closed" });
- const style = document.createElement("style");
- style.textContent = \`
- .bubble { position: fixed; right: 20px; bottom: 20px; z-index: 2147483646; width: 48px; height: 48px;
- border-radius: 50%; border: none; cursor: pointer; background: #111; color: #fff;
- box-shadow: 0 4px 16px rgba(0,0,0,.28); display: grid; place-items: center; font-size: 21px;
- transition: transform .15s ease; }
- .bubble:hover { transform: scale(1.08); }
- .panel { position: fixed; top: 0; right: 0; bottom: 0; width: min(420px, 92vw); z-index: 2147483647;
- background: #fff; box-shadow: -8px 0 28px rgba(0,0,0,.22); display: none; flex-direction: column; }
- .panel.open { display: flex; }
- .bar { display: flex; align-items: center; justify-content: space-between; padding: 8px 12px;
- background: #111; color: #fff; font: 13px/1.4 system-ui, sans-serif; }
- .bar button { background: none; border: none; color: #fff; font-size: 16px; cursor: pointer; }
- iframe { border: 0; flex: 1; width: 100%; }
- .reload { position: fixed; right: 84px; bottom: 28px; z-index: 2147483646; display: none;
- background: #111; color: #fff; border: none; border-radius: 8px; padding: 8px 12px;
- font: 13px system-ui, sans-serif; cursor: pointer; }
- .reload.show { display: block; }
- \`;
- const bubble = document.createElement("button");
- bubble.className = "bubble";
- bubble.type = "button";
- bubble.title = "Edit this app";
- bubble.setAttribute("aria-label", "Edit this app");
- bubble.textContent = "\\u270E";
- const panel = document.createElement("div");
- panel.className = "panel";
- const bar = document.createElement("div");
- bar.className = "bar";
- const title = document.createElement("span");
- title.textContent = "Editing " + slug;
- const close = document.createElement("button");
- close.type = "button";
- close.setAttribute("aria-label", "Close editor");
- close.textContent = "\\u2715";
- bar.append(title, close);
- panel.append(bar);
- const reload = document.createElement("button");
- reload.className = "reload";
- reload.type = "button";
- reload.textContent = "App updated \\u21BB reload";
- root.append(style, bubble, panel, reload);
-
- let frame = null;
- let baseVersion = null;
- let timer = null;
-
- const fetchVersion = async () => {
- try {
- const r = await fetch("/__claw__/version", { cache: "no-store" });
- if (!r.ok) return null;
- const d = await r.json();
- return typeof d.version === "number" ? d.version : null;
- } catch {
- return null;
- }
- };
-
- const poll = async () => {
- const v = await fetchVersion();
- if (v === null) return;
- if (baseVersion === null) baseVersion = v;
- else if (v !== baseVersion) reload.classList.add("show");
- };
-
- const open = () => {
- if (!frame) {
- frame = document.createElement("iframe");
- frame.src = portal.replace(/\\/$/, "") + "/app-edit?slug=" + encodeURIComponent(slug) + "&embed=1";
- panel.append(frame);
- }
- panel.classList.add("open");
- bubble.style.display = "none";
- void poll();
- if (!timer) timer = setInterval(poll, 4000);
- };
- const shut = () => {
- panel.classList.remove("open");
- bubble.style.display = "";
- if (timer) { clearInterval(timer); timer = null; }
- };
- bubble.addEventListener("click", open);
- close.addEventListener("click", shut);
- reload.addEventListener("click", () => location.reload());
-
- const mount = () => document.body && document.body.append(host);
- if (document.body) mount();
- else document.addEventListener("DOMContentLoaded", mount);
-})();
-`;
diff --git a/test/deploy-edit-widget.test.ts b/test/deploy-app-shell.test.ts
similarity index 74%
rename from test/deploy-edit-widget.test.ts
rename to test/deploy-app-shell.test.ts
index 6ebbd35a6..dd4ef6b49 100644
--- a/test/deploy-edit-widget.test.ts
+++ b/test/deploy-app-shell.test.ts
@@ -33,7 +33,7 @@ function appServingUpstream(upstreamPort: number) {
},
auditLog,
acl,
- deployDir: mkdtempSync(join(tmpdir(), "edit-widget-")),
+ deployDir: mkdtempSync(join(tmpdir(), "app-shell-")),
});
return createApp({
deploy,
@@ -109,7 +109,7 @@ const viewerCookie = () => `portal_session=${mintPortalSession("U-viewer")}`;
const ownerToken = (sub: string, expInMs = 60_000) =>
mintDeployOwnerToken(GATE_SECRET, { slug: "mysite", sub, exp: Date.now() + expInMs });
-test("edit widget: a valid owner link becomes a host-only cookie and turns on HTML injection", async () => {
+test("app shell: a valid owner link becomes a host-only cookie and turns on the shell", async () => {
const f = await widgetFixture();
try {
const token = await ownerToken("U1");
@@ -120,40 +120,80 @@ test("edit widget: a valid owner link becomes a host-only cookie and turns on HT
assert.match(setCookie, /HttpOnly/, "the owner cookie is HttpOnly");
assert.equal(swallow.headers.location, "/", "the redirect drops the token from the URL");
- const page = await httpGet(f.port, "/", { Host: HOST, Cookie: `dpl_owner=${token}` });
+ const page = await httpGet(f.port, "/", {
+ Host: HOST,
+ Cookie: `dpl_owner=${token}`,
+ "Sec-Fetch-Dest": "document",
+ });
assert.equal(page.status, 200);
- assert.match(page.body, /<html><body>APP<\/body><\/html>/, "the app's own HTML is intact");
- assert.match(page.body, /<script src="\/__claw__\/widget\.js" defer/, "the widget tag is appended");
- assert.match(page.body, new RegExp(`data-portal="${PORTAL}"`), "the widget knows the portal origin");
- assert.match(page.body, /data-slug="mysite"/, "the widget knows the app");
+ assert.match(page.body, /__qmAppShell/, "the owner's top-level document load gets the shell");
+ assert.match(page.body, /<iframe id="app" src="\/"/, "the app renders inside a same-origin frame");
+ assert.match(page.body, new RegExp(PORTAL.replace(/[/.]/g, "\\$&")), "the chat column knows the portal origin");
+ assert.doesNotMatch(page.body, /APP<\/body>/, "the shell is served without touching the upstream");
} finally {
await f.close();
}
});
-test("edit widget: a plain visitor (granted, signed in) gets untouched HTML and no widget endpoints", async () => {
+test("app shell: the frame's own load (sec-fetch-dest: iframe) proxies the app untouched", async () => {
const f = await widgetFixture();
try {
- const page = await httpGet(f.port, "/", { Host: HOST, Cookie: viewerCookie() });
+ const token = await ownerToken("U1");
+ const page = await httpGet(f.port, "/", {
+ Host: HOST,
+ Cookie: `dpl_owner=${token}`,
+ "Sec-Fetch-Dest": "iframe",
+ });
assert.equal(page.status, 200);
- assert.equal(page.body, "<html><body>APP</body></html>", "no injection for a non-owner");
+ assert.equal(page.body, "<html><body>APP</body></html>", "the app's own HTML is byte-identical");
+ } finally {
+ await f.close();
+ }
+});
- const js = await httpGet(f.port, "/__claw__/widget.js", { Host: HOST, Cookie: viewerCookie() });
- assert.doesNotMatch(js.body, /__clawEditWidget/, "the gateway serves no widget to non-owners");
+test("app shell: the frame src preserves the requested path and query", async () => {
+ const f = await widgetFixture();
+ try {
+ const token = await ownerToken("U1");
+ const page = await httpGet(f.port, "/reports/q3?tab=2", {
+ Host: HOST,
+ Cookie: `dpl_owner=${token}`,
+ "Sec-Fetch-Dest": "document",
+ });
+ assert.equal(page.status, 200);
+ assert.match(page.body, /<iframe id="app" src="\/reports\/q3\?tab=2"/, "deep links land inside the frame");
} finally {
await f.close();
}
});
-test("edit widget: owner endpoints serve the script and the applied version", async () => {
+test("app shell: a client without fetch metadata gets the raw app, never a nested shell", async () => {
const f = await widgetFixture();
try {
const token = await ownerToken("U1");
- const js = await httpGet(f.port, "/__claw__/widget.js", { Host: HOST, Cookie: `dpl_owner=${token}` });
- assert.equal(js.status, 200);
- assert.match(String(js.headers["content-type"]), /text\/javascript/);
- assert.match(js.body, /__clawEditWidget/, "the widget script is served");
+ const page = await httpGet(f.port, "/", { Host: HOST, Cookie: `dpl_owner=${token}` });
+ assert.equal(page.status, 200);
+ assert.equal(page.body, "<html><body>APP</body></html>", "no sec-fetch-dest means a straight proxy");
+ } finally {
+ await f.close();
+ }
+});
+
+test("app shell: a plain visitor (granted, signed in) gets untouched HTML and no shell endpoints", async () => {
+ const f = await widgetFixture();
+ try {
+ const page = await httpGet(f.port, "/", { Host: HOST, Cookie: viewerCookie(), "Sec-Fetch-Dest": "document" });
+ assert.equal(page.status, 200);
+ assert.equal(page.body, "<html><body>APP</body></html>", "no shell for a non-owner");
+ } finally {
+ await f.close();
+ }
+});
+test("app shell: the owner version endpoint reports the applied version", async () => {
+ const f = await widgetFixture();
+ try {
+ const token = await ownerToken("U1");
const version = await httpGet(f.port, "/__claw__/version", { Host: HOST, Cookie: `dpl_owner=${token}` });
assert.equal(version.status, 200);
assert.equal(JSON.parse(version.body).version, 1, "the applied version is reported");
@@ -162,7 +202,7 @@ test("edit widget: owner endpoints serve the script and the applied version", as
}
});
-test("edit widget: an owner's XHR/fetch HTML fragment is not injected (sec-fetch-dest gate)", async () => {
+test("app shell: an owner's XHR/fetch HTML fragment is not shelled (sec-fetch-dest gate)", async () => {
const f = await widgetFixture();
try {
const token = await ownerToken("U1");
@@ -172,20 +212,20 @@ test("edit widget: an owner's XHR/fetch HTML fragment is not injected (sec-fetch
"Sec-Fetch-Dest": "empty",
});
assert.equal(frag.status, 200);
- assert.doesNotMatch(frag.body, /__claw__\/widget\.js/, "a non-document HTML load is left untouched");
+ assert.doesNotMatch(frag.body, /__qmAppShell/, "a non-document HTML load is left untouched");
} finally {
await f.close();
}
});
-test("edit widget: a 206 partial HTML response is not injected", async () => {
+test("app shell: a 206 partial HTML response streams byte-exact through the frame", async () => {
const f = await widgetFixture((_req, res) => {
res.writeHead(206, { "content-type": "text/html", "content-range": "bytes 0-9/32" });
res.end("<html></h");
});
try {
const token = await ownerToken("U1");
- const r = await httpGet(f.port, "/", { Host: HOST, Cookie: `dpl_owner=${token}` });
+ const r = await httpGet(f.port, "/", { Host: HOST, Cookie: `dpl_owner=${token}`, "Sec-Fetch-Dest": "iframe" });
assert.equal(r.status, 206);
assert.equal(r.body, "<html></h", "a range slice stays byte-exact");
} finally {
@@ -193,7 +233,7 @@ test("edit widget: a 206 partial HTML response is not injected", async () => {
}
});
-test("edit widget: a non-owner request to /__claw__/ falls through to the app, not a gateway 404", async () => {
+test("app shell: a non-owner request to /__claw__/ falls through to the app, not a gateway 404", async () => {
const f = await widgetFixture((req, res) => {
res.writeHead(200, { "content-type": "text/plain" });
res.end(`APP SAW ${req.url}`);
@@ -207,7 +247,7 @@ test("edit widget: a non-owner request to /__claw__/ falls through to the app, n
}
});
-test("edit widget: an owner token for someone who cannot manage the app grants nothing", async () => {
+test("app shell: an owner token for someone who cannot manage the app grants nothing", async () => {
const f = await widgetFixture();
try {
const forged = await ownerToken("U-stranger");
@@ -215,15 +255,19 @@ test("edit widget: an owner token for someone who cannot manage the app grants n
assert.equal(swallow.status, 401, "a non-manager's owner token leaves them an anonymous visitor");
assert.equal(swallow.headers["set-cookie"], undefined, "no owner cookie for a non-manager");
- const page = await httpGet(f.port, "/", { Host: HOST, Cookie: `dpl_owner=${forged}; ${viewerCookie()}` });
+ const page = await httpGet(f.port, "/", {
+ Host: HOST,
+ Cookie: `dpl_owner=${forged}; ${viewerCookie()}`,
+ "Sec-Fetch-Dest": "document",
+ });
assert.equal(page.status, 200, "the visitor's own grant still admits them");
- assert.doesNotMatch(page.body, /__claw__\/widget\.js/, "a forged owner cookie injects no widget");
+ assert.doesNotMatch(page.body, /__qmAppShell/, "a forged owner cookie raises no shell");
} finally {
await f.close();
}
});
-test("edit widget: an expired owner token is rejected", async () => {
+test("app shell: an expired owner token is rejected", async () => {
const f = await widgetFixture();
try {
const expired = await ownerToken("U1", -1);
@@ -234,7 +278,7 @@ test("edit widget: an expired owner token is rejected", async () => {
}
});
-test("edit widget: non-HTML responses stream through untouched even for the owner", async () => {
+test("app shell: non-HTML responses stream through untouched even for the owner", async () => {
const f = await widgetFixture((_req, res) => {
res.writeHead(200, { "content-type": "application/json", "content-length": "13" });
res.end('{"data":true}');
@@ -244,31 +288,13 @@ test("edit widget: non-HTML responses stream through untouched even for the owne
const r = await httpGet(f.port, "/api/data", { Host: HOST, Cookie: `dpl_owner=${token}` });
assert.equal(r.status, 200);
assert.equal(r.body, '{"data":true}', "JSON is byte-identical");
- assert.equal(r.headers["content-length"], "13", "content-length survives when nothing is injected");
- } finally {
- await f.close();
- }
-});
-
-test("edit widget: injection drops the stale content-length so the page still parses", async () => {
- const html = "<html><body>SIZED</body></html>";
- const f = await widgetFixture((_req, res) => {
- res.writeHead(200, { "content-type": "text/html", "content-length": String(html.length) });
- res.end(html);
- });
- try {
- const token = await ownerToken("U1");
- const r = await httpGet(f.port, "/", { Host: HOST, Cookie: `dpl_owner=${token}` });
- assert.equal(r.status, 200);
- assert.match(r.body, /SIZED/);
- assert.match(r.body, /__claw__\/widget\.js/);
- assert.equal(r.headers["content-length"], undefined, "the now-wrong content-length is dropped");
+ assert.equal(r.headers["content-length"], "13", "content-length survives the proxy");
} finally {
await f.close();
}
});
-test("edit widget: an app cannot plant the owner cookie on its visitors", async () => {
+test("app shell: an app cannot plant the owner cookie on its visitors", async () => {
const f = await widgetFixture((_req, res) => {
res.writeHead(200, {
"content-type": "text/html",