Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Let a deployed app opt into being framed by named origins (#1503)

Tom Firthf75cfd1c27e1
diff --git a/plugins/portal/src/index.ts b/plugins/portal/src/index.ts
index c8e7efd15..84cf5a7b9 100644
--- a/plugins/portal/src/index.ts
+++ b/plugins/portal/src/index.ts
@@ -843,15 +843,26 @@ function loginProviderCookie(sub: string): string[] {
];
}
+const FRAME_SESSION_COOKIE = "portal_session_x";
+
function sessionCookieSet(value: string, sub: string): string[] {
- const set = setCookie("portal_session", value, {
+ const attrs = {
path: "/",
maxAge: SESSION_TTL_S,
secure: SECURE_COOKIES,
...(COOKIE_DOMAIN ? { domain: COOKIE_DOMAIN } : {}),
- });
+ };
+ const set = setCookie("portal_session", value, attrs);
+ const framed = setCookie(FRAME_SESSION_COOKIE, value, { ...attrs, sameSite: "None" });
return [
- ...(COOKIE_DOMAIN ? [set, clearCookie("portal_session", "/", SECURE_COOKIES)] : [set]),
+ ...(COOKIE_DOMAIN
+ ? [
+ set,
+ framed,
+ clearCookie("portal_session", "/", SECURE_COOKIES),
+ clearCookie(FRAME_SESSION_COOKIE, "/", SECURE_COOKIES),
+ ]
+ : [set, framed]),
...loginProviderCookie(sub),
];
}
@@ -1030,7 +1041,10 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>
setSession(res, [
...(signedOutSession ? loginProviderCookie(signedOutSession.sub) : []),
clearCookie("portal_session", "/", SECURE_COOKIES, COOKIE_DOMAIN),
- ...(COOKIE_DOMAIN ? [clearCookie("portal_session", "/", SECURE_COOKIES)] : []),
+ clearCookie(FRAME_SESSION_COOKIE, "/", SECURE_COOKIES, COOKIE_DOMAIN),
+ ...(COOKIE_DOMAIN
+ ? [clearCookie("portal_session", "/", SECURE_COOKIES), clearCookie(FRAME_SESSION_COOKIE, "/", SECURE_COOKIES)]
+ : []),
clearCookie("portal_oidc_tmp", "/auth", SECURE_COOKIES),
...(AUTH_BROKER_UPSTREAM ? [clearCookie("qm_idp_session", AUTH_BROKER_PREFIX, true)] : []),
...(LOCAL_AUTH_BYPASS && isLoopbackAddress(req.socket.remoteAddress)
diff --git a/plugins/portal/src/session.ts b/plugins/portal/src/session.ts
index f04856f6f..7ce263880 100644
--- a/plugins/portal/src/session.ts
+++ b/plugins/portal/src/session.ts
@@ -110,10 +110,17 @@ export interface CookieOpts {
maxAge?: number;
secure: boolean;
domain?: string;
+ sameSite?: "Lax" | "None";
}
export function setCookie(name: string, value: string, opts: CookieOpts): string {
- const parts = [`${name}=${encodeURIComponent(value)}`, "HttpOnly", "SameSite=Lax", `Path=${opts.path ?? "/"}`];
+ const sameSite = opts.sameSite === "None" && opts.secure ? "None" : "Lax";
+ const parts = [
+ `${name}=${encodeURIComponent(value)}`,
+ "HttpOnly",
+ `SameSite=${sameSite}`,
+ `Path=${opts.path ?? "/"}`,
+ ];
if (opts.domain) parts.push(`Domain=${opts.domain}`);
if (opts.secure) parts.push("Secure");
if (opts.maxAge !== undefined) parts.push(`Max-Age=${opts.maxAge}`);
diff --git a/plugins/portal/test/session.test.ts b/plugins/portal/test/session.test.ts
index 403313866..b04b131ae 100644
--- a/plugins/portal/test/session.test.ts
+++ b/plugins/portal/test/session.test.ts
@@ -174,6 +174,15 @@ test("cookie helpers set HttpOnly/SameSite/Path and Secure only when asked", ()
assert.match(clearCookie("portal_session", "/", true), /Max-Age=0/);
});
+test("a cross-site cookie is only emitted when it is also Secure", () => {
+ const crossSite = setCookie("portal_session_x", "v", { path: "/", maxAge: 100, secure: true, sameSite: "None" });
+ assert.match(crossSite, /SameSite=None/);
+ assert.match(crossSite, /Secure/);
+ const insecure = setCookie("portal_session_x", "v", { path: "/", maxAge: 100, secure: false, sameSite: "None" });
+ assert.match(insecure, /SameSite=Lax/);
+ assert.ok(!insecure.includes("Secure"));
+});
+
test("readCookie extracts a named cookie and survives other pairs", () => {
const header = "a=1; portal_session=abc.def; webuiuser=EVIL";
assert.equal(readCookie(header, "portal_session"), "abc.def");
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.ts
index 45baf6b9a..d177ed7b3 100644
--- a/plugins/web-ui/server/index.ts
+++ b/plugins/web-ui/server/index.ts
@@ -2268,6 +2268,24 @@ const apiRoutes: readonly WebRoute[] = [
return relayCore(res, "POST", `/v1/deployments/${encodeURIComponent(id)}/name`, JSON.stringify({ name }));
},
},
+ {
+ method: "POST",
+ path: "/api/deployments/:id/embed-ancestors",
+ handle: async (c) => {
+ const { req, res, user } = c;
+ const id = c.params.id!;
+ if (!(await gateManageDeployment(res, user, id))) return;
+ const p = await readJson<{ embedAncestors?: unknown }>(req, res, false);
+ if (!p) return;
+ const embedAncestors = Array.isArray(p.embedAncestors) ? p.embedAncestors : [];
+ return relayCore(
+ res,
+ "POST",
+ `/v1/deployments/${encodeURIComponent(id)}/embed-ancestors`,
+ JSON.stringify({ embedAncestors }),
+ );
+ },
+ },
{
method: "POST",
path: "/api/deployments/:id/archive",
diff --git a/plugins/web-ui/src/deploy-view.ts b/plugins/web-ui/src/deploy-view.ts
index 9c4025233..4e6dc2a10 100644
--- a/plugins/web-ui/src/deploy-view.ts
+++ b/plugins/web-ui/src/deploy-view.ts
@@ -18,6 +18,7 @@ export interface DeploymentView {
name?: string;
displayName?: string;
permission?: "read" | "write";
+ embedAncestors?: string[];
createdAt?: number;
updatedAt?: number;
lastAccessAt?: number;
diff --git a/plugins/web-ui/src/deploys.ts b/plugins/web-ui/src/deploys.ts
index 77fc969d8..d0ee5c7a7 100644
--- a/plugins/web-ui/src/deploys.ts
+++ b/plugins/web-ui/src/deploys.ts
@@ -1,7 +1,7 @@
import { openDeploymentPermissions } from "./deploy-permissions";
import { html, nothing, render, type TemplateResult } from "lit";
import { live } from "lit/directives/live.js";
-import { Archive, Check, Copy, ExternalLink, RotateCcw, X } from "lucide";
+import { Archive, Check, Copy, ExternalLink, Plus, RotateCcw, Trash2, X } from "lucide";
import { api, withBase } from "./core-bridge";
import { errMessage } from "../../chassis/src/errors";
import { copyText, icon, relTime } from "./ui";
@@ -44,6 +44,14 @@ const DEPLOY_TABS: Array<{ value: DeploymentTab; label: string }> = [
{ value: "archived", label: "Archived" },
];
+type DeployEditField = "displayName" | "name" | "embedAncestors";
+
+const DEPLOY_EDIT_FIELDS: Record<DeployEditField, { endpoint: string; savedValue: (d: DeploymentView) => string }> = {
+ displayName: { endpoint: "display-name", savedValue: (d) => d.displayName ?? "" },
+ name: { endpoint: "name", savedValue: (d) => d.name ?? "" },
+ embedAncestors: { endpoint: "embed-ancestors", savedValue: (d) => (d.embedAncestors ?? []).join("\n") },
+};
+
let deployList: DeploymentView[] = [];
let deployNotices: DeploymentNotices = { list: "", detail: null };
let deployLoading = false;
@@ -53,8 +61,9 @@ let deployTab: DeploymentTab = "yours";
let deployPageHost: HTMLElement | null = null;
let activeDeploy: DeploymentView | null = null;
let visibleVersionCount = 10;
-let editingDeploy: { id: string; field: "displayName" | "name" } | null = null;
+let editingDeploy: { id: string; field: DeployEditField } | null = null;
let deployDraft = "";
+let embedDraft: string[] = [];
let deploySaving = false;
let archiveCandidate: DeploymentView | null = null;
let restoreArchiveFocus = false;
@@ -264,6 +273,7 @@ function drawDeployDetail(d: DeploymentView, loading = false): void {
const contextScope = deploymentContextScope(d);
const editingName = editingDeploy?.id === d.id && editingDeploy.field === "displayName";
const editingSlug = editingDeploy?.id === d.id && editingDeploy.field === "name";
+ const editingEmbed = editingDeploy?.id === d.id && editingDeploy.field === "embedAncestors";
render(
html`
<div class="resource-detail deploy-detail">
@@ -310,6 +320,25 @@ function drawDeployDetail(d: DeploymentView, loading = false): void {
<div><strong>App URL</strong><span>Changes the app URL. Existing links do not redirect.</span></div>
${editingSlug ? deployEditForm(d, "name") : html`<div class="deploy-setting-value"><code>/d/${deploymentSlug(d)}/</code><button class="btn" type="button" @click=${() => startEditDeploy(d, "name")}>Change</button></div>`}
</div>
+ <div class="deploy-setting-row">
+ <div>
+ <strong>Embedding</strong
+ ><span
+ >Sites allowed to show this app inside their own page. Every frame between the app and the browser
+ tab must be listed.</span
+ >
+ </div>
+ ${
+ editingEmbed
+ ? deployEditForm(d, "embedAncestors")
+ : html`<div class="deploy-setting-value">
+ ${embedAncestorsSummary(d)}
+ <button class="btn" type="button" @click=${() => startEditDeploy(d, "embedAncestors")}>
+ ${d.embedAncestors?.length ? "Change" : "Allow"}
+ </button>
+ </div>`
+ }
+ </div>
<div class="actions deploy-danger-actions">
${
d.status === "archived"
@@ -383,7 +412,23 @@ function returnToDeploysList(): void {
drawDeploysPage();
}
-function deployEditForm(d: DeploymentView, field: "displayName" | "name"): TemplateResult {
+function cleanEmbedDraft(rows: readonly string[]): string[] {
+ const seen = new Set<string>();
+ for (const row of rows) {
+ const value = row.trim();
+ if (value) seen.add(value);
+ }
+ return [...seen];
+}
+
+function embedAncestorsSummary(d: DeploymentView): TemplateResult {
+ const origins = d.embedAncestors ?? [];
+ if (!origins.length) return html`<span class="deploy-embed-empty">Not embeddable</span>`;
+ return html`<span class="deploy-embed-origins">${origins.map((origin) => html`<code>${origin}</code>`)}</span>`;
+}
+
+function deployEditForm(d: DeploymentView, field: DeployEditField): TemplateResult {
+ if (field === "embedAncestors") return deployEmbedForm(d);
const slug = field === "name";
return html`
<form
@@ -424,9 +469,95 @@ function deployEditForm(d: DeploymentView, field: "displayName" | "name"): Templ
`;
}
-function startEditDeploy(d: DeploymentView, field: "displayName" | "name"): void {
+function deployEmbedForm(d: DeploymentView): TemplateResult {
+ const setRow = (index: number, value: string) => {
+ embedDraft = embedDraft.map((row, i) => (i === index ? value : row));
+ };
+ const removeRow = (index: number) => {
+ embedDraft = embedDraft.filter((_, i) => i !== index);
+ if (!embedDraft.length) embedDraft = [""];
+ drawDeployDetail(d);
+ focusEmbedRow(Math.min(index, embedDraft.length - 1));
+ };
+ const addRow = () => {
+ embedDraft = [...embedDraft, ""];
+ drawDeployDetail(d);
+ focusEmbedRow(embedDraft.length - 1);
+ };
+ return html`
+ <form
+ class="deploy-embed-editor"
+ @submit=${(event: SubmitEvent) => {
+ event.preventDefault();
+ void commitEditDeploy(d);
+ }}
+ >
+ <ul class="deploy-embed-list">
+ ${embedDraft.map(
+ (row, index) => html`
+ <li>
+ <input
+ class="deploy-edit-input deploy-embed-input"
+ data-embed-row=${index}
+ aria-label="Site allowed to embed this app"
+ spellcheck="false"
+ placeholder="https://tools.example.com"
+ ?disabled=${deploySaving}
+ .value=${live(row)}
+ @input=${(event: InputEvent) => setRow(index, (event.currentTarget as HTMLInputElement).value)}
+ @keydown=${(event: KeyboardEvent) => event.key === "Escape" && cancelEditDeploy()}
+ />
+ <button
+ class="icon-btn"
+ type="button"
+ ${tip("Remove")}
+ aria-label="Remove this site"
+ ?disabled=${deploySaving}
+ @click=${() => removeRow(index)}
+ >
+ ${icon(Trash2, 14)}
+ </button>
+ </li>
+ `,
+ )}
+ </ul>
+ <div class="deploy-embed-actions">
+ <button class="btn" type="button" ?disabled=${deploySaving} @click=${addRow}>
+ ${icon(Plus, 14)}<span>Add site</span>
+ </button>
+ <span class="spacer"></span>
+ <button class="icon-btn" type="submit" aria-label="Save" ${tip("Save")} ?disabled=${deploySaving}>
+ ${icon(Check, 14)}
+ </button>
+ <button
+ class="icon-btn"
+ type="button"
+ ${tip("Cancel")}
+ aria-label="Cancel"
+ ?disabled=${deploySaving}
+ @click=${cancelEditDeploy}
+ >
+ ${icon(X, 14)}
+ </button>
+ </div>
+ <div class="hint deploy-embed-hint">
+ An https origin each, e.g. <code>https://tools.example.com</code> or <code>https://*.example.com</code>. Save
+ with none listed to forbid embedding again.
+ </div>
+ </form>
+ `;
+}
+
+function focusEmbedRow(index: number): void {
+ requestAnimationFrame(() => {
+ document.querySelector<HTMLInputElement>(`[data-embed-row="${index}"]`)?.focus();
+ });
+}
+
+function startEditDeploy(d: DeploymentView, field: DeployEditField): void {
editingDeploy = { id: d.id, field };
- deployDraft = field === "displayName" ? (d.displayName ?? "") : (d.name ?? "");
+ if (field === "embedAncestors") embedDraft = [...(d.embedAncestors ?? []), ""];
+ else deployDraft = DEPLOY_EDIT_FIELDS[field].savedValue(d);
deployNotices = withoutDeploymentDetailNotice(deployNotices);
drawDeployDetail(d);
requestAnimationFrame(() => {
@@ -439,6 +570,7 @@ function startEditDeploy(d: DeploymentView, field: "displayName" | "name"): void
function cancelEditDeploy(): void {
editingDeploy = null;
deployDraft = "";
+ embedDraft = [];
if (activeDeploy) drawDeployDetail(activeDeploy);
else drawDeploysPage();
}
@@ -447,8 +579,10 @@ async function commitEditDeploy(d: DeploymentView): Promise<void> {
if (!editingDeploy || deploySaving) return;
const field = editingDeploy.field;
const value = deployDraft.trim();
- const current = field === "displayName" ? (d.displayName ?? "") : (d.name ?? "");
- if (value === current) return cancelEditDeploy();
+ const embedAncestors = field === "embedAncestors" ? cleanEmbedDraft(embedDraft) : [];
+ const current = DEPLOY_EDIT_FIELDS[field].savedValue(d);
+ const next = field === "embedAncestors" ? embedAncestors.join("\n") : value;
+ if (next === current) return cancelEditDeploy();
if (field === "name" && !value) {
deployNotices = withDeploymentDetailNotice(deployNotices, d.id, "A URL slug is required.");
return drawDeployDetail(d);
@@ -456,14 +590,20 @@ async function commitEditDeploy(d: DeploymentView): Promise<void> {
deploySaving = true;
drawDeployDetail(d);
try {
- const endpoint = field === "displayName" ? "display-name" : "name";
- const payload = field === "displayName" ? { displayName: value } : { name: value };
+ const { endpoint } = DEPLOY_EDIT_FIELDS[field];
+ const payloads: Record<DeployEditField, object> = {
+ displayName: { displayName: value },
+ name: { name: value },
+ embedAncestors: { embedAncestors },
+ };
+ const payload = payloads[field];
await api(`/api/deployments/${encodeURIComponent(d.id)}/${endpoint}`, {
method: "POST",
body: JSON.stringify(payload),
});
editingDeploy = null;
deployDraft = "";
+ embedDraft = [];
deploySaving = false;
await refreshDeployments();
const updated = deployList.find((item) => item.id === d.id) ?? d;
diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.css
index 538dccedb..b7cb2405c 100644
--- a/plugins/web-ui/src/shell.css
+++ b/plugins/web-ui/src/shell.css
@@ -7505,6 +7505,63 @@ a.connector-widget:focus-visible {
justify-content: flex-end;
gap: 5px;
}
+.deploy-embed-origins {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: flex-end;
+ gap: 4px 6px;
+ min-width: 0;
+}
+.deploy-embed-origins code {
+ padding: 1px 6px;
+ border: 1px solid color-mix(in srgb, var(--border) 70%, transparent);
+ border-radius: 999px;
+ font-size: 12px;
+ white-space: nowrap;
+}
+.deploy-embed-empty {
+ color: var(--muted-foreground);
+}
+.deploy-embed-editor {
+ grid-column: 1 / -1;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+.deploy-embed-list {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+.deploy-embed-list li {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+}
+.deploy-embed-input {
+ flex: 1;
+ min-width: 0;
+ font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
+ font-size: 12px;
+}
+.deploy-embed-actions {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+}
+.deploy-embed-actions .spacer {
+ flex: 1;
+}
+.deploy-embed-hint {
+ font-size: 12px;
+}
+.deploy-embed-hint code {
+ font-size: 11px;
+}
+
.deploy-edit-form label {
min-width: 0;
}
diff --git a/plugins/web-ui/test/deployments-server-route.test.ts b/plugins/web-ui/test/deployments-server-route.test.ts
index bf627ef87..03b4906b8 100644
--- a/plugins/web-ui/test/deployments-server-route.test.ts
+++ b/plugins/web-ui/test/deployments-server-route.test.ts
@@ -120,3 +120,44 @@ test("deployment sharing uses the signed-in capability and drops caller identity
assert.ok(requests.every((call) => call.capability === "signed-in-user-capability"));
assert.deepEqual(requests[1]?.body, { scope: "personal:bob", access: "view" });
});
+
+test("embed-ancestors relays the origin list and never invents one", async () => {
+ let before = calls.length;
+ const saved = await fetch(`${base}/api/deployments/d1/embed-ancestors`, {
+ method: "POST",
+ headers,
+ body: JSON.stringify({ embedAncestors: ["https://tools.example.com", "https://*.example.com"] }),
+ });
+ assert.equal(saved.status, 200);
+ const savedCall = calls
+ .slice(before)
+ .find((call) => call.method === "POST" && isNoncedCoreCall(call.url, "/v1/deployments/d1/embed-ancestors"));
+ assert.deepEqual(savedCall?.body, { embedAncestors: ["https://tools.example.com", "https://*.example.com"] });
+
+ before = calls.length;
+ assert.equal(
+ (
+ await fetch(`${base}/api/deployments/d1/embed-ancestors`, {
+ method: "POST",
+ headers,
+ body: JSON.stringify({ embedAncestors: [] }),
+ })
+ ).status,
+ 200,
+ );
+ const clearedCall = calls
+ .slice(before)
+ .find((call) => call.method === "POST" && isNoncedCoreCall(call.url, "/v1/deployments/d1/embed-ancestors"));
+ assert.deepEqual(clearedCall?.body, { embedAncestors: [] });
+
+ before = calls.length;
+ await fetch(`${base}/api/deployments/d1/embed-ancestors`, {
+ method: "POST",
+ headers,
+ body: JSON.stringify({ embedAncestors: "https://tools.example.com" }),
+ });
+ const coercedCall = calls
+ .slice(before)
+ .find((call) => call.method === "POST" && isNoncedCoreCall(call.url, "/v1/deployments/d1/embed-ancestors"));
+ assert.deepEqual(coercedCall?.body, { embedAncestors: [] });
+});
diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.ts
index 74d995886..4775ac0cd 100644
--- a/src/api/agent-api-catalog.ts
+++ b/src/api/agent-api-catalog.ts
@@ -459,9 +459,10 @@ const FAMILIES: AgentApiFamily[] = [
(m === "GET" && /^\/v1\/deployments\/[^/]+\/fetch$/.test(p)) ||
(m === "GET" && /^\/v1\/deployments\/[^/]+\/logs$/.test(p)) ||
(m === "GET" && /^\/v1\/deployments\/[^/]+\/(git-url|share)$/.test(p)) ||
- (m === "POST" && /^\/v1\/deployments\/[^/]+\/(share|archive|restore|name|display-name|always-on)$/.test(p)),
+ (m === "POST" &&
+ /^\/v1\/deployments\/[^/]+\/(share|archive|restore|name|display-name|always-on|embed-ancestors)$/.test(p)),
guidance:
- 'To see the published apps you can reach across scopes, GET /v1/deployments (each row carries your permission and a clone/push gitUrl). Read what an app renders as the asking person with GET /v1/deployments/:id/fetch. A published app (`apps` action `publish`) is reachable only by its owner plus whoever the owner shares it with. To widen or narrow that — "share it with everyone" or "share it with <teammate>" — POST /v1/deployments/:id/share with `scope:"org"` or `recipient:"<name>"`; no redeploy. To rename or take down an app, use name / display-name / archive. POST /v1/deployments/:id/always-on with `{alwaysOn:true|false}` keeps an app permanently warm (no idle cold starts) or returns it to sleep-when-idle. Anyone who manages the app can change these: its owner from any conversation, a current member of the channel/team it was published from, or someone granted "manage" access.',
+ 'To see the published apps you can reach across scopes, GET /v1/deployments (each row carries your permission and a clone/push gitUrl). Read what an app renders as the asking person with GET /v1/deployments/:id/fetch. A published app (`apps` action `publish`) is reachable only by its owner plus whoever the owner shares it with. To widen or narrow that — "share it with everyone" or "share it with <teammate>" — POST /v1/deployments/:id/share with `scope:"org"` or `recipient:"<name>"`; no redeploy. To rename or take down an app, use name / display-name / archive. POST /v1/deployments/:id/always-on with `{alwaysOn:true|false}` keeps an app permanently warm (no idle cold starts) or returns it to sleep-when-idle. POST /v1/deployments/:id/embed-ancestors with `{embedAncestors:["https://tools.example.com", ...]}` lets those sites show the app inside their own page (an iframe); list every frame between the app and the browser tab, and pass `[]` to forbid embedding again. Anyone who manages the app can change these: its owner from any conversation, a current member of the channel/team it was published from, or someone granted "manage" access.',
routes: [
{
method: "GET",
@@ -520,6 +521,12 @@ const FAMILIES: AgentApiFamily[] = [
summary:
"keep an app you manage permanently warm — body {alwaysOn:true} exempts it from idle sleep so visitors never hit a cold start; {alwaysOn:false} returns it to the default sleep-when-idle",
},
+ {
+ method: "POST",
+ path: "/v1/deployments/:id/embed-ancestors",
+ summary:
+ "let named sites show an app you manage inside their page (iframe) — body {embedAncestors:[https origins, optionally https://*.example.com]}; list every frame between the app and the browser tab; [] forbids embedding again",
+ },
{
method: "POST",
path: "/v1/deployments/:id/archive",
diff --git a/src/api/app-deployments.ts b/src/api/app-deployments.ts
index 43aa295f2..c0790fda8 100644
--- a/src/api/app-deployments.ts
+++ b/src/api/app-deployments.ts
@@ -26,6 +26,7 @@ export function createDeploymentMethods(
| "renameDeployment"
| "setDeploymentDisplayName"
| "setDeploymentAlwaysOn"
+ | "setDeploymentEmbedAncestors"
| "keepAlwaysOnWarm"
| "reachDeployment"
| "deploymentLogsFor"
@@ -97,6 +98,9 @@ export function createDeploymentMethods(
setDeploymentAlwaysOn(id, alwaysOn) {
return deps.deploy.setDeploymentAlwaysOn(id, alwaysOn);
},
+ setDeploymentEmbedAncestors(id, embedAncestors) {
+ return deps.deploy.setDeploymentEmbedAncestors(id, embedAncestors);
+ },
keepAlwaysOnWarm() {
return deps.deploy.keepAlwaysOnWarm();
},
diff --git a/src/api/app-types.ts b/src/api/app-types.ts
index 71a3a30bd..32752f3fe 100644
--- a/src/api/app-types.ts
+++ b/src/api/app-types.ts
@@ -129,6 +129,7 @@ export interface DeploymentView {
appliedVersion?: number;
status: Deployment["status"];
alwaysOn?: boolean;
+ embedAncestors?: string[];
lastAccessAt?: number;
createdAt?: number;
updatedAt?: number;
@@ -157,6 +158,7 @@ export function deploymentView(d: Deployment): DeploymentView {
...(d.appliedVersion !== undefined ? { appliedVersion: d.appliedVersion } : {}),
status: d.status,
...(d.alwaysOn ? { alwaysOn: true } : {}),
+ ...(d.embedAncestors?.length ? { embedAncestors: d.embedAncestors } : {}),
...(d.lastAccessAt !== undefined ? { lastAccessAt: d.lastAccessAt } : {}),
...(versions[0] ? { createdAt: versions[0].createdAt } : {}),
...(versions.at(-1) ? { updatedAt: versions.at(-1)!.createdAt } : {}),
@@ -557,6 +559,7 @@ export interface App {
renameDeployment(id: string, name: string): Promise<Deployment>;
setDeploymentDisplayName(id: string, displayName: string): Promise<Deployment>;
setDeploymentAlwaysOn(id: string, alwaysOn: boolean): Promise<Deployment>;
+ setDeploymentEmbedAncestors(id: string, embedAncestors: string[]): Promise<Deployment>;
keepAlwaysOnWarm(): Promise<number>;
reachDeployment(id: string, principalId: string, opts?: ReachOptions): Promise<Reach>;
deploymentLogsFor(
diff --git a/src/api/routes/deployments.ts b/src/api/routes/deployments.ts
index 2010f11ab..3e197f07b 100644
--- a/src/api/routes/deployments.ts
+++ b/src/api/routes/deployments.ts
@@ -22,7 +22,8 @@ import { resolveShareTarget as resolveShareTargetGrammar } from "../artifact-sha
import { verifyDeployGitAccess, viewerIdentityKey } from "../../deploy/access-token.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 { FRAME_SESSION_COOKIE, portalSessionSub, portalSessionSubFrom } from "../../deploy/viewer-session.ts";
+import { EMBED_ANCESTORS_HINT, parseEmbedAncestors } from "../../deploy/embed-ancestors.ts";
import { proxyHeaders } from "../../util/http-proxy.ts";
function deploymentProxyAgent(port?: number): { agent?: SocksProxyAgent } {
@@ -198,7 +199,7 @@ function forwardableHeaders(req: BaseCtx["req"]): Record<string, string | string
const kept = String(out.cookie ?? "")
.split(";")
.map((part) => part.trim())
- .filter((part) => part && !/^(?:dpl_access|dpl_owner|portal_session)\s*=/.test(part));
+ .filter((part) => part && !/^(?:dpl_access|dpl_owner|portal_session|portal_session_x)\s*=/.test(part));
if (kept.length) out.cookie = kept.join("; ");
else delete out.cookie;
return out;
@@ -206,9 +207,19 @@ function forwardableHeaders(req: BaseCtx["req"]): Record<string, string | string
const APP_SANDBOX_CSP = "sandbox allow-scripts allow-forms allow-popups allow-modals allow-downloads";
+function frameAncestorsDirective(ancestors: readonly string[]): string {
+ return `frame-ancestors 'self' ${ancestors.join(" ")}`;
+}
+
+function cspMentionsFrameAncestors(value: string | string[] | undefined): boolean {
+ if (!value) return false;
+ return (Array.isArray(value) ? value : [value]).some((v) => /frame-ancestors/i.test(v));
+}
+
function gatewaySafeResponseHeaders(
headers: Record<string, string | string[] | number | undefined>,
sandbox = false,
+ frameAncestors?: readonly string[],
): Record<string, string | string[]> {
const normalized: Record<string, string | string[] | undefined> = {};
for (const [rawName, value] of Object.entries(headers)) {
@@ -220,7 +231,9 @@ function gatewaySafeResponseHeaders(
const cookies = out["set-cookie"];
if (cookies) {
const values = Array.isArray(cookies) ? cookies : [cookies];
- const kept = values.filter((cookie) => !/^\s*(?:dpl_access|dpl_owner|portal_session)\s*=/i.test(cookie));
+ const kept = values.filter(
+ (cookie) => !/^\s*(?:dpl_access|dpl_owner|portal_session|portal_session_x)\s*=/i.test(cookie),
+ );
if (kept.length) out["set-cookie"] = kept;
else delete out["set-cookie"];
}
@@ -231,6 +244,13 @@ function gatewaySafeResponseHeaders(
? [...(Array.isArray(existing) ? existing : [existing]), APP_SANDBOX_CSP]
: APP_SANDBOX_CSP;
}
+ if (frameAncestors?.length && !out["x-frame-options"] && !cspMentionsFrameAncestors(out["content-security-policy"])) {
+ const directive = frameAncestorsDirective(frameAncestors);
+ const existing = out["content-security-policy"];
+ out["content-security-policy"] = existing
+ ? [...(Array.isArray(existing) ? existing : [existing]), directive]
+ : directive;
+ }
return out;
}
@@ -297,6 +317,7 @@ function proxyReachHttp2(
headers: Record<string, string | string[]>,
bufferedBody: Buffer | null,
sandbox: boolean,
+ frameAncestors?: readonly string[],
): void {
const { req, res, deps, url, method } = ctx;
const { host, port, tls } = endpoint.endpoint;
@@ -401,7 +422,8 @@ function proxyReachHttp2(
markUpstreamUp(`${host}:${port}`);
armThrottleShield(`${host}:${port}`, Number(responseHeaders[":status"] ?? 0), up);
const status = Number(responseHeaders[":status"] ?? 502);
- const safeHeaders = gatewaySafeResponseHeaders(responseHeaders, sandbox);
+ const safeHeaders = gatewaySafeResponseHeaders(responseHeaders, sandbox, frameAncestors);
+ if (frameAncestors !== undefined) res.removeHeader("content-security-policy");
res.writeHead(status, safeHeaders);
up.pipe(res, { end: false });
});
@@ -492,7 +514,7 @@ async function proxyReach(
reach: Awaited<ReturnType<App["reachDeployment"]>>,
subPath: string,
viewer?: string,
- opts?: { sandbox?: boolean },
+ opts?: { sandbox?: boolean; frameAncestors?: readonly string[] },
): Promise<void> {
const { req, res, deps, url, method } = ctx;
if (res.destroyed) return;
@@ -545,7 +567,7 @@ async function proxyReach(
}
if (res.destroyed) return;
if (reach.endpoint.httpVersion === "2") {
- proxyReachHttp2(ctx, reach, subPath, headers, bufferedBody, opts?.sandbox ?? false);
+ proxyReachHttp2(ctx, reach, subPath, headers, bufferedBody, opts?.sandbox ?? false, opts?.frameAncestors);
return;
}
const htmlNav = wantsWarmingPage(req, method);
@@ -563,7 +585,8 @@ async function proxyReach(
markUpstreamUp(upstreamKey);
upRes.on("error", () => res.destroy());
armThrottleShield(upstreamKey, upRes.statusCode ?? 0, upRes);
- const headers = gatewaySafeResponseHeaders(upRes.headers, opts?.sandbox ?? false);
+ const headers = gatewaySafeResponseHeaders(upRes.headers, opts?.sandbox ?? false, opts?.frameAncestors);
+ if (opts?.frameAncestors !== undefined) res.removeHeader("content-security-policy");
res.writeHead(upRes.statusCode ?? 502, headers);
upRes.pipe(res);
},
@@ -814,7 +837,15 @@ export async function proxyDeploymentSubdomain(ctx: BaseCtx): Promise<boolean> {
const sessionSecret = deps.deployAppsSessionSecret;
const loginUrl = deps.deployAppsLoginUrl;
const wantsHtml = ctx.method === "GET" && String(req.headers.accept ?? "").includes("text/html");
- const sub = sessionSecret ? portalSessionSub(req.headers.cookie, sessionSecret) : null;
+ let sub = sessionSecret ? portalSessionSub(req.headers.cookie, sessionSecret) : null;
+ const dest = req.headers["sec-fetch-dest"];
+ const site = req.headers["sec-fetch-site"];
+ const framed = dest === "iframe" || site === "same-origin";
+ const embedAncestors = framed ? ((await app.getDeployment(slug).catch(() => null))?.embedAncestors ?? []) : [];
+ if (!sub && sessionSecret && embedAncestors.length) {
+ sub = portalSessionSubFrom(req.headers.cookie, FRAME_SESSION_COOKIE, sessionSecret);
+ }
+ if (embedAncestors.length) res.setHeader("content-security-policy", frameAncestorsDirective(embedAncestors));
if (!sessionSecret || !loginUrl) {
sendJson(res, 503, { error: "unavailable", message: "sign-in is not configured for deployment subdomains" });
return true;
@@ -920,7 +951,7 @@ export async function proxyDeploymentSubdomain(ctx: BaseCtx): Promise<boolean> {
cleanUrlRedirect();
return true;
}
- await proxyReach(ctx, reach, pathname, sub);
+ await proxyReach(ctx, reach, pathname, sub, { frameAncestors: embedAncestors });
return true;
}
@@ -1414,6 +1445,22 @@ export async function setDeploymentDisplayName(ctx: ApiCtx): Promise<void> {
}
}
+async function setDeploymentEmbedAncestors(ctx: ApiCtx): Promise<void> {
+ const { res, app, params, body } = ctx;
+ const id = await deploymentId(app, params.id!);
+ if (!id) return sendJson(res, 404, { error: "not_found" });
+ if (!(await callerMayManageDeployment(ctx, id)))
+ return sendJson(res, 403, { error: "forbidden", message: "only someone who manages this app can change this" });
+ const ancestors = parseEmbedAncestors((body as { embedAncestors?: unknown }).embedAncestors);
+ if (!ancestors)
+ return sendJson(res, 400, { error: "bad_request", message: `embedAncestors (${EMBED_ANCESTORS_HINT}) required` });
+ try {
+ return sendJson(res, 200, { deployment: deploymentView(await app.setDeploymentEmbedAncestors(id, ancestors)) });
+ } catch (e) {
+ return sendJson(res, 400, { error: "embed_ancestors_failed", message: errMessage(e) });
+ }
+}
+
async function setDeploymentAlwaysOn(ctx: ApiCtx): Promise<void> {
const { res, app, params, body } = ctx;
const id = await deploymentId(app, params.id!);
@@ -1535,4 +1582,5 @@ export const deploymentRoutes: ReadonlyArray<Route<ApiCtx>> = [
{ method: "POST", path: "/v1/deployments/:id/name", auth: "either", handle: renameDeployment },
{ method: "POST", path: "/v1/deployments/:id/display-name", auth: "either", handle: setDeploymentDisplayName },
{ method: "POST", path: "/v1/deployments/:id/always-on", auth: "either", handle: setDeploymentAlwaysOn },
+ { method: "POST", path: "/v1/deployments/:id/embed-ancestors", auth: "either", handle: setDeploymentEmbedAncestors },
];
diff --git a/src/deploy/deploy-service.ts b/src/deploy/deploy-service.ts
index 0327171c4..955a3e940 100644
--- a/src/deploy/deploy-service.ts
+++ b/src/deploy/deploy-service.ts
@@ -1,3 +1,4 @@
+import { EMBED_ANCESTORS_HINT, parseEmbedAncestors } from "./embed-ancestors.ts";
import { mkdir, writeFile } from "node:fs/promises";
import { join, dirname, resolve, relative, isAbsolute } from "node:path";
import { randomUUID } from "node:crypto";
@@ -60,6 +61,7 @@ export interface DeployOrUpdateInput {
share?: Array<{ scope: ScopeId; permission: Permission }>;
createdInScope?: ScopeId;
alwaysOn?: boolean;
+ embedAncestors?: string[];
defaultAudience?: { contextScopeId: ScopeId; granteeScopeIds: ScopeId[]; snapshotAt: number; force?: boolean };
}
@@ -79,6 +81,7 @@ export interface DeployService {
renameDeployment(id: string, name: string): Promise<Deployment>;
setDeploymentDisplayName(id: string, displayName: string): Promise<Deployment>;
setDeploymentAlwaysOn(id: string, alwaysOn: boolean): Promise<Deployment>;
+ setDeploymentEmbedAncestors(id: string, embedAncestors: string[]): Promise<Deployment>;
keepAlwaysOnWarm(): Promise<number>;
reachDeployment(idOrName: string, principalId: string, opts?: ReachOptions): Promise<Reach>;
@@ -538,6 +541,24 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {
});
},
+ async setDeploymentEmbedAncestors(id, embedAncestors) {
+ const ancestors = parseEmbedAncestors(embedAncestors);
+ if (!ancestors) throw new Error(`embedAncestors must be an ${EMBED_ANCESTORS_HINT}`);
+ return withDeployLock(id, async () => {
+ const d = await deps.deployStore.get(id);
+ if (!d) throw new Error(`unknown deployment: ${id}`);
+ await deps.deployStore.setEmbedAncestors(id, ancestors);
+ deps.auditLog.record({
+ at: Date.now(),
+ principalId: d.createdBy,
+ action: "deploy_embed_ancestors",
+ resource: id,
+ scopeLabel: d.ownerScopeId,
+ });
+ return (await deps.deployStore.get(id))!;
+ });
+ },
+
async keepAlwaysOnWarm() {
const result = await leaderLease.hold("deployments:keep-warm", async () => {
let warmed = 0;
@@ -641,6 +662,8 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {
async deployOrUpdate(input) {
const { ownerScopeId, createdBy } = input;
+ if (input.embedAncestors !== undefined && !parseEmbedAncestors(input.embedAncestors))
+ throw new Error(`embedAncestors must be an ${EMBED_ANCESTORS_HINT}`);
if (input.renameFrom !== undefined) {
if (input.name === undefined) throw new Error("rename requires a target name");
@@ -672,6 +695,8 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {
if (input.defaultAudience)
await reconcileDefaultAudience((await deps.deployStore.get(existing.id))!, input.defaultAudience, false);
} else if (input.alwaysOn !== undefined) await this.setDeploymentAlwaysOn(existing.id, input.alwaysOn);
+ if (input.embedAncestors !== undefined)
+ await this.setDeploymentEmbedAncestors(existing.id, input.embedAncestors);
if (input.share?.length) await issueShares((await deps.deployStore.get(existing.id))!, createdBy, input.share);
return (await deps.deployStore.get(existing.id))!;
}
@@ -687,6 +712,8 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {
input.rollbackTo,
input.alwaysOn !== undefined ? { alwaysOn: input.alwaysOn } : undefined,
);
+ if (input.embedAncestors !== undefined)
+ await this.setDeploymentEmbedAncestors(existing.id, input.embedAncestors);
if (input.share?.length) await issueShares((await deps.deployStore.get(existing.id))!, createdBy, input.share);
return (await deps.deployStore.get(existing.id))!;
}
@@ -730,6 +757,7 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {
}
if (input.defaultAudience)
await reconcileDefaultAudience((await deps.deployStore.get(d.id))!, input.defaultAudience, isCreate);
+ if (input.embedAncestors !== undefined) await this.setDeploymentEmbedAncestors(d.id, input.embedAncestors);
if (input.share?.length) await issueShares((await deps.deployStore.get(d.id))!, createdBy, input.share);
return (await deps.deployStore.get(d.id))!;
},
diff --git a/src/deploy/deploy-store.ts b/src/deploy/deploy-store.ts
index 81b088a76..078b88cbc 100644
--- a/src/deploy/deploy-store.ts
+++ b/src/deploy/deploy-store.ts
@@ -68,6 +68,7 @@ export interface Deployment {
endpoint: DeployEndpoint | null;
alwaysOn?: boolean;
+ embedAncestors?: string[];
lastAccessAt?: number;
appliedVersion?: number;
versions: DeploymentVersion[];
@@ -108,6 +109,7 @@ export interface DeployStore {
setOwnerScope(id: string, ownerScopeId: ScopeId): Promise<void>;
setDisplayName(id: string, displayName: string | undefined): Promise<void>;
setAlwaysOn(id: string, alwaysOn: boolean): Promise<void>;
+ setEmbedAncestors(id: string, embedAncestors: string[]): Promise<void>;
setDefaultAudience(id: string, snapshot: DefaultAudienceSnapshot): Promise<void>;
setAppliedVersion(id: string, version: number): Promise<void>;
touch(id: string, at: number): Promise<void>;
@@ -431,6 +433,9 @@ export function createDeployStore(backing?: DurableMap<Deployment> | DeployStore
async setAlwaysOn(id, alwaysOn) {
await backingMap.merge(id, { alwaysOn } as Partial<Deployment>);
},
+ async setEmbedAncestors(id, embedAncestors) {
+ await backingMap.merge(id, { embedAncestors } as Partial<Deployment>);
+ },
async setDefaultAudience(id, snapshot) {
const d = await backingMap.get(id);
if (d) {
diff --git a/src/deploy/embed-ancestors.ts b/src/deploy/embed-ancestors.ts
new file mode 100644
index 000000000..35fa93121
--- /dev/null
+++ b/src/deploy/embed-ancestors.ts
@@ -0,0 +1,17 @@
+const HOST_LABEL = "[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";
+const EMBED_ANCESTOR = new RegExp(`^https://(?:\\*\\.)?(?:${HOST_LABEL}\\.)+[a-z](?:[a-z0-9-]*[a-z0-9])?$`);
+const MAX_EMBED_ANCESTORS = 16;
+
+export const EMBED_ANCESTORS_HINT = `array of up to ${MAX_EMBED_ANCESTORS} https origins, e.g. https://tools.example.com or https://*.example.com`;
+
+export function parseEmbedAncestors(input: unknown): string[] | null {
+ if (!Array.isArray(input) || input.length > MAX_EMBED_ANCESTORS) return null;
+ const out: string[] = [];
+ for (const raw of input) {
+ if (typeof raw !== "string") return null;
+ const value = raw.trim().toLowerCase();
+ if (!EMBED_ANCESTOR.test(value)) return null;
+ if (!out.includes(value)) out.push(value);
+ }
+ return out;
+}
diff --git a/src/deploy/viewer-session.ts b/src/deploy/viewer-session.ts
index 9893293a7..dfb7ef0d5 100644
--- a/src/deploy/viewer-session.ts
+++ b/src/deploy/viewer-session.ts
@@ -1,7 +1,18 @@
import { createHmac, timingSafeEqual } from "node:crypto";
+export const FRAME_SESSION_COOKIE = "portal_session_x";
+
export function portalSessionSub(cookieHeader: string | undefined, secret: string, now = Date.now()): string | null {
- for (const token of readCookies(cookieHeader, "portal_session")) {
+ return portalSessionSubFrom(cookieHeader, "portal_session", secret, now);
+}
+
+export function portalSessionSubFrom(
+ cookieHeader: string | undefined,
+ name: string,
+ secret: string,
+ now = Date.now(),
+): string | null {
+ for (const token of readCookies(cookieHeader, name)) {
const sub = verifySessionToken(token, secret, now);
if (sub) return sub;
}
diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.ts
index 12b359f9d..ef7f4d6d5 100644
--- a/src/harness/agent-tools.ts
+++ b/src/harness/agent-tools.ts
@@ -1125,7 +1125,9 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
"most recent writes). The rest of the disk is reset from source on every relaunch. By default " +
"an app sleeps when idle and cold-starts on the next visit; set `alwaysOn: true` to keep it " +
"warm (no idle cold starts) — use it only when someone actually needs instant loads, and " +
- "`alwaysOn: false` to turn it back off.",
+ "`alwaysOn: false` to turn it back off. An app cannot be shown inside another site's page " +
+ "(an iframe) unless `embedAncestors` names that site; set it when someone asks for the app in " +
+ "a panel or extension, and `[]` to turn it back off.",
parameters: Type.Object({
audience: Type.Optional(
Type.Array(
@@ -1174,6 +1176,12 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
"true keeps the app always warm — it is never put to sleep for being idle, so there are no cold starts. false returns it to the default sleep-when-idle behavior. Omitted = leave the current setting alone.",
}),
),
+ embedAncestors: Type.Optional(
+ Type.Array(Type.String(), {
+ description:
+ "Sites allowed to embed the app in an iframe, as https origins (https://tools.example.com, or https://*.example.com for any subdomain). Every frame between the app and the browser tab must be listed, so a panel inside another site needs both. [] forbids embedding again. Omitted = leave the current setting alone.",
+ }),
+ ),
}),
async execute(callId, params) {
const tc = ref.current;
@@ -1189,6 +1197,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
const r = await tc.publish({ ...params, share: params.audience } as PublishInput);
const reach = describePublishAudience(r.audience);
const alwaysOnNote = r.alwaysOn ? "\nAlways-on: the app is kept warm — no idle cold starts." : "";
+ const embedNote = r.embedAncestors?.length ? `\nEmbeddable by: ${r.embedAncestors.join(", ")}` : "";
const dataNote = r.dataDir
? `\nDurable data: runtime state written under ${r.dataDir} ($DATA_DIR) survives restarts and redeploys — keep SQLite at ${r.dataDir}/app.db (it gets the strongest durability the runtime offers). If this app writes runtime state anywhere else on disk, migrate it there (data deliberately baked into the repo stays where it is).`
: "";
@@ -1204,7 +1213,9 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
...(r.audience ? { audience: r.audience } : {}),
...(r.dataDir ? { dataDir: r.dataDir } : {}),
},
- text(`Published ${r.name ?? r.id} (v${r.version}) → ${r.url}\n${reach}${alwaysOnNote}${dataNote}`),
+ text(
+ `Published ${r.name ?? r.id} (v${r.version}) → ${r.url}\n${reach}${alwaysOnNote}${embedNote}${dataNote}`,
+ ),
);
} catch (e) {
const msg = errMessage(e);
diff --git a/src/tools/primitives.ts b/src/tools/primitives.ts
index 57a8530e1..4631921e8 100644
--- a/src/tools/primitives.ts
+++ b/src/tools/primitives.ts
@@ -86,6 +86,7 @@ export interface PublishInput {
env?: Record<string, string>;
rollbackTo?: number;
alwaysOn?: boolean;
+ embedAncestors?: string[];
share?: Array<{ scope: ScopeId; permission: Permission }>;
}
@@ -106,6 +107,7 @@ interface PublishResult {
audience?: PublishAudienceDescriptor;
dataDir?: string;
alwaysOn?: boolean;
+ embedAncestors?: string[];
}
export class NeedsApproval extends Error {
@@ -1063,6 +1065,7 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
...(Object.keys(authEnv).length ? { stampEnv: authEnv } : {}),
...(input.rollbackTo !== undefined ? { rollbackTo: input.rollbackTo } : {}),
...(input.alwaysOn !== undefined ? { alwaysOn: input.alwaysOn } : {}),
+ ...(input.embedAncestors !== undefined ? { embedAncestors: input.embedAncestors } : {}),
...(doReconcile
? {
defaultAudience: {
@@ -1096,6 +1099,7 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
audience,
...(dataDir ? { dataDir } : {}),
...(d.alwaysOn ? { alwaysOn: true } : {}),
+ ...(d.embedAncestors?.length ? { embedAncestors: d.embedAncestors } : {}),
};
});
},
diff --git a/test/deploy-embed-ancestors.test.ts b/test/deploy-embed-ancestors.test.ts
new file mode 100644
index 000000000..1438539b3
--- /dev/null
+++ b/test/deploy-embed-ancestors.test.ts
@@ -0,0 +1,86 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { createDeployStore } from "../src/deploy/deploy-store.ts";
+import { createDeployService } from "../src/deploy/deploy-service.ts";
+import { createAclStore } from "../src/acl/acl-store.ts";
+import { scopeId } from "../src/types.ts";
+
+function svc() {
+ const deployStore = createDeployStore();
+ const deploy = createDeployService({
+ deployStore,
+ provider: {
+ profile: { managedScaleToZero: false },
+ apply: async () => ({ host: "127.0.0.1", port: 5000 }),
+ destroy: async () => {},
+ },
+ auditLog: { record() {}, events: async () => [], tail: async () => [] },
+ acl: createAclStore(),
+ deployDir: mkdtempSync(join(tmpdir(), "embed-ancestors-")),
+ });
+ return { deploy, deployStore };
+}
+
+const owner = { ownerScopeId: scopeId("personal", "U1"), createdBy: "U1" };
+const files = [{ path: "server.js", data: new TextEncoder().encode("listen") }];
+const ancestors = ["https://internal.example.com", "https://mail.example.com"];
+
+test("publish sets embed ancestors, a republish that omits them keeps them, and [] clears them", async () => {
+ const { deploy } = svc();
+ const created = await deploy.deployOrUpdate({
+ ...owner,
+ name: "panel",
+ entrypoint: "node server.js",
+ files,
+ embedAncestors: ancestors,
+ });
+ assert.deepEqual(created.embedAncestors, ancestors);
+
+ const kept = await deploy.deployOrUpdate({ ...owner, name: "panel", files });
+ assert.deepEqual(kept.embedAncestors, ancestors, "a republish without the field leaves the setting alone");
+ assert.equal(kept.currentVersion, 2);
+
+ const cleared = await deploy.deployOrUpdate({ ...owner, name: "panel", files, embedAncestors: [] });
+ assert.deepEqual(cleared.embedAncestors, []);
+});
+
+test("embed ancestors can be changed without a new version, through rename and rollback too", async () => {
+ const { deploy } = svc();
+ const first = await deploy.deployOrUpdate({ ...owner, name: "panel", entrypoint: "node server.js", files });
+ await deploy.deployOrUpdate({ ...owner, name: "panel", files });
+
+ const renamed = await deploy.deployOrUpdate({
+ ...owner,
+ name: "panel2",
+ renameFrom: "panel",
+ embedAncestors: ancestors,
+ });
+ assert.equal(renamed.id, first.id);
+ assert.deepEqual(renamed.embedAncestors, ancestors);
+ assert.equal(renamed.currentVersion, 2, "setting the list is not a redeploy");
+
+ const rolled = await deploy.deployOrUpdate({ ...owner, name: "panel2", rollbackTo: 1, embedAncestors: [] });
+ assert.deepEqual(rolled.embedAncestors, []);
+});
+
+test("an invalid embed ancestor is refused before anything is published", async () => {
+ const { deploy, deployStore } = svc();
+ await assert.rejects(
+ deploy.deployOrUpdate({
+ ...owner,
+ name: "panel",
+ entrypoint: "node server.js",
+ files,
+ embedAncestors: ["http://x.example.com"],
+ }),
+ /embedAncestors must be an array of up to 16 https origins/,
+ );
+ assert.equal(await deployStore.getByName("panel"), null);
+
+ const d = await deploy.deploy({ ...owner, entrypoint: "node server.js", files });
+ await assert.rejects(deploy.setDeploymentEmbedAncestors(d.id, ["*"]), /embedAncestors must be an/);
+ assert.equal((await deployStore.get(d.id))!.embedAncestors, undefined);
+});
diff --git a/test/deploy-subdomain-reach.test.ts b/test/deploy-subdomain-reach.test.ts
index 5023352d1..4fa0d7dde 100644
--- a/test/deploy-subdomain-reach.test.ts
+++ b/test/deploy-subdomain-reach.test.ts
@@ -397,3 +397,91 @@ test("subdomain ingress: the gateway vouches for the verified viewer with a per-
await new Promise<void>((resolve) => upstream.close(() => resolve()));
}
});
+
+test("subdomain ingress: the SameSite=None twin is honoured only for framed requests to embeddable apps", async () => {
+ const upstream = createHttpServer((req, res) => {
+ if (req.url?.startsWith("/xfo")) res.setHeader("x-frame-options", "DENY");
+ res.writeHead(200, { "content-type": "text/plain" });
+ res.end(`cookie=${req.headers.cookie ?? ""}`);
+ });
+ upstream.listen(0);
+ const app = appServingUpstream((upstream.address() as AddressInfo).port);
+ const d = await app.deploy({
+ ownerScopeId: scopeId("personal", "U1"),
+ createdBy: "U1",
+ entrypoint: "x",
+ files: [],
+ name: "framed",
+ });
+ const server = createInsecureTestServer(app, {
+ deployAppsDomain: "apps.example.com",
+ deployGateSecret: "gate-secret",
+ auditLog,
+ ...SESSION_DEPS,
+ });
+ server.listen(0);
+ const port = (server.address() as AddressInfo).port;
+ const host = "framed.apps.example.com";
+ const twin = `portal_session_x=${mintPortalSession("U1")}`;
+ const frameDoc = { "Sec-Fetch-Dest": "iframe", "Sec-Fetch-Site": "cross-site" };
+
+ try {
+ const notOptedIn = await httpGet(port, "/", { Host: host, Cookie: twin, ...frameDoc });
+ assert.equal(notOptedIn.status, 401, "an app that has not opted in never honours the twin");
+ assert.ok(!String(notOptedIn.headers["content-security-policy"] ?? "").includes("frame-ancestors"));
+
+ await app.setDeploymentEmbedAncestors(d.id, ["https://internal.example.com", "https://mail.google.com"]);
+
+ const framed = await httpGet(port, "/", { Host: host, Cookie: twin, ...frameDoc });
+ assert.equal(framed.status, 200, "the frame document authenticates with the twin");
+ assert.match(
+ String(framed.headers["content-security-policy"]),
+ /frame-ancestors 'self' https:\/\/internal\.example\.com https:\/\/mail\.google\.com/,
+ );
+ assert.ok(!framed.body.includes("portal_session_x"), "the twin never reaches the app container");
+
+ const inFrame = await httpGet(port, "/api", {
+ Host: host,
+ Cookie: twin,
+ "Sec-Fetch-Dest": "empty",
+ "Sec-Fetch-Site": "same-origin",
+ });
+ assert.equal(inFrame.status, 200, "the app's own requests from inside the frame authenticate too");
+
+ const subresource = await httpGet(port, "/", {
+ Host: host,
+ Cookie: twin,
+ "Sec-Fetch-Dest": "image",
+ "Sec-Fetch-Site": "cross-site",
+ });
+ assert.equal(subresource.status, 401, "a cross-site <img> or fetch from anywhere else is nobody, as with Lax");
+
+ const noMetadata = await httpGet(port, "/", { Host: host, Cookie: twin });
+ assert.equal(noMetadata.status, 401, "without Sec-Fetch metadata the twin is ignored and the Lax cookie rules");
+
+ const lax = await httpGet(port, "/", { Host: host, Cookie: `portal_session=${mintPortalSession("U1")}` });
+ assert.equal(lax.status, 200, "the original cookie works exactly as before");
+
+ const stranger = await httpGet(port, "/", {
+ Host: host,
+ Cookie: `portal_session_x=${mintPortalSession("U9")}`,
+ ...frameDoc,
+ });
+ assert.equal(stranger.status, 403, "a signed-in stranger is still denied by the ACL");
+ assert.match(String(stranger.headers["content-security-policy"]), /frame-ancestors 'self' https:\/\/internal/);
+
+ const anonymousFrame = await httpGet(port, "/", { Host: host, ...frameDoc });
+ assert.equal(anonymousFrame.status, 401);
+ assert.match(String(anonymousFrame.headers["content-security-policy"]), /frame-ancestors 'self'/);
+
+ const deferred = await httpGet(port, "/xfo", { Host: host, Cookie: twin, ...frameDoc });
+ assert.equal(deferred.headers["x-frame-options"], "DENY");
+ assert.ok(
+ !String(deferred.headers["content-security-policy"] ?? "").includes("frame-ancestors"),
+ "an app's own framing header wins; adding frame-ancestors would make browsers ignore it",
+ );
+ } finally {
+ server.close();
+ upstream.close();
+ }
+});
diff --git a/test/embed-ancestors.test.ts b/test/embed-ancestors.test.ts
new file mode 100644
index 000000000..4eb3cd43b
--- /dev/null
+++ b/test/embed-ancestors.test.ts
@@ -0,0 +1,33 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { parseEmbedAncestors } from "../src/deploy/embed-ancestors.ts";
+
+test("embed ancestors: https origins on named hosts, lowercased and deduplicated", () => {
+ assert.deepEqual(
+ parseEmbedAncestors([" https://Internal.Example.com ", "https://*.example.com", "https://internal.example.com"]),
+ ["https://internal.example.com", "https://*.example.com"],
+ );
+ assert.deepEqual(parseEmbedAncestors([]), [], "an empty list switches embedding off");
+ assert.deepEqual(parseEmbedAncestors(["https://a-b.example.com"]), ["https://a-b.example.com"]);
+});
+
+test("embed ancestors: anything that could widen framing beyond a named origin is refused", () => {
+ for (const bad of [
+ ["*"],
+ ["https://*"],
+ ["http://internal.example.com"],
+ ["javascript:alert(1)"],
+ ["https://internal.example.com/path"],
+ ["https://internal.example.com:8443"],
+ ["https://*.com"],
+ ["https://1.2.3.4"],
+ ["https://-x.example.com"],
+ ["https://x-.example.com"],
+ ["internal.example.com"],
+ "https://internal.example.com",
+ [42],
+ Array.from({ length: 17 }, (_, i) => `https://h${i}.example.com`),
+ ]) {
+ assert.equal(parseEmbedAncestors(bad), null, JSON.stringify(bad));
+ }
+});
diff --git a/test/integration/admin-login.test.ts b/test/integration/admin-login.test.ts
index b640014af..3e97122db 100644
--- a/test/integration/admin-login.test.ts
+++ b/test/integration/admin-login.test.ts
@@ -44,7 +44,13 @@ test(
assert.ok(cookie);
assert.match(cookie, /HttpOnly/);
assert.match(cookie, /SameSite=Lax/);
- if (publicUrl.startsWith("https:")) assert.match(cookie, /Secure/);
+ if (publicUrl.startsWith("https:")) {
+ assert.match(cookie, /Secure/);
+ const twin = res.headers.getSetCookie().find((value) => value.startsWith("portal_session_x="));
+ assert.ok(twin, "the SameSite=None twin is issued beside the Lax cookie");
+ assert.match(twin, /SameSite=None/);
+ assert.match(twin, /Secure/);
+ }
return cookie.split(";")[0]!;
};