diff --git a/.dev.vars.example b/.dev.vars.example index 9c16289..0bb3824 100644 --- a/.dev.vars.example +++ b/.dev.vars.example @@ -7,6 +7,10 @@ BETTER_AUTH_SECRET= # Optional: pins the app's URL. Leave it out to accept any host, for example from your phone. # BETTER_AUTH_URL= +# Optional: a distinct origin routed to this Worker for embedded respondents. Set +# BETTER_AUTH_URL to the owner origin too; each published form must register its exact host. +# FORMS_RESPONDENT_ORIGIN= + # Optional: who may make an account, as whole addresses separated by commas. An entry that # names a domain (@example.org) is ignored: no email is sent yet, so nothing proves who can # read mail there. A listed address belongs to whoever signs up with it first. diff --git a/apps/web/e2e/embed.spec.ts b/apps/web/e2e/embed.spec.ts new file mode 100644 index 0000000..22857a3 --- /dev/null +++ b/apps/web/e2e/embed.spec.ts @@ -0,0 +1,374 @@ +import { fileURLToPath } from "node:url"; +import type { Page } from "@playwright/test"; +import { test as browserTest } from "@playwright/test"; +import { shortFeedback } from "../test/short-feedback"; +import { expect, test } from "./fixtures"; +import { freshId, signUp } from "./owner"; + +const port = Number(process.env.FORMS_E2E_PORT) || 4771; +const owner = `http://localhost:${port}`; +const respondent = `http://127.0.0.1:${port}`; +// The example form names this product origin. The product's documents are mocked by Playwright. +const host = "http://localhost:4771"; +const hostPage = `${host}/synthetic-host`; + +async function serveLoader(page: Page) { + await page.route(`${host}/forms-embed-loader.mjs`, (route) => + route.fulfill({ + path: fileURLToPath(new URL("../../../embed/loader.mjs", import.meta.url)), + contentType: "text/javascript", + }), + ); +} + +test.use({ trace: "off" }); + +test("a host loader opens a sandboxed form with consent, context and a private resume link", async ({ + page, +}) => { + test.setTimeout(120_000); + await page.setViewportSize({ width: 320, height: 700 }); + await page.route(hostPage, (route) => + route.fulfill({ + contentType: "text/html", + body: "Synthetic host

Product content

", + }), + ); + await serveLoader(page); + await page.goto(hostPage); + await page.evaluate( + async ({ owner, respondent }) => { + const target = document.createElement("div"); + document.body.append(target); + const path = "/forms-embed-loader.mjs"; + const loader = await import(path); + const context = { product: "bread-lab", publicRoute: "/recipes" }; + loader.mountFormsFeedback({ + target, + respondentOrigin: respondent, + publicOrigin: owner, + form: "home-baking", + context, + entryLabel: "Give feedback", + closeLabel: "Close feedback", + directLabel: "Open form directly", + }); + context.publicRoute = "/plans"; + (window as typeof window & { embedMessages?: unknown[] }).embedMessages = []; + window.addEventListener("message", (event) => { + if (event.origin === respondent) + (window as typeof window & { embedMessages: unknown[] }).embedMessages.push(event.data); + }); + }, + { owner, respondent }, + ); + await expect(page.getByRole("link", { name: "Open form directly" })).toHaveAttribute( + "href", + `${owner}/f/home-baking`, + ); + await page.getByRole("button", { name: "Give feedback" }).click(); + await expect(page.locator("iframe")).toHaveAttribute( + "sandbox", + "allow-scripts allow-same-origin allow-forms", + ); + const frame = page.frameLocator("iframe"); + await expect(frame.getByRole("heading", { name: "Bread at home", exact: true })).toBeVisible(); + expect( + await frame.locator("html").evaluate((element) => element.scrollWidth <= element.clientWidth), + ).toBe(true); + await expect(frame.getByText("Product: bread-lab")).toBeVisible(); + await expect(frame.getByText("Public page or route: /recipes")).toBeVisible(); + await expect(frame.getByText("Public page or route: /plans")).toHaveCount(0); + await frame.getByRole("link", { name: "What is stored about you" }).click(); + await expect(frame.getByRole("heading", { name: "What is stored" })).toBeVisible(); + await expect(frame.getByText("No feedback is dispatched", { exact: false })).toBeVisible(); + await frame.getByRole("link", { name: "Back to the form" }).click(); + await expect(frame.getByText("Public page or route: /recipes")).toBeVisible(); + await expect(frame.getByText("Public page or route: /plans")).toHaveCount(0); + await frame.getByLabel("I have read this and agree to take part.").check(); + const start = page.waitForRequest( + (request) => request.url() === `${respondent}/api/forms/home-baking/responses`, + ); + await frame.getByRole("button", { name: "Start", exact: true }).click(); + const submitted = await (await start).headerValue("X-Embed-Context"); + expect(JSON.parse(submitted ?? "null")).toEqual({ + product: "bread-lab", + publicRoute: "/recipes", + }); + await expect(frame.getByRole("heading", { name: "You and your kitchen" })).toBeVisible(); + const privateUrl = + page + .frames() + .find((each) => each.url().startsWith(`${respondent}/f/home-baking/r/`)) + ?.url() ?? ""; + expect(/#[A-Za-z0-9_-]{43}$/.test(privateUrl)).toBe(true); + const messages = await page.evaluate( + () => (window as typeof window & { embedMessages: unknown[] }).embedMessages, + ); + expect(messages.some((message) => (message as { type?: string }).type === "ready")).toBe(true); + expect(JSON.stringify(messages).includes(new URL(privateUrl).hash.slice(1))).toBe(false); + expect(JSON.stringify(messages).includes("bread-lab")).toBe(false); + await frame.getByRole("button", { name: "Begin" }).click(); + await frame.locator("label").filter({ hasText: "Most weeks" }).click(); + for (let step = 0; step < 70; step++) { + if (await frame.getByRole("heading", { name: "Thank you" }).isVisible()) break; + const finish = frame.getByRole("button", { name: "Finish" }); + if (await finish.isVisible()) { + await finish.evaluate((button: HTMLButtonElement) => button.click()); + break; + } + await frame.getByRole("button", { name: /^(Next|Skip|Continue|Finish|Begin)$/ }).click(); + } + await expect(frame.getByRole("heading", { name: "Thank you" })).toBeVisible(); + const resumed = page.waitForEvent("framenavigated", (each) => each.url() === privateUrl); + await page.locator("iframe").evaluate((element: HTMLIFrameElement, url) => { + element.src = url; + }, privateUrl); + await resumed; + await expect(frame.getByRole("heading", { name: "Thank you" })).toBeVisible(); +}); + +test("public fallback and the private address work after the owner removes the embed", async ({ + browser, + page, +}, info) => { + const id = freshId(info); + const definition = shortFeedback(id); + const ownerContext = await browser.newContext({ baseURL: owner }); + const ownerPage = await ownerContext.newPage(); + try { + await signUp(ownerPage); + const headers = { Origin: owner }; + const path = `/api/owner/forms/${id}`; + const created = await ownerPage.request.post("/api/owner/forms", { + headers, + data: { definition: { ...definition, embed: { origin: host, context: {} } } }, + }); + expect(created.status()).toBe(201); + expect( + ( + await ownerPage.request.post(`${path}/state`, { headers, data: { state: "open" } }) + ).status(), + ).toBe(200); + await page.route(hostPage, (route) => + route.fulfill({ contentType: "text/html", body: "
Host content
" }), + ); + await serveLoader(page); + await page.goto(hostPage); + await page.evaluate( + async ({ id, respondent, owner }) => { + const path = "/forms-embed-loader.mjs"; + const loader = await import(path); + loader.mountFormsFeedback({ + target: document.querySelector("main"), + respondentOrigin: respondent, + publicOrigin: owner, + form: id, + entryLabel: "Give feedback", + closeLabel: "Close feedback", + directLabel: "Open form directly", + }); + }, + { id, respondent, owner }, + ); + await page.getByRole("button", { name: "Give feedback" }).click(); + const frame = page.frameLocator("iframe"); + await frame.getByRole("button", { name: "Start", exact: true }).click(); + await frame.getByRole("button", { name: "Options" }).click(); + await frame.getByRole("button", { name: "Continue on another device" }).click(); + const address = new URL( + await frame.getByRole("textbox", { name: "Continue on another device" }).inputValue(), + ); + expect( + address.origin === owner && + address.pathname.startsWith(`/f/${id}/r/`) && + /^#[A-Za-z0-9_-]{43}$/.test(address.hash), + ).toBe(true); + + const revisedTitle = "Revised synthetic feedback"; + const changed = await ownerPage.request.post(`${path}/definition`, { + headers, + data: { definition: { ...definition, title: revisedTitle } }, + }); + expect(changed.status()).toBe(200); + expect((await page.request.get(`${respondent}/embed/${id}`)).status()).toBe(404); + await page.getByRole("link", { name: "Open form directly" }).click(); + await expect(page).toHaveURL(`${owner}/f/${id}`); + await expect(page.getByRole("heading", { name: revisedTitle })).toBeVisible(); + + const fresh = await browser.newContext(); + try { + const resume = await fresh.newPage(); + await resume.route(`${owner}/resume-test`, (route) => + route.fulfill({ + contentType: "text/html", + body: "Other device", + }), + ); + await resume.goto(`${owner}/resume-test`); + await resume.evaluate( + (path) => window.location.replace(path), + `${address.pathname}${address.hash}`, + ); + await expect(resume.getByRole("heading", { name: "Two quick questions" })).toBeVisible(); + } finally { + await fresh.close(); + } + } finally { + await ownerContext.close(); + } +}); + +browserTest("a foreign outer ancestor blocks the registered iframe", async ({ page }) => { + const fetched: number[] = []; + page.on("response", (response) => { + if (response.url() === `${respondent}/f/home-baking`) fetched.push(response.status()); + }); + await page.route("http://foreign.test/nested", (route) => + route.fulfill({ + contentType: "text/html", + body: ``, + }), + ); + await page.route(hostPage, (route) => + route.fulfill({ + contentType: "text/html", + body: ``, + }), + ); + await page.goto("http://foreign.test/nested"); + await expect(page.locator("iframe").contentFrame().locator("iframe")).toHaveCount(1); + const nested = page.frames().find((frame) => frame.url() === `${respondent}/f/home-baking`); + expect(fetched).toContain(200); + expect(nested).toBeUndefined(); +}); + +browserTest("context ignores another window before accepting the parent once", async ({ page }) => { + await page.route(hostPage, (route) => + route.fulfill({ + contentType: "text/html", + body: ``, + }), + ); + await page.goto(hostPage); + const frame = page.frameLocator("iframe"); + await expect(frame.getByRole("heading", { name: "Bread at home", exact: true })).toBeVisible(); + await page.waitForFunction(() => (window as typeof window & { formNonce?: string }).formNonce); + const nonce = await page.evaluate( + () => (window as typeof window & { formNonce: string }).formNonce, + ); + await frame.locator("body").evaluate( + (_element, { nonce, origin }) => + window.dispatchEvent( + new MessageEvent("message", { + origin, + source: window, + data: { version: 1, type: "context", nonce, context: { publicRoute: "/plans" } }, + }), + ), + { nonce, origin: host }, + ); + await expect(frame.getByText("Public page or route: /plans")).toHaveCount(0); + const send = (messageNonce: string, context: Record) => + page + .locator("iframe") + .evaluate( + (element: HTMLIFrameElement, { origin, nonce, context }) => + element.contentWindow?.postMessage( + { version: 1, type: "context", nonce, context }, + origin, + ), + { origin: respondent, nonce: messageNonce, context }, + ); + await send("00000000-0000-4000-8000-000000000000", { publicRoute: "/plans" }); + await send(nonce, { product: "bread-lab" }); + await expect(frame.getByText("Product: bread-lab")).toBeVisible(); + await send(nonce, { publicRoute: "/plans" }); + await expect(frame.getByText("Public page or route: /plans")).toHaveCount(0); + await expect(frame.getByText("Product: bread-lab")).toBeVisible(); +}); + +browserTest("the loader ignores ready from its iframe on a different origin", async ({ page }) => { + await page.route("http://foreign.test/ready", (route) => + route.fulfill({ + contentType: "text/html", + body: '', + }), + ); + await page.route(hostPage, (route) => + route.fulfill({ contentType: "text/html", body: "
Host content
" }), + ); + await serveLoader(page); + await page.goto(hostPage); + await page.evaluate( + async ({ owner, respondent }) => { + const seen: string[] = []; + (window as typeof window & { seenOrigins?: string[] }).seenOrigins = seen; + window.addEventListener("message", (event) => seen.push(event.origin)); + const target = document.createElement("div"); + document.body.append(target); + const path = "/forms-embed-loader.mjs"; + const loader = await import(path); + loader.mountFormsFeedback({ + target, + respondentOrigin: respondent, + publicOrigin: owner, + form: "home-baking", + context: { product: "bread-lab" }, + entryLabel: "Give feedback", + closeLabel: "Close feedback", + directLabel: "Open form directly", + }); + (document.querySelector("button") as HTMLButtonElement).click(); + (document.querySelector("iframe") as HTMLIFrameElement).src = "http://foreign.test/ready"; + }, + { owner, respondent }, + ); + await expect + .poll(() => + page.evaluate(() => (window as typeof window & { seenOrigins?: string[] }).seenOrigins ?? []), + ) + .toContain("http://foreign.test"); + await page.locator("iframe").evaluate((element: HTMLIFrameElement, origin) => { + element.src = `${origin}/f/home-baking`; + }, respondent); + await expect(page.frameLocator("iframe").getByText("Product: bread-lab")).toBeVisible(); +}); + +browserTest("an unregistered error page refuses a real frame", async ({ page }) => { + const fetched: number[] = []; + page.on("response", (response) => { + if (response.url() === `${respondent}/f/home-baking/unknown`) fetched.push(response.status()); + }); + await page.route(hostPage, (route) => + route.fulfill({ + contentType: "text/html", + body: ``, + }), + ); + await page.goto(hostPage); + await expect.poll(() => fetched).toContain(404); + expect(page.frames().some((frame) => frame.url() === `${respondent}/f/home-baking/unknown`)).toBe( + false, + ); +}); + +browserTest( + "the Forms policy restricts a direct iframe without a sandbox attribute", + async ({ page }) => { + await page.route(hostPage, (route) => + route.fulfill({ + contentType: "text/html", + body: ``, + }), + ); + await page.goto(hostPage); + const frame = page.frameLocator("iframe"); + await expect(frame.getByRole("heading", { name: "Bread at home", exact: true })).toBeVisible(); + const popup = await frame.locator("body").evaluate(() => window.open("about:blank")); + expect(popup).toBeNull(); + }, +); diff --git a/apps/web/e2e/server.mjs b/apps/web/e2e/server.mjs index 3aa0a41..8898eab 100644 --- a/apps/web/e2e/server.mjs +++ b/apps/web/e2e/server.mjs @@ -20,7 +20,7 @@ rmSync(state, { recursive: true, force: true }); // left alone. writeFileSync( resolve(root, "dist/server/.dev.vars"), - `BETTER_AUTH_SECRET=${randomBytes(32).toString("hex")}\n`, + `BETTER_AUTH_SECRET=${randomBytes(32).toString("hex")}\nBETTER_AUTH_URL=http://localhost:${port}\nFORMS_RESPONDENT_ORIGIN=http://127.0.0.1:${port}\n`, ); // Run the tools with this Node, not through a shell: Playwright stops the server by killing this @@ -39,9 +39,17 @@ const server = spawn( process.execPath, [ resolve(root, "node_modules/vite/bin/vite.js"), - ...["preview", "--port", String(port), "--strictPort"], + ...["preview", "--host", "0.0.0.0", "--port", String(port), "--strictPort"], ], - { stdio: "inherit", env: { ...process.env, FORMS_STATE_DIR: state } }, + { + stdio: "inherit", + env: { + ...process.env, + FORMS_STATE_DIR: state, + BETTER_AUTH_URL: `http://localhost:${port}`, + FORMS_RESPONDENT_ORIGIN: `http://127.0.0.1:${port}`, + }, + }, ); for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => server.kill(signal)); server.on("exit", (code) => process.exit(code ?? 0)); diff --git a/apps/web/migrations/0019_embed-context.sql b/apps/web/migrations/0019_embed-context.sql new file mode 100644 index 0000000..758a8e1 --- /dev/null +++ b/apps/web/migrations/0019_embed-context.sql @@ -0,0 +1 @@ +ALTER TABLE `response` ADD `embed_context` text; \ No newline at end of file diff --git a/apps/web/migrations/meta/0019_snapshot.json b/apps/web/migrations/meta/0019_snapshot.json new file mode 100644 index 0000000..afbac54 --- /dev/null +++ b/apps/web/migrations/meta/0019_snapshot.json @@ -0,0 +1,1321 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "3254df60-e7d3-4c93-bb7f-b7f11d35d67b", + "prevId": "6fc03ead-8e1a-409c-84f7-df157fd50278", + "tables": { + "account": { + "name": "account", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsecond') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "account_userId_idx": { + "name": "account_userId_idx", + "columns": [ + "user_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "account_user_id_user_id_fk": { + "name": "account_user_id_user_id_fk", + "tableFrom": "account", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "session": { + "name": "session", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsecond') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "session_token_unique": { + "name": "session_token_unique", + "columns": [ + "token" + ], + "isUnique": true + }, + "session_userId_idx": { + "name": "session_userId_idx", + "columns": [ + "user_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "session_user_id_user_id_fk": { + "name": "session_user_id_user_id_fk", + "tableFrom": "session", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "user": { + "name": "user", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email_verified": { + "name": "email_verified", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsecond') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsecond') * 1000 as integer))" + } + }, + "indexes": { + "user_email_unique": { + "name": "user_email_unique", + "columns": [ + "email" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "verification": { + "name": "verification", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsecond') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsecond') * 1000 as integer))" + } + }, + "indexes": { + "verification_identifier_idx": { + "name": "verification_identifier_idx", + "columns": [ + "identifier" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "answer": { + "name": "answer", + "columns": { + "response_id": { + "name": "response_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "question_id": { + "name": "question_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "item_id": { + "name": "item_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "active_ms": { + "name": "active_ms", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "changes": { + "name": "changes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "save_id": { + "name": "save_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "answer_question_idx": { + "name": "answer_question_idx", + "columns": [ + "question_id", + "item_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "answer_response_id_response_id_fk": { + "name": "answer_response_id_response_id_fk", + "tableFrom": "answer", + "tableTo": "response", + "columnsFrom": [ + "response_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "answer_response_id_question_id_item_id_pk": { + "columns": [ + "response_id", + "question_id", + "item_id" + ], + "name": "answer_response_id_question_id_item_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "definition": { + "name": "definition", + "columns": { + "hash": { + "name": "hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "form_id": { + "name": "form_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "json": { + "name": "json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "entry_private": { + "name": "entry_private", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "withdrawn": { + "name": "withdrawn", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": { + "definition_form_idx": { + "name": "definition_form_idx", + "columns": [ + "form_id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "detached_answer": { + "name": "detached_answer", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "form_id": { + "name": "form_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "answers": { + "name": "answers", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "save_id": { + "name": "save_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "detached_answer_form_idx": { + "name": "detached_answer_form_idx", + "columns": [ + "form_id" + ], + "isUnique": false + }, + "detached_answer_live_save_idx": { + "name": "detached_answer_live_save_idx", + "columns": [ + "form_id", + "save_id" + ], + "isUnique": true, + "where": "\"detached_answer\".\"save_id\" is not null" + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "detached_capability": { + "name": "detached_capability", + "columns": { + "form_id": { + "name": "form_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "definition_hash": { + "name": "definition_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "seal": { + "name": "seal", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "detached_capability_form_id_definition_hash_generation_pk": { + "columns": [ + "form_id", + "definition_hash", + "generation" + ], + "name": "detached_capability_form_id_definition_hash_generation_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "feedback_connector": { + "name": "feedback_connector", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "form_id": { + "name": "form_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "destination": { + "name": "destination", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "audience": { + "name": "audience", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "generation": { + "name": "generation", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "grant_reference": { + "name": "grant_reference", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "approved_origin": { + "name": "approved_origin", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "measure_question_id": { + "name": "measure_question_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "measure_kind": { + "name": "measure_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "note_question_id": { + "name": "note_question_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "context_json": { + "name": "context_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "feedback_connector_form_idx": { + "name": "feedback_connector_form_idx", + "columns": [ + "form_id" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "feedback_outbox": { + "name": "feedback_outbox", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "response_id": { + "name": "response_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "delivery_id": { + "name": "delivery_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sent_at": { + "name": "sent_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload_json": { + "name": "payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "claim_id": { + "name": "claim_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lease_until": { + "name": "lease_until", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "result_code": { + "name": "result_code", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "grant_reference": { + "name": "grant_reference", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "approved_origin": { + "name": "approved_origin", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "feedback_outbox_response_idx": { + "name": "feedback_outbox_response_idx", + "columns": [ + "response_id" + ], + "isUnique": true + }, + "feedback_outbox_delivery_idx": { + "name": "feedback_outbox_delivery_idx", + "columns": [ + "delivery_id" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "feedback_preview": { + "name": "feedback_preview", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "response_id": { + "name": "response_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "connector_id": { + "name": "connector_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "connector_version": { + "name": "connector_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "definition_hash": { + "name": "definition_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "answer_revision": { + "name": "answer_revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "include_note": { + "name": "include_note", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "projection_json": { + "name": "projection_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "connector_generation": { + "name": "connector_generation", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "grant_reference": { + "name": "grant_reference", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "approved_origin": { + "name": "approved_origin", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "feedback_preview_response_idx": { + "name": "feedback_preview_response_idx", + "columns": [ + "response_id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "form": { + "name": "form", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "entry_mode": { + "name": "entry_mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'open'" + }, + "entry_seal": { + "name": "entry_seal", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "entry_generation": { + "name": "entry_generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "entry_expires_at": { + "name": "entry_expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "definition_hash": { + "name": "definition_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "form_owner_idx": { + "name": "form_owner_idx", + "columns": [ + "owner_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "form_owner_id_user_id_fk": { + "name": "form_owner_id_user_id_fk", + "tableFrom": "form", + "tableTo": "user", + "columnsFrom": [ + "owner_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "form_definition_hash_definition_hash_fk": { + "name": "form_definition_hash_definition_hash_fk", + "tableFrom": "form", + "tableTo": "definition", + "columnsFrom": [ + "definition_hash" + ], + "columnsTo": [ + "hash" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "response": { + "name": "response", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "form_id": { + "name": "form_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "definition_hash": { + "name": "definition_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "answers_version": { + "name": "answers_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "answer_revision": { + "name": "answer_revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "secret_seal": { + "name": "secret_seal", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "device": { + "name": "device", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "embed_context": { + "name": "embed_context", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "position": { + "name": "position", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "completed_at": { + "name": "completed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reached_active_ms": { + "name": "reached_active_ms", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "response_form_idx": { + "name": "response_form_idx", + "columns": [ + "form_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "response_definition_hash_definition_hash_fk": { + "name": "response_definition_hash_definition_hash_fk", + "tableFrom": "response", + "tableTo": "definition", + "columnsFrom": [ + "definition_hash" + ], + "columnsTo": [ + "hash" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "response_save": { + "name": "response_save", + "columns": { + "response_id": { + "name": "response_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "question_id": { + "name": "question_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "item_id": { + "name": "item_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "save_id": { + "name": "save_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pending": { + "name": "pending", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "response_save_response_id_response_id_fk": { + "name": "response_save_response_id_response_id_fk", + "tableFrom": "response_save", + "tableTo": "response", + "columnsFrom": [ + "response_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "response_save_response_id_question_id_item_id_save_id_pk": { + "columns": [ + "response_id", + "question_id", + "item_id", + "save_id" + ], + "name": "response_save_response_id_question_id_item_id_save_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "retired_form_id": { + "name": "retired_form_id", + "columns": { + "form_id": { + "name": "form_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/apps/web/migrations/meta/_journal.json b/apps/web/migrations/meta/_journal.json index 18d28c5..918931c 100644 --- a/apps/web/migrations/meta/_journal.json +++ b/apps/web/migrations/meta/_journal.json @@ -134,6 +134,13 @@ "when": 1796346898273, "tag": "0018_fantastic_joseph", "breakpoints": true + }, + { + "idx": 19, + "version": "6", + "when": 1796350046168, + "tag": "0019_embed-context", + "breakpoints": true } ] -} +} \ No newline at end of file diff --git a/apps/web/playwright.config.ts b/apps/web/playwright.config.ts index e739571..a8e5860 100644 --- a/apps/web/playwright.config.ts +++ b/apps/web/playwright.config.ts @@ -17,6 +17,9 @@ export default defineConfig({ reporter: process.env.CI ? [["list"], ["html", { open: "never" }]] : "list", use: { baseURL: `http://localhost:${PORT}`, + // Chromium 159 blocks loopback-to-loopback frames as local network access. These tests + // use two loopback names to exercise origin and CSP checks in one local Worker. + launchOptions: { args: ["--disable-features=LocalNetworkAccessChecks"] }, trace: "retain-on-failure", }, // A form is answered on a phone as often as at a desk, and the two are not the same page: diff --git a/apps/web/src/components/continue-elsewhere.tsx b/apps/web/src/components/continue-elsewhere.tsx index 29dc4a3..b5735e1 100644 --- a/apps/web/src/components/continue-elsewhere.tsx +++ b/apps/web/src/components/continue-elsewhere.tsx @@ -17,12 +17,14 @@ export function ContinueElsewhere({ ref, formId, responseId, + resumeOrigin, secret, onClose, }: { ref: Ref; formId: string; responseId: string; + resumeOrigin?: string; secret: string; /** Called when the dialog has closed, to put the focus back where it came from. */ onClose?: () => void; @@ -34,7 +36,7 @@ export function ContinueElsewhere({ const open = () => { const path = responseAddress(formId, { id: responseId, secret }); - setAddress(`${window.location.origin}${path}`); + setAddress(`${resumeOrigin ?? window.location.origin}${path}`); setCopied(false); dialog.current?.showModal(); }; diff --git a/apps/web/src/components/disclosure-print.tsx b/apps/web/src/components/disclosure-print.tsx new file mode 100644 index 0000000..040e119 --- /dev/null +++ b/apps/web/src/components/disclosure-print.tsx @@ -0,0 +1,12 @@ +import { getRouteApi, useHydrated } from "@tanstack/react-router"; +import { LiveButton } from "./live-button"; + +const form = getRouteApi("/f/$form"); + +export function DisclosurePrint({ label }: { label: string }) { + const { origins } = form.useLoaderData(); + const hydrated = useHydrated(); + // The respondent document's sandbox blocks print dialogs. + if (origins && (!hydrated || window.location.origin === origins.respondent)) return null; + return window.print()}>{label}; +} diff --git a/apps/web/src/components/options-menu.tsx b/apps/web/src/components/options-menu.tsx index f616b85..4e6817e 100644 --- a/apps/web/src/components/options-menu.tsx +++ b/apps/web/src/components/options-menu.tsx @@ -22,6 +22,7 @@ export function OptionsMenu({ autoAdvance, formId, responseId, + resumeOrigin, secret, version, hasConsent, @@ -32,6 +33,7 @@ export function OptionsMenu({ autoAdvance: { on: boolean; set: (on: boolean) => void } | undefined; formId: string; responseId: string; + resumeOrigin?: string; secret: string; /** Names the wording the response began under, for the copy of its consent. */ version: string; @@ -141,6 +143,7 @@ export function OptionsMenu({ ref={elsewhere} formId={formId} responseId={responseId} + resumeOrigin={resumeOrigin} secret={secret} onClose={() => button.current?.focus()} /> diff --git a/apps/web/src/components/runner.tsx b/apps/web/src/components/runner.tsx index f56b72a..0fb8560 100644 --- a/apps/web/src/components/runner.tsx +++ b/apps/web/src/components/runner.tsx @@ -59,10 +59,12 @@ export function Runner({ definition, formId, responseId, + resumeOrigin, }: { definition?: Definition; formId: string; responseId: string; + resumeOrigin?: string; }) { const [opened, setOpened] = useState({ state: "loading" }); const [attempt, setAttempt] = useState(0); @@ -149,6 +151,7 @@ export function Runner({ // says today: its answers were given to those questions. definition={(opened.response.definition ?? definition) as Definition} responseId={responseId} + resumeOrigin={resumeOrigin} secret={opened.secret} initial={opened.response} /> @@ -159,11 +162,13 @@ export function Runner({ function Answering({ definition, responseId, + resumeOrigin, secret, initial, }: { definition: Definition; responseId: string; + resumeOrigin?: string; secret: string; initial: ResponseState; }) { @@ -507,6 +512,7 @@ function Answering({ autoAdvance={hasRepeat ? { on: autoAdvance, set: chooseAutoAdvance } : undefined} formId={definition.id} responseId={responseId} + resumeOrigin={resumeOrigin} secret={secret} version={initial.version} hasConsent={definition.consent !== undefined} diff --git a/apps/web/src/components/start-page.tsx b/apps/web/src/components/start-page.tsx index aa19d67..00e4f5a 100644 --- a/apps/web/src/components/start-page.tsx +++ b/apps/web/src/components/start-page.tsx @@ -1,4 +1,9 @@ -import { type Definition, withdrawalOf } from "@gateweave/forms-schema"; +import { + acceptedEmbedContext, + type Definition, + type EmbedContext, + withdrawalOf, +} from "@gateweave/forms-schema"; import { useNavigate } from "@tanstack/react-router"; import { type FormEvent, useEffect, useId, useRef, useState } from "react"; import { RequestFailed, type ReviewedEntry, startResponse } from "#/lib/client"; @@ -27,6 +32,8 @@ export function StartPage({ closed = false, turnstileSiteKey, review, + embedVersion, + respondentOrigin, }: { definition: Definition; /** The form takes no new responses. One already begun on this device can still be finished. */ @@ -34,6 +41,8 @@ export function StartPage({ /** The demo's Turnstile key. Where it is set, Start waits for the token it makes. */ turnstileSiteKey?: string | null; review?: ReviewedEntry; + embedVersion?: string; + respondentOrigin?: string; }) { const navigate = useNavigate(); const { consent } = definition; @@ -48,6 +57,46 @@ export function StartPage({ const [turnstileFailed, setTurnstileFailed] = useState(false); const box = useRef(null); const problemId = useId(); + const [embedded, setEmbedded] = useState(false); + const [context, setContext] = useState(); + const accepted = useRef(undefined); + const frozen = useRef(false); + const surface = useRef(null); + + useEffect(() => { + if ( + !definition.embed || + window.location.origin !== respondentOrigin || + window.parent === window + ) + return; + setEmbedded(true); + const host = definition.embed.origin; + const parent = window.parent; + const nonce = crypto.randomUUID(); + const receive = (event: MessageEvent) => { + if (event.source !== parent || event.origin !== host || frozen.current || accepted.current) + return; + if (event.data?.version !== 1 || event.data?.type !== "context" || event.data.nonce !== nonce) + return; + const value = acceptedEmbedContext(definition, event.data.context); + if (!value) return; + accepted.current = value; + setContext(value); + }; + window.addEventListener("message", receive); + parent.postMessage({ version: 1, type: "ready", nonce }, host); + const observer = new ResizeObserver(() => { + const height = Math.ceil(surface.current?.scrollHeight ?? 0); + if (height > 0) + parent.postMessage({ version: 1, type: "size", height: Math.min(height, 2400) }, host); + }); + if (surface.current) observer.observe(surface.current); + return () => { + observer.disconnect(); + window.removeEventListener("message", receive); + }; + }, [definition, respondentOrigin]); // Read after the page has loaded: the server does not know what this browser remembers. useEffect(() => { @@ -55,12 +104,19 @@ export function StartPage({ setReady(true); }, [definition.id]); - const open = (response: SavedResponse) => - navigate({ + const open = (response: SavedResponse) => { + if (window.location.origin === respondentOrigin) { + window.location.assign( + `/f/${encodeURIComponent(definition.id)}/r/${response.id}#${response.secret}`, + ); + return; + } + return navigate({ to: "/f/$form/r/$response", params: { form: definition.id, response: response.id }, hash: response.secret, }); + }; const start = async (event: FormEvent) => { event.preventDefault(); @@ -78,6 +134,7 @@ export function StartPage({ return; } setStarting(true); + frozen.current = true; setProblem(undefined); try { const started = await startResponse( @@ -86,6 +143,9 @@ export function StartPage({ consent !== undefined, turnstileToken, review, + window.location.origin === respondentOrigin && embedVersion + ? { version: embedVersion, context } + : undefined, ); rememberResponse(definition.id, started); await open(started); @@ -114,13 +174,39 @@ export function StartPage({ // thumb is on a phone, whichever hand holds it, so its buttons take the bar's whole width. return (
-
+
{/* A page with little on it stands in the middle of a phone, not in its top corner. */}

{definition.title}

+ {embedded && ( +
+

{strings.embed.purpose}

+ {context && + Object.entries(context).map(([key, value]) => ( +

+ {strings.embed.fields[key as keyof EmbedContext]}: {value} +

+ ))} + +
+ )} {saved && (

{strings.start.resumeTitle}

@@ -150,7 +236,7 @@ export function StartPage({ diff --git a/apps/web/src/lib/client.ts b/apps/web/src/lib/client.ts index 57b1e64..71a4800 100644 --- a/apps/web/src/lib/client.ts +++ b/apps/web/src/lib/client.ts @@ -49,6 +49,7 @@ const disclosureSchema = z.object({ controller: z.object({ name: z.string(), contact: z.string() }).nullable(), withdrawal: z.enum(["until-closed", "until-complete"]), keepsApart: z.boolean(), + embed: definitionSchema.shape.embed.nullable(), feedback: z.boolean(), columns: z.object({ response: z.array(z.string()), @@ -210,6 +211,7 @@ export async function startResponse( consent: boolean, turnstile?: string, review?: ReviewedEntry, + embed?: { version: string; context?: Record }, ): Promise { const path = `/api/forms/${encodeURIComponent(formId)}/responses`; return startedSchema.parse( @@ -221,7 +223,11 @@ export async function startResponse( ...(turnstile ? { turnstile } : {}), }, review?.token, - review ? { "X-Form-Version": review.version } : undefined, + { + ...(review ? { "X-Form-Version": review.version } : {}), + ...(embed ? { "X-Embed-Version": embed.version } : {}), + ...(embed?.context ? { "X-Embed-Context": JSON.stringify(embed.context) } : {}), + }, ), ); } diff --git a/apps/web/src/lib/forms.ts b/apps/web/src/lib/forms.ts index 0778052..4b43ed0 100644 --- a/apps/web/src/lib/forms.ts +++ b/apps/web/src/lib/forms.ts @@ -12,15 +12,19 @@ export const getForm = createServerFn({ method: "GET" }) .handler(async ({ data: id }) => { const { findForm } = await import("#/server/forms"); const { turnstileSiteKey } = await import("#/server/demo"); + const { embedOrigins } = await import("#/server/embed"); const form = await findForm(id); if (!form) return null; + const origins = embedOrigins() ?? null; if (form.state === "draft") - return { state: form.state, definition: null, turnstileSiteKey: null }; + return { state: form.state, definition: null, turnstileSiteKey: null, origins }; if (form.entryMode === "by-link") - return { state: "restricted" as const, definition: null, turnstileSiteKey: null }; + return { state: "restricted" as const, definition: null, turnstileSiteKey: null, origins }; return { state: form.state, definition: form.definition, + version: form.hash, + origins, turnstileSiteKey: turnstileSiteKey() ?? null, }; }); @@ -70,6 +74,7 @@ export const getStored = createServerFn({ method: "GET" }) controller: definition.controller ?? null, withdrawal: withdrawalOf(definition), keepsApart: detachedQuestions(definition).length > 0, + embed: definition.embed ?? null, feedback: await hasFeedbackConnector(definition.id), columns: storedColumns(), historyDays: HISTORY_DAYS, diff --git a/apps/web/src/lib/strings.ts b/apps/web/src/lib/strings.ts index 6cb6c47..8393184 100644 --- a/apps/web/src/lib/strings.ts +++ b/apps/web/src/lib/strings.ts @@ -4,6 +4,17 @@ */ export const strings = { product: "Gateweave Forms", + embed: { + purpose: + "This form may keep the public product details below with your answers. They help its controller understand where feedback was invited. No answer or private return link is sent to the page around this form.", + close: "Close feedback", + fields: { + product: "Product", + publicVersion: "Public version", + publicRoute: "Public page or route", + planCategory: "Plan category", + }, + }, tagline: "Long surveys that people finish.", demo: { banner: "Made-up forms, answers deleted after a day.", @@ -407,6 +418,9 @@ export const strings = { lead: "This page lists everything the server keeps when you answer this form. It is made from the server's own list of what it stores, so nothing is kept that is not named here.", entry: "The owner can require a private entry link. The link's codes stay after # in your browser's address and go to the server only in an authorization header. The server stores seals for entry and optional contact, tied to this form and its wording, never the clear codes. Entry links expire after seven days or sooner if the owner rotates or revokes one. A response already started can continue and be taken back with its own separate code.", + embed: + "When opened inside a registered product, the product may send only the public values this form declares. Forms checks them and fixes the accepted values when you press Start. They are stored with this response. The product receives readiness, size and close messages only; it receives no answers, contact details or private return link. No feedback is dispatched from Forms by this feature.", + embedTitle: "Public product context", controllerTitle: "Who runs this form", controllerBody: "They decide what the answers are used for, and they are who to ask about yours.", @@ -444,6 +458,8 @@ export const strings = { "A seal that proves the long code at the end of your address, without being that code. The code itself is only in your address.", device: "Whether you started on a phone, a tablet or a desk screen, judged by the width of the window.", + embedContext: + "The accepted public product, public version, public route and plan category values, when this response started in a registered embed. Empty for an ordinary link. These values stay with this response and are not dispatched by Forms.", position: "Which card you are on, so that you can continue on another device.", createdAt: "When you started.", updatedAt: diff --git a/apps/web/src/routes/f/$form.tsx b/apps/web/src/routes/f/$form.tsx index 08a9552..c18e1f8 100644 --- a/apps/web/src/routes/f/$form.tsx +++ b/apps/web/src/routes/f/$form.tsx @@ -1,10 +1,28 @@ import { createFileRoute, notFound, Outlet } from "@tanstack/react-router"; +import { useEffect } from "react"; import { Notice } from "#/components/notice"; import { getForm } from "#/lib/forms"; import { strings } from "#/lib/strings"; function FormPages() { - const { definition, state } = Route.useLoaderData(); + const { definition, state, origins } = Route.useLoaderData(); + const respondentOrigin = origins?.respondent; + useEffect(() => { + if (window.location.origin !== respondentOrigin) return; + const follow = (event: MouseEvent) => { + const anchor = (event.target as Element | null)?.closest("a[href]"); + if (!(anchor instanceof HTMLAnchorElement)) return; + const url = new URL(anchor.href); + // Each respondent document loads its data on the server because this origin + // does not expose server functions. Keep disclosure navigation in the same frame. + if (url.origin === respondentOrigin && url.pathname.startsWith("/f/")) { + event.preventDefault(); + window.location.assign(url.href); + } + }; + document.addEventListener("click", follow, true); + return () => document.removeEventListener("click", follow, true); + }, [respondentOrigin]); if (state === "restricted") return ; // A draft has pages only for its owner, under /forms. Here it is not open yet. if (!definition) return {strings.formDraft.body}; diff --git a/apps/web/src/routes/f/$form/consent.tsx b/apps/web/src/routes/f/$form/consent.tsx index 5b388ab..5f97b9e 100644 --- a/apps/web/src/routes/f/$form/consent.tsx +++ b/apps/web/src/routes/f/$form/consent.tsx @@ -2,7 +2,7 @@ import { createFileRoute, Link, notFound, useLocation } from "@tanstack/react-ro import { useEffect, useState } from "react"; import { z } from "zod"; import { AboutForm } from "#/components/about-form"; -import { LiveButton } from "#/components/live-button"; +import { DisclosurePrint } from "#/components/disclosure-print"; import { Notice } from "#/components/notice"; import { RichTextView } from "#/components/rich-text"; import { loadDisclosures } from "#/lib/client"; @@ -108,7 +108,7 @@ function ConsentContent({ /> {/* What is on paper needs no buttons. */}
- window.print()}>{t.print} + {back}
diff --git a/apps/web/src/routes/f/$form/index.tsx b/apps/web/src/routes/f/$form/index.tsx index a1bc416..9f2ceb6 100644 --- a/apps/web/src/routes/f/$form/index.tsx +++ b/apps/web/src/routes/f/$form/index.tsx @@ -10,7 +10,7 @@ const form = getRouteApi("/f/$form"); export const Route = createFileRoute("/f/$form/")({ component: Start }); function Start() { - const { definition, state, turnstileSiteKey } = form.useLoaderData(); + const { definition, state, turnstileSiteKey, version, origins } = form.useLoaderData(); const { form: formId } = Route.useParams(); const fragment = useLocation({ select: (location) => location.hash }); const [loaded, setLoaded] = useState<{ @@ -53,6 +53,8 @@ function Start() { return ( diff --git a/apps/web/src/routes/f/$form/r.$response.tsx b/apps/web/src/routes/f/$form/r.$response.tsx index 84db945..181d606 100644 --- a/apps/web/src/routes/f/$form/r.$response.tsx +++ b/apps/web/src/routes/f/$form/r.$response.tsx @@ -9,7 +9,7 @@ export const Route = createFileRoute("/f/$form/r/$response")({ function ResponsePage() { const { response, form: formId } = Route.useParams(); - const { definition } = form.useLoaderData(); + const { definition, origins } = form.useLoaderData(); // Keyed by the response, so that opening another one starts from its own answers. return ( ); } diff --git a/apps/web/src/routes/f/$form/stored.tsx b/apps/web/src/routes/f/$form/stored.tsx index 2137cf7..b940c59 100644 --- a/apps/web/src/routes/f/$form/stored.tsx +++ b/apps/web/src/routes/f/$form/stored.tsx @@ -2,7 +2,7 @@ import { createFileRoute, Link, notFound, useLocation } from "@tanstack/react-ro import { useEffect, useState } from "react"; import { z } from "zod"; import { Contact } from "#/components/about-form"; -import { LiveButton } from "#/components/live-button"; +import { DisclosurePrint } from "#/components/disclosure-print"; import { Notice } from "#/components/notice"; import { loadDisclosures } from "#/lib/client"; import { getStored } from "#/lib/forms"; @@ -75,7 +75,8 @@ function StoredContent({ }: { found: NonNullable>>; }) { - const { title, controller, withdrawal, keepsApart, feedback, columns, historyDays } = found; + const { title, controller, withdrawal, keepsApart, feedback, columns, historyDays, embed } = + found; const hash = useLocation({ select: (location) => location.hash }); const [fragment, setFragment] = useState(); useEffect(() => setFragment(hash), [hash]); @@ -89,6 +90,24 @@ function StoredContent({

{t.lead}

{t.entry}

+ {embed && ( +
+

{t.embedTitle}

+

{t.embed}

+
    + {Object.entries(embed.context).map( + ([key, values]) => + values && + values.length > 0 && ( +
  • + {strings.embed.fields[key as keyof typeof strings.embed.fields]}:{" "} + {values.join(", ")} +
  • + ), + )} +
+
+ )}

{t.controllerTitle}

@@ -174,7 +193,7 @@ function StoredContent({ {/* What is on paper needs no buttons. */}
- window.print()}>{t.print} + {privateLink ? ( Not found

Not found

", { + status: 404, + headers: { + "Content-Type": "text/html; charset=utf-8", + "Cache-Control": "private, no-store", + "Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'; sandbox", + "X-Frame-Options": "DENY", + }, + }); +} + export default { async fetch(request) { refuseProductionDemoTurnstileTestKeys(env); if (!env.DB || !env.BETTER_AUTH_SECRET) return notSetUp(); + const url = new URL(request.url); + const origins = embedOrigins(); + if (env.FORMS_RESPONDENT_ORIGIN !== undefined && !origins) return denied(); + const respondent = origins && url.origin === origins.respondent; + let cleanRequest: Request = request; + // Owner origin: /login, /account, /forms/*, /api/auth/*, /api/owner/* and + // /_serverFn/* (including owner RPC and actions). Respondent origin: registered + // /f/* documents, /api/forms/*, /api/responses/* and static assets. A forged + // Cookie or Sec-Fetch-Site header cannot cross this gate. + if (origins && url.origin !== origins.owner && !respondent) return denied(); + if (respondent) { + const formDocument = request.method === "GET" && embedFormPath(url.pathname); + const publicAsset = + request.method === "GET" && + (/^\/assets\//.test(url.pathname) || + /^\/(?:favicon\.svg|apple-touch-icon\.png)$/.test(url.pathname)); + const formApi = + /^\/api\/forms\/([a-z0-9][a-z0-9_-]{0,63})\/(entry|disclosures|responses|detached)$/.exec( + url.pathname, + ); + const responseApi = + /^\/api\/responses\/[A-Za-z0-9_-]{16}(?:\/(disclosures|progress|feedback-preview|complete))?$/.exec( + url.pathname, + ); + const formAction = formApi?.[2]; + const responseAction = responseApi?.[1]; + const formAllowed = + formApi && + request.method === + (formAction === "entry" || formAction === "disclosures" ? "GET" : "POST"); + const responseAllowed = + responseApi && + (responseAction === "progress" || + responseAction === "feedback-preview" || + responseAction === "complete" + ? request.method === "POST" + : request.method === "GET" || (!responseAction && request.method === "DELETE")); + if (url.pathname.startsWith("/embed/")) { + const id = /^\/embed\/([a-z0-9][a-z0-9_-]{0,63})\/?$/.exec(url.pathname)?.[1]; + if (request.method !== "GET" || !id) return denied(); + const host = await registeredHost(`/f/${id}`); + if (!host) return denied(); + return new Response(null, { + status: 302, + headers: { + Location: `${url.origin}/f/${id}`, + "Cache-Control": "private, no-store", + "Content-Security-Policy": `default-src 'none'; frame-ancestors ${host}; sandbox allow-scripts allow-same-origin allow-forms`, + }, + }); + } + if (!publicAsset && !formAllowed && !responseAllowed && !formDocument) return denied(); + if ( + formAllowed && + formAction !== "responses" && + !(await registeredHost(`/f/${formApi[1]}/stored`)) + ) + return denied(); + if (formDocument && !(await registeredHost(url.pathname))) return denied(); + // Respondents have no account cookie. Do not pass a forged one to app code or + // allow a response from this origin to create an owner session. + const headers = new Headers(request.headers); + headers.delete("Cookie"); + cleanRequest = new Request(request, { headers }); + } const nonce = newNonce(); - const response = await handler.fetch(request, { context: { nonce } }); - // Vite's dev server adds inline scripts of its own for hot reload, which have no nonce. - if (import.meta.env.DEV) return response; - return withSecurityHeaders(request, response, nonce, demoMode()); + const response = await handler.fetch(cleanRequest, { context: { nonce } }); + // Vite's dev server adds inline scripts of its own for hot reload. Its frame policy + // still applies even though the production script nonce policy cannot. + if (import.meta.env.DEV) { + const dev = new Response(response.body, response); + if (dev.headers.get("Content-Type")?.startsWith("text/html")) { + const host = respondent ? await registeredHost(url.pathname) : undefined; + dev.headers.set( + "Content-Security-Policy", + host + ? `frame-ancestors ${host}; sandbox allow-scripts allow-same-origin allow-forms` + : "frame-ancestors 'none'", + ); + if (host) dev.headers.delete("X-Frame-Options"); + else dev.headers.set("X-Frame-Options", "DENY"); + dev.headers.set("Cache-Control", "private, no-store"); + } + if (respondent) { + dev.headers.delete("Set-Cookie"); + dev.headers.delete("Access-Control-Allow-Origin"); + dev.headers.delete("Access-Control-Allow-Credentials"); + } + return dev; + } + const host = + respondent && response.headers.get("Content-Type")?.startsWith("text/html") + ? await registeredHost(url.pathname) + : undefined; + const secured = withSecurityHeaders(cleanRequest, response, nonce, demoMode(), host); + if (respondent) { + secured.headers.delete("Set-Cookie"); + secured.headers.delete("Access-Control-Allow-Origin"); + secured.headers.delete("Access-Control-Allow-Credentials"); + } + return secured; }, async scheduled() { // Only the demo may keep its examples; anywhere else a stray trigger changes nothing. diff --git a/apps/web/src/server/api.ts b/apps/web/src/server/api.ts index 21d0a2f..45055b3 100644 --- a/apps/web/src/server/api.ts +++ b/apps/web/src/server/api.ts @@ -7,6 +7,7 @@ import { readCapped, TooLarge } from "./body"; import { createDb } from "./db"; import { detachedCapability } from "./db/schema"; import { demoMode, turnstileSiteKey } from "./demo"; +import { acceptedContext, embedOrigins, exactRegisteredHost } from "./embed"; import { prepareFeedbackPreview } from "./feedback"; import { findForm, findPublicVersion, hasFeedbackConnector } from "./forms"; import { @@ -209,6 +210,7 @@ async function disclosures(definition: Awaited 0, + embed: definition.embed ?? null, feedback: await hasFeedbackConnector(definition.id), columns: storedColumns(), historyDays: HISTORY_DAYS, @@ -246,6 +248,14 @@ async function responseOf(request: Request, id: string): Promise { export function startResponse(request: Request, formId: string): Promise { return answering(async () => { const form = await formOf(formId); + const respondentOrigin = embedOrigins()?.respondent; + const url = new URL(request.url); + const respondent = url.origin === respondentOrigin; + const embedVersion = request.headers.get("X-Embed-Version"); + const contextHeader = request.headers.get("X-Embed-Context"); + const embedHost = respondent ? exactRegisteredHost(form.definition) : undefined; + if (respondent && (!embedHost || form.entryMode !== "open")) + throw new Refusal(404, "There is no such form."); // A draft does not exist for a respondent yet. A closed form does, and says so. if (form.state === "draft" || !(await entryAllowed(form, request))) throw new Refusal(404, "There is no such form."); @@ -253,6 +263,24 @@ export function startResponse(request: Request, formId: string): Promise; + if (contextHeader !== null) { + if (!respondent || contextHeader.length > 512) + throw new Refusal(400, "This context is not accepted for this form."); + let value: unknown; + try { + value = JSON.parse(contextHeader); + } catch { + throw new Refusal(400, "This context is not accepted for this form."); + } + context = acceptedContext(form.definition, value); + if (!context) throw new Refusal(400, "This context is not accepted for this form."); + } const body = await readBody(request, demoMode() ? demoCreateBody : createBody); await withinCeiling( env.START_LIMIT, @@ -273,7 +301,7 @@ export function startResponse(request: Request, formId: string): Promise { + const id = embedFormPath(pathname); + if (!id) return undefined; + let form: Awaited>; + try { + form = await findForm(id); + } catch { + return undefined; + } + if (!form || form.state === "draft") return undefined; + if (form.entryMode !== "open" && /^\/f\/[^/]+\/?$/.test(pathname)) return undefined; + return exactRegisteredHost(form.definition); +} diff --git a/apps/web/src/server/env.d.ts b/apps/web/src/server/env.d.ts index 26a18f2..3c3a39a 100644 --- a/apps/web/src/server/env.d.ts +++ b/apps/web/src/server/env.d.ts @@ -4,6 +4,8 @@ declare namespace Cloudflare { interface Env { /** Public URL of the app. Inferred from the request when unset. */ BETTER_AUTH_URL?: string; + /** Distinct public origin used only for embedded respondent pages and APIs. */ + FORMS_RESPONDENT_ORIGIN?: string; /** * Who may make an account: whole addresses, separated by commas. Anyone when unset. An * entry that names a domain is ignored. See src/lib/sign-up-allow.ts. diff --git a/apps/web/src/server/responses.ts b/apps/web/src/server/responses.ts index bb6714e..b059d3a 100644 --- a/apps/web/src/server/responses.ts +++ b/apps/web/src/server/responses.ts @@ -6,6 +6,7 @@ import { definitionSchema, detachedQuestions, detachedQuestionsShown, + type EmbedContext, isAnswered, isChoices, placesOf, @@ -60,6 +61,7 @@ export async function createResponse( db: Database, form: Form, device: Device, + embed?: { context?: EmbedContext; origin: string }, ): Promise<{ id: string; secret: string }> { const id = randomToken(12); const secret = randomToken(32); @@ -79,6 +81,7 @@ export async function createResponse( answersVersion: ANSWERS_VERSION, secretSeal: seal, device, + embedContext: embed?.context ? JSON.stringify(embed.context) : null, createdAt: now, updatedAt: now, }), @@ -98,6 +101,8 @@ export async function createResponse( answersVersion: ANSWERS_VERSION, seal, device, + embedContext: embed?.context ? JSON.stringify(embed.context) : null, + embedOrigin: embed?.origin, now, entryMode: form.entryMode, entrySeal: form.entrySeal, diff --git a/apps/web/src/server/security-headers.ts b/apps/web/src/server/security-headers.ts index cc819c0..c5bb363 100644 --- a/apps/web/src/server/security-headers.ts +++ b/apps/web/src/server/security-headers.ts @@ -9,10 +9,10 @@ export function newNonce(): string { * wrote and collects what a respondent types, so a script from elsewhere could read answers as * they are given. * - * Nothing may frame a page yet. Embedding a form in another site is planned, with a list of - * allowed sites per form, and that list is what will go into `frame-ancestors` then. + * A registered respondent page can be framed by its one published host origin. The same + * sandbox is enforced here even when a host omits the iframe attribute. */ -export function contentSecurityPolicy(nonce: string, turnstile = false): string { +export function contentSecurityPolicy(nonce: string, turnstile = false, host?: string): string { const cloudflare = "https://challenges.cloudflare.com"; return [ "default-src 'none'", @@ -22,7 +22,8 @@ export function contentSecurityPolicy(nonce: string, turnstile = false): string "font-src 'self'", `connect-src 'self'${turnstile ? ` ${cloudflare}` : ""}`, ...(turnstile ? [`frame-src ${cloudflare}`] : []), - "frame-ancestors 'none'", + `frame-ancestors ${host ?? "'none'"}`, + ...(host ? ["sandbox allow-scripts allow-same-origin allow-forms"] : []), "base-uri 'none'", "form-action 'self'", ].join("; "); @@ -34,6 +35,7 @@ export function withSecurityHeaders( response: Response, nonce: string, turnstile = false, + host?: string, ): Response { const secured = new Response(response.body, response); const { headers } = secured; @@ -51,9 +53,9 @@ export function withSecurityHeaders( headers.get("Content-Type")?.startsWith("text/html") && !headers.has("Content-Security-Policy") ) { - headers.set("Content-Security-Policy", contentSecurityPolicy(nonce, turnstile)); - // For browsers that predate `frame-ancestors`. - headers.set("X-Frame-Options", "DENY"); + headers.set("Content-Security-Policy", contentSecurityPolicy(nonce, turnstile, host)); + if (host) headers.delete("X-Frame-Options"); + else headers.set("X-Frame-Options", "DENY"); // The page carries this response's nonce. headers.set("Cache-Control", "private, no-store"); } diff --git a/apps/web/src/server/statements.ts b/apps/web/src/server/statements.ts index 528d44a..7d45f43 100644 --- a/apps/web/src/server/statements.ts +++ b/apps/web/src/server/statements.ts @@ -385,6 +385,8 @@ export function startStatements( answersVersion: number; seal: string; device: string; + embedContext?: string | null; + embedOrigin?: string | null; now: number; } & EntryAuthority, ): Statement[] { @@ -399,13 +401,17 @@ export function startStatements( return [ { sql: `INSERT INTO definition (hash, form_id, json) SELECT ?1, ?2, ?3 WHERE ${entryGuard(4, "?1")} + AND (?10 IS NULL OR EXISTS (SELECT 1 FROM form WHERE id = ?2 AND definition_hash = ?1)) ON CONFLICT (hash) DO NOTHING`, - params: [start.hash, start.formId, start.json, ...entry], + params: [start.hash, start.formId, start.json, ...entry, start.embedOrigin ?? null], }, { sql: `INSERT INTO response - (id, form_id, definition_hash, answers_version, secret_seal, device, created_at, updated_at) - SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7 WHERE ${entryGuard(8, "?3")}`, + (id, form_id, definition_hash, answers_version, secret_seal, device, created_at, updated_at, embed_context) + SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7, ?14 WHERE ${entryGuard(8, "?3")} + AND (?16 IS NULL OR (EXISTS (SELECT 1 FROM form WHERE id = ?2 AND definition_hash = ?3) + AND EXISTS (SELECT 1 FROM definition WHERE hash = ?3 + AND json_extract(json, ?15) = ?16)))`, params: [ start.id, start.formId, @@ -415,6 +421,9 @@ export function startStatements( start.device, start.now, ...entry, + start.embedContext ?? null, + "$.embed.origin", + start.embedOrigin ?? null, ], }, ]; diff --git a/apps/web/test/api.test.ts b/apps/web/test/api.test.ts index 733a868..da3766c 100644 --- a/apps/web/test/api.test.ts +++ b/apps/web/test/api.test.ts @@ -95,6 +95,7 @@ describe("starting a response", () => { "created_at", "definition_hash", "device", + "embed_context", "form_id", "id", "position", diff --git a/apps/web/test/embed.test.ts b/apps/web/test/embed.test.ts new file mode 100644 index 0000000..8d68efd --- /dev/null +++ b/apps/web/test/embed.test.ts @@ -0,0 +1,465 @@ +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { startStatements } from "../src/server/statements"; +import { as, signUp } from "./accounts"; +import { type Forms, startForms } from "./forms-worker"; +import { shortFeedback } from "./short-feedback"; + +const owner = "http://localhost:4771"; +const respondent = "http://127.0.0.1:4771"; +const at = (path: string) => `${respondent}${path}`; +let forms: Forms; + +beforeAll(async () => { + forms = await startForms({ origin: owner, settings: { FORMS_RESPONDENT_ORIGIN: respondent } }); +}); +afterAll(() => forms.dispose()); + +describe("respondent origin", () => { + it.each([ + { BETTER_AUTH_URL: "", FORMS_RESPONDENT_ORIGIN: respondent }, + { BETTER_AUTH_URL: owner, FORMS_RESPONDENT_ORIGIN: `${respondent}/wrong` }, + { BETTER_AUTH_URL: respondent, FORMS_RESPONDENT_ORIGIN: respondent }, + ])( + "refuses requests when the configured origin split is invalid ($FORMS_RESPONDENT_ORIGIN)", + async (settings) => { + const app = await startForms({ origin: owner, settings }); + try { + for (const path of ["/login", "/api/auth/sign-in/email", "/f/home-baking"]) { + const response = await app.fetch(at(path)); + expect(response.status).toBe(404); + expect(response.headers.get("Set-Cookie")).toBeNull(); + } + } finally { + await app.dispose(); + } + }, + ); + + it("frames only the registered public form, with the same sandbox on the document", async () => { + const redirect = await forms.fetch(at("/embed/home-baking")); + expect(redirect.status).toBe(302); + expect(redirect.headers.get("location")).toBe(at("/f/home-baking")); + expect(redirect.headers.get("Cache-Control")).toBe("private, no-store"); + expect(redirect.headers.get("Content-Security-Policy")).toContain(`frame-ancestors ${owner}`); + expect(redirect.headers.get("Content-Security-Policy")).toContain( + "sandbox allow-scripts allow-same-origin allow-forms", + ); + const page = await forms.fetch(at("/f/home-baking")); + expect(page.status).toBe(200); + const policy = page.headers.get("Content-Security-Policy") ?? ""; + expect(policy).toContain(`frame-ancestors ${owner}`); + expect(policy).toContain("sandbox allow-scripts allow-same-origin allow-forms"); + expect(page.headers.get("X-Frame-Options")).toBeNull(); + expect(page.headers.get("Cache-Control")).toBe("private, no-store"); + for (const path of ["/f/home-baking/consent", "/f/home-baking/stored"]) { + const disclosure = await forms.fetch(at(path)); + expect(disclosure.headers.get("Content-Security-Policy")).toContain( + `frame-ancestors ${owner}`, + ); + } + }); + + it("rejects owner/auth/RPC paths and forged owner cookies on the respondent host", async () => { + for (const path of [ + "/forms", + "/account", + "/login", + "/api/auth/sign-in/email", + "/api/owner/forms", + "/_serverFn/forged", + ]) { + const answer = await forms.fetch(at(path), { + headers: { Cookie: "better-auth.session_token=forged", "Sec-Fetch-Site": "same-origin" }, + }); + expect(answer.status).toBe(404); + expect(answer.headers.get("Set-Cookie")).toBeNull(); + } + const forgedSignIn = await forms.fetch(at("/api/auth/sign-in/email"), { + method: "POST", + headers: { + "Content-Type": "application/json", + Origin: respondent, + Cookie: "better-auth.session_token=forged", + }, + body: JSON.stringify({ email: "test@example.test", password: "forged" }), + }); + expect(forgedSignIn.status).toBe(404); + expect(forgedSignIn.headers.get("Set-Cookie")).toBeNull(); + const cors = await forms.fetch(at("/api/forms/home-baking/entry"), { + headers: { Origin: owner }, + }); + expect(cors.headers.get("Access-Control-Allow-Origin")).toBeNull(); + }); + + it("denies framing for unknown paths, unregistered forms and another port", async () => { + for (const path of ["/f/unknown", "/f/home-baking/unknown", "/embed/unknown"]) { + const answer = await forms.fetch(at(path)); + expect(answer.headers.get("X-Frame-Options")).toBe("DENY"); + expect(answer.headers.get("Content-Security-Policy")).toContain("frame-ancestors 'none'"); + expect(answer.headers.get("Cache-Control")).toBe("private, no-store"); + } + const otherPort = await forms.fetch("http://127.0.0.1:4772/f/home-baking"); + expect(otherPort.status).toBe(404); + }); + + it("accepts only declared bounded public context once at Start", async () => { + const entry = await forms.fetch(at("/api/forms/home-baking/entry")); + const version = String(((await entry.json()) as { version: string }).version); + const stored = await forms.fetch(at(`/f/home-baking/stored?v=${version}`)); + expect(stored.status).toBe(200); + const copy = await stored.text(); + expect(copy).toContain("embedContext"); + expect(copy).toContain("No feedback is dispatched"); + expect((await forms.fetch(at("/f/home-baking/stored?v=not-a-version"))).status).toBe(404); + const headers = { + "Content-Type": "application/json", + Origin: respondent, + "X-Embed-Version": version, + }; + const start = (context: unknown, more: Record = {}) => + forms.fetch(at("/api/forms/home-baking/responses"), { + method: "POST", + headers: { + ...headers, + ...(context === undefined ? {} : { "X-Embed-Context": JSON.stringify(context) }), + ...more, + }, + body: JSON.stringify({ device: "desk", consent: true }), + }); + for (const value of [ + { publicRoute: "/recipes?item=7" }, + { publicRoute: "/recipes#step" }, + { product: "not-declared" }, + { product: "x".repeat(65) }, + { publicRoute: "/recipes", secret: "x" }, + ]) { + expect((await start(value)).status).toBe(400); + } + expect((await start({ product: "bread-lab" }, { Origin: owner })).status).toBe(400); + expect((await start({ product: "bread-lab" }, { "X-Embed-Version": "other" })).status).toBe( + 400, + ); + const accepted = await start({ product: "bread-lab", publicRoute: "/recipes" }); + expect(accepted.status).toBe(201); + const { id } = (await accepted.json()) as { id: string }; + const row = await forms.db + .prepare("SELECT embed_context FROM response WHERE id = ?1") + .bind(id) + .first<{ embed_context: string }>(); + expect(JSON.parse(row?.embed_context ?? "null")).toEqual({ + product: "bread-lab", + publicRoute: "/recipes", + }); + expect((await start(undefined, { Origin: owner })).status).toBe(400); + expect((await start(undefined, { "X-Embed-Version": "" })).status).toBe(400); + const withoutContext = await start(undefined); + expect(withoutContext.status).toBe(201); + const withoutContextId = ((await withoutContext.json()) as { id: string }).id; + expect( + await forms.db + .prepare("SELECT embed_context FROM response WHERE id = ?1") + .bind(withoutContextId) + .first(), + ).toEqual({ embed_context: null }); + }); + + it("keeps closed forms framed for their notice, but refuses Start", async () => { + const app = await startForms({ + settings: { FORMS_RESPONDENT_ORIGIN: "https://respondent.test" }, + }); + try { + const cookie = await signUp(app); + const id = "closed-embed-feedback"; + const definition = { + ...shortFeedback(id), + embed: { origin: "https://host.test", context: {} }, + }; + expect( + ( + await app.fetch( + "/api/owner/forms", + as(cookie, { method: "POST", body: JSON.stringify({ definition }) }), + ) + ).status, + ).toBe(201); + for (const state of ["open", "closed"]) { + expect( + ( + await app.fetch( + `/api/owner/forms/${id}/state`, + as(cookie, { method: "POST", body: JSON.stringify({ state }) }), + ) + ).status, + ).toBe(200); + } + const page = await app.fetch(`https://respondent.test/f/${id}`); + expect(page.status).toBe(200); + expect(page.headers.get("Content-Security-Policy")).toContain( + "frame-ancestors https://host.test", + ); + const start = await app.fetch(`https://respondent.test/api/forms/${id}/responses`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ device: "desk" }), + }); + expect(start.status).toBe(403); + } finally { + await app.dispose(); + } + }); + + it("keeps authenticated optional feedback available on the respondent origin", async () => { + const app = await startForms({ + origin: owner, + settings: { FORMS_RESPONDENT_ORIGIN: respondent }, + }); + try { + await app.db + .prepare( + `INSERT INTO feedback_connector ( + id, form_id, destination, audience, generation, measure_question_id, + measure_kind, context_json, version, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, 1, 1)`, + ) + .bind( + "embed-fixture", + "home-baking", + "Made-up feedback inbox", + "the made-up team", + "fixture-generation", + "often", + "choice", + "{}", + ) + .run(); + + const entry = await app.fetch(at("/api/forms/home-baking/entry")); + const { version } = (await entry.json()) as { version: string }; + const disclosures = await app.fetch(at("/api/forms/home-baking/disclosures")); + expect(disclosures.status).toBe(200); + expect(await disclosures.json()).toMatchObject({ embed: { origin: owner }, feedback: true }); + + const headers = { "Content-Type": "application/json", Origin: respondent }; + const start = await app.fetch(at("/api/forms/home-baking/responses"), { + method: "POST", + headers: { ...headers, "X-Embed-Version": version }, + body: JSON.stringify({ device: "desk", consent: true }), + }); + expect(start.status).toBe(201); + const { id, secret } = (await start.json()) as { id: string; secret: string }; + const post = (action: string, body: unknown) => + app.fetch(at(`/api/responses/${id}/${action}`), { + method: "POST", + headers: { ...headers, Authorization: `Bearer ${secret}` }, + body: JSON.stringify(body), + }); + expect( + ( + await post("progress", { + answer: { question: "often", value: { option: "weekly" }, activeMs: 500 }, + }) + ).status, + ).toBe(200); + + const preview = await post("feedback-preview", { includeNote: false }); + expect(preview.status).toBe(200); + const prepared = (await preview.json()) as { preview: string; projection: unknown }; + expect(prepared.projection).toEqual({ choice: "weekly" }); + expect((await post("complete", { feedbackPreview: prepared.preview })).status).toBe(200); + expect( + await app.db + .prepare("SELECT COUNT(*) AS count FROM feedback_outbox WHERE response_id = ?") + .bind(id) + .first(), + ).toEqual({ count: 1 }); + } finally { + await app.dispose(); + } + }); + + it("rejects a host registration on the respondent origin itself", async () => { + const app = await startForms({ + settings: { FORMS_RESPONDENT_ORIGIN: "https://respondent.test" }, + }); + try { + const cookie = await signUp(app); + const id = "same-origin-embed"; + const definition = { + ...shortFeedback(id), + embed: { origin: "https://respondent.test", context: {} }, + }; + expect( + ( + await app.fetch( + "/api/owner/forms", + as(cookie, { method: "POST", body: JSON.stringify({ definition }) }), + ) + ).status, + ).toBe(201); + expect( + ( + await app.fetch( + `/api/owner/forms/${id}/state`, + as(cookie, { method: "POST", body: JSON.stringify({ state: "open" }) }), + ) + ).status, + ).toBe(200); + expect((await app.fetch(`https://respondent.test/embed/${id}`)).status).toBe(404); + expect((await app.fetch(`https://respondent.test/f/${id}`)).status).toBe(404); + } finally { + await app.dispose(); + } + }); + + it("rejects pending Starts with and without context after the embed is removed", async () => { + const app = await startForms({ + settings: { FORMS_RESPONDENT_ORIGIN: "https://respondent.test" }, + }); + try { + const cookie = await signUp(app); + const id = "embed-version-race"; + const definition = { + ...shortFeedback(id), + embed: { origin: "https://host.test", context: { product: ["bread-lab"] } }, + }; + expect( + ( + await app.fetch( + "/api/owner/forms", + as(cookie, { method: "POST", body: JSON.stringify({ definition }) }), + ) + ).status, + ).toBe(201); + expect( + ( + await app.fetch( + `/api/owner/forms/${id}/state`, + as(cookie, { method: "POST", body: JSON.stringify({ state: "open" }) }), + ) + ).status, + ).toBe(200); + const old = await app.fetch(`/api/forms/${id}/entry`); + const hash = ((await old.json()) as { version: string }).version; + const pending = [JSON.stringify({ product: "bread-lab" }), null].map((embedContext, index) => + startStatements({ + id: `synthetic-race-${index}`, + formId: id, + hash, + json: JSON.stringify(definition), + answersVersion: 1, + seal: "synthetic-seal", + device: "desk", + now: Date.now(), + embedContext, + embedOrigin: "https://host.test", + entryMode: "open", + entrySeal: null, + entryGeneration: 0, + entryExpiresAt: null, + }), + ); + const changed = await app.fetch( + `/api/owner/forms/${id}/definition`, + as(cookie, { + method: "POST", + body: JSON.stringify({ + definition: { ...shortFeedback(id), title: "Revised synthetic feedback" }, + }), + }), + ); + expect(changed.status).toBe(200); + for (const statements of pending) { + const written = await app.db.batch( + statements.map(({ sql, params }) => app.db.prepare(sql).bind(...params)), + ); + expect(written.at(-1)?.meta.changes).toBe(0); + } + const rows = await app.db + .prepare("SELECT id FROM response WHERE form_id = ?1") + .bind(id) + .all(); + expect(rows.results).toHaveLength(0); + const after = await app.fetch(`https://respondent.test/api/forms/${id}/responses`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-Embed-Version": hash, + Origin: "https://respondent.test", + }, + body: JSON.stringify({ device: "desk" }), + }); + expect(after.status).toBe(404); + } finally { + await app.dispose(); + } + }); + + it("still requires the demo challenge before an embedded Start", async () => { + const app = await startForms({ + origin: owner, + settings: { FORMS_RESPONDENT_ORIGIN: respondent, FORMS_DEMO: "1" }, + }); + try { + const published = await app.fetch(at("/api/forms/home-baking/entry")); + const { version } = (await published.json()) as { version: string }; + const started = await app.fetch(at("/api/forms/home-baking/responses"), { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-Embed-Version": version, + Origin: respondent, + }, + body: JSON.stringify({ device: "desk", consent: true }), + }); + expect(started.status).toBe(503); + const rows = await app.db.prepare("SELECT id FROM response").all(); + expect(rows.results).toHaveLength(0); + } finally { + await app.dispose(); + } + }); + + it("verifies each demo Start against the hostname that served it", async () => { + const app = await startForms({ + origin: owner, + settings: { + FORMS_RESPONDENT_ORIGIN: respondent, + FORMS_DEMO: "1", + TURNSTILE_SITE_KEY: "synthetic-key", + TURNSTILE_SECRET_KEY: "synthetic-secret", + TURNSTILE_HOSTNAME: "localhost", + }, + }); + try { + const published = await app.fetch(at("/api/forms/home-baking/entry")); + const { version } = (await published.json()) as { version: string }; + const start = (origin: string, turnstile: string) => + app.fetch(`${origin}/api/forms/home-baking/responses`, { + method: "POST", + headers: { + "Content-Type": "application/json", + ...(origin === respondent ? { "X-Embed-Version": version, Origin: origin } : {}), + }, + body: JSON.stringify({ device: "desk", consent: true, turnstile }), + }); + expect((await start(respondent, "owner-hostname-token")).status).toBe(403); + expect((await start(owner, "respondent-hostname-token")).status).toBe(403); + expect((await app.db.prepare("SELECT id FROM response").all()).results).toHaveLength(0); + expect((await start(respondent, "respondent-hostname-token")).status).toBe(201); + expect((await start(owner, "owner-hostname-token")).status).toBe(201); + } finally { + await app.dispose(); + } + }); + + it("has no embed surface without a distinct respondent origin", async () => { + const app = await startForms({ origin: owner }); + try { + expect((await app.fetch("/embed/home-baking")).status).toBe(404); + const page = await app.fetch("/f/home-baking"); + expect(page.headers.get("Content-Security-Policy")).toContain("frame-ancestors 'none'"); + } finally { + await app.dispose(); + } + }); +}); diff --git a/apps/web/test/forms-worker.ts b/apps/web/test/forms-worker.ts index 199de23..a0d3516 100644 --- a/apps/web/test/forms-worker.ts +++ b/apps/web/test/forms-worker.ts @@ -111,13 +111,14 @@ export async function startForms({ } const checked = secret !== undefined && sent.get("secret") === secret && token !== "wrong-token"; + let hostname = settings.TURNSTILE_HOSTNAME; + if (token === "wrong-hostname-token") hostname = "other.example.test"; + if (token === "respondent-hostname-token" && settings.FORMS_RESPONDENT_ORIGIN) + hostname = new URL(settings.FORMS_RESPONDENT_ORIGIN).hostname; return Response.json({ success: checked, action: token === "wrong-action-token" ? "other-action" : "start-response", - hostname: - token === "wrong-hostname-token" - ? "other.example.test" - : settings.TURNSTILE_HOSTNAME, + hostname, }); } return new Response("Outbound requests are blocked in this test", { status: 502 }); diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index f406ff3..70ec448 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -23,9 +23,22 @@ export default defineConfig(({ command }) => ({ config: (config) => { // The example forms are served from their files in local development and in the // build the browser tests run against (e2e/build.mjs), and nowhere else. + const e2ePort = Number(process.env.FORMS_E2E_PORT) || 4771; const localForms = command === "serve" || process.env.FORMS_E2E - ? { vars: { ...config.vars, FORMS_EXAMPLES: "1", FORMS_PRIVATE_ENTRY: "1" } } + ? { + vars: { + ...config.vars, + FORMS_EXAMPLES: "1", + FORMS_PRIVATE_ENTRY: "1", + ...(process.env.FORMS_E2E + ? { + BETTER_AUTH_URL: `http://localhost:${e2ePort}`, + FORMS_RESPONDENT_ORIGIN: `http://127.0.0.1:${e2ePort}`, + } + : {}), + }, + } : {}; if (command !== "serve") return localForms; // In dev only: `secrets.required` would drop the optional settings in .dev.vars. diff --git a/docs/architecture.md b/docs/architecture.md index 7129075..1888569 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -103,6 +103,28 @@ The report says what the source held, what each section became and what was chan ## The app (`apps/web`) +### Embedded respondent origin + +An optional `FORMS_RESPONDENT_ORIGIN` and the owner `BETTER_AUTH_URL` split one Worker by exact +origin in `server.ts`. The respondent origin exposes registered `/f/` documents, their +respondent APIs and static assets. It refuses auth, owner routes and TanStack server function +addresses before the router, even with forged cookies. The published definition's `embed.origin` +is the single exact ancestor allowed for that form's respondent documents; the rest retain +`frame-ancestors 'none'`. The iframe and response CSP both require scripts, same origin and forms +only. That leaves top navigation, popups and downloads outside the sandbox. Documents and errors +are private and no-store, and the host registration grants no API CORS. + +The host's loader is a movable module at `embed/loader.mjs`. It creates an entry, a direct public +link on the owner origin and the iframe after the host's initial content. Version 1 messages +carry ready, size, close and declared context. Both sides check the sender window and exact +origin. A nonce ties each ready and context exchange to the current document. After a disclosure +page the loader responds with the same context it copied at mount. The form displays the first +valid context before Start and saves it with the response. Every respondent-origin Start checks +the published definition and live embed registration in the guarded write, including direct +iframes that send no context. The same consent, stored-data, answer and withdrawal controls +serve ordinary and embedded entry. The private address shown inside the form uses the owner +origin so an issued response can still be opened when the embed registration changes. + ### Pages | Address | What it is | diff --git a/docs/data.md b/docs/data.md index 64eb18d..0fbb63a 100644 --- a/docs/data.md +++ b/docs/data.md @@ -17,6 +17,13 @@ first page. That page takes its list from the same schema as the tables below, a ## Where things are +An embedded response may also keep `response.embed_context`: a JSON object of the exact public +product, version, route and plan-category values declared by the form and accepted when the +respondent pressed Start. An ordinary response has null there. The values are shown before Start +and described on the form's versioned “What is stored” page. Forms does not dispatch them or the +answers to the product host. The iframe protocol sends readiness, height and close signals, and +receives context; it sends no answers or private response link to the host. + Everything the app stores is in one D1 database. It uses no KV, no R2 and no Durable Object. ### About a respondent diff --git a/docs/self-hosting.md b/docs/self-hosting.md index 8d2524e..4462a6e 100644 --- a/docs/self-hosting.md +++ b/docs/self-hosting.md @@ -7,17 +7,18 @@ deployment stores, and what deleting does, is in [data.md](data.md). ## Settings -| Name | What it does | -| ---------------------- | ---------------------------------------------------------------------------- | -| `BETTER_AUTH_SECRET` | Required secret. Signs the sessions of the people who run forms | -| `BETTER_AUTH_URL` | Optional. The app's own URL, which requests that change something must match | -| `SIGN_UP_ALLOW` | Optional. Who may make an account: whole addresses, comma-separated | -| `FORMS_EXAMPLES` | Never on a deployment. `"1"` serves the made-up forms in `examples/` | -| `FORMS_DEMO` | Never for self-hosting. `"1"` is Gateweave's public demo switch | -| `FORMS_PRIVATE_ENTRY` | Optional. `"1"` lets owners switch an open form to private entry | -| `TURNSTILE_SITE_KEY` | Public key of the demo's Turnstile widget | -| `TURNSTILE_SECRET_KEY` | Secret key for the same Turnstile widget | -| `TURNSTILE_HOSTNAME` | Hostname where the demo's Turnstile token must have been issued | +| Name | What it does | +| ------------------------- | ----------------------------------------------------------------------------------------------------------------- | +| `BETTER_AUTH_SECRET` | Required secret. Signs the sessions of the people who run forms | +| `BETTER_AUTH_URL` | Optional. The app's own URL, which requests that change something must match | +| `SIGN_UP_ALLOW` | Optional. Who may make an account: whole addresses, comma-separated | +| `FORMS_EXAMPLES` | Never on a deployment. `"1"` serves the made-up forms in `examples/` | +| `FORMS_DEMO` | Never for self-hosting. `"1"` is Gateweave's public demo switch | +| `FORMS_PRIVATE_ENTRY` | Optional. `"1"` lets owners switch an open form to private entry | +| `FORMS_RESPONDENT_ORIGIN` | Optional. A distinct Forms origin for registered product embeds. Requires `BETTER_AUTH_URL` for the owner origin. | +| `TURNSTILE_SITE_KEY` | Public key of the demo's Turnstile widget | +| `TURNSTILE_SECRET_KEY` | Secret key for the same Turnstile widget | +| `TURNSTILE_HOSTNAME` | Hostname where the demo's Turnstile token must have been issued | Set `BETTER_AUTH_URL` and `SIGN_UP_ALLOW` on anything that is reachable from outside. Without `SIGN_UP_ALLOW`, anyone who reaches the server can make an account and bring forms in. No email @@ -121,6 +122,42 @@ The Wrangler config disables [Version URLs](https://developers.cloudflare.com/wo Check that any older Version URLs and aliases are unreachable before activation. They can serve an older Worker against its configured database even after your main address runs newer code. +### Embedding a public form + +Route a second, distinct origin to the same Worker and set `FORMS_RESPONDENT_ORIGIN` to that +origin and `BETTER_AUTH_URL` to the owner origin. Both values must be exact origins, with scheme, +host and optional port. Use HTTPS, with HTTP allowed on loopback for local development. A Worker +with an invalid configured origin pair refuses requests. A published definition opts in with +`embed.origin`, the exact product host origin, and `embed.context`, lists of public values for `product`, +`publicVersion`, `publicRoute` and `planCategory`. A form without both the respondent origin and +this registration has no embed entry. A registration equal to the respondent origin is refused. +To remove an origin split, detach the respondent hostname from the Worker before clearing +`FORMS_RESPONDENT_ORIGIN`. + +The product serves `embed/loader.mjs` from its own build or a pinned self-hosted copy, after its +initial content. It mounts a compact entry, a direct public link and an iframe at +`/embed/`. Pass `respondentOrigin` as `FORMS_RESPONDENT_ORIGIN` and +`publicOrigin` as `BETTER_AUTH_URL` to `mountFormsFeedback`. A product may also create an iframe with +`sandbox="allow-scripts allow-same-origin allow-forms"`. Forms enforces the same sandbox in its +CSP. The product host must permit the respondent origin in its own `frame-src`. The Forms page +names only the exact registered host in `frame-ancestors`; a foreign outer frame also blocks it. +The owner origin retains auth, `/forms`, `/account`, `/api/owner` and `/_serverFn`; the respondent +origin refuses those paths before routing and never sets an account cookie. API responses do not +grant CORS to the product host. The fallback link opens the public `/f/` entry on the owner +origin with no fragment. Printable disclosures are available from that standalone form. + +The iframe and loader exchange only version 1 `ready`, `context`, `size` and `close` messages, +checking both origin and source window. Forms accepts context only from values declared in the +published definition, fixes the first accepted set when Start is pressed and stores it with the +response. For hosts implementing the messages themselves, echo the ready message's `nonce` in +the context reply and reuse the same public values when returning from a disclosure. The loader +keeps those values at mount. The private return link is shown inside Forms and opens on the +owner origin. Forms does not dispatch feedback to a product in this release. + +Before enabling embedding for a demo, register both hostnames on its Turnstile widget. Siteverify +must return the respondent hostname for a Start on the respondent origin. An ordinary demo +Start still expects `TURNSTILE_HOSTNAME`. + ## Rate limits at Cloudflare's edge Two addresses of the app can be called by anyone, with no secret: starting a response diff --git a/embed/loader.mjs b/embed/loader.mjs new file mode 100644 index 0000000..8a228a0 --- /dev/null +++ b/embed/loader.mjs @@ -0,0 +1,109 @@ +/** Copy this small module into a host build or serve a pinned release from the host. */ +export function mountFormsFeedback({ + target, + respondentOrigin, + publicOrigin, + form, + context = {}, + entryLabel, + closeLabel, + directLabel, +}) { + const origin = new URL(respondentOrigin); + const publicForms = new URL(publicOrigin); + if ( + origin.origin !== respondentOrigin || + publicForms.origin !== publicOrigin || + !["http:", "https:"].includes(origin.protocol) || + !["http:", "https:"].includes(publicForms.protocol) || + publicOrigin === respondentOrigin || + origin.origin === location.origin || + !/^[a-z0-9][a-z0-9_-]{0,63}$/.test(form) + ) + throw new Error("Invalid Forms embed configuration"); + const publicLink = `${publicOrigin}/f/${form}`; + const contextSnapshot = Object.freeze({ ...context }); + const entry = document.createElement("button"); + entry.type = "button"; + entry.textContent = entryLabel; + entry.style.minHeight = "44px"; + const direct = document.createElement("a"); + direct.href = publicLink; + direct.textContent = directLabel; + direct.style.display = "inline-flex"; + direct.style.minHeight = "44px"; + direct.style.alignItems = "center"; + const panel = document.createElement("div"); + panel.style.maxWidth = "640px"; + panel.style.width = "100%"; + panel.hidden = true; + let frame; + let lastNonce; + function receive(event) { + if ( + !frame || + event.source !== frame.contentWindow || + event.origin !== origin.origin || + event.data?.version !== 1 + ) + return; + if (event.data.type === "ready") { + const { nonce } = event.data; + if ( + typeof nonce !== "string" || + !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(nonce) || + nonce === lastNonce + ) + return; + lastNonce = nonce; + frame.contentWindow.postMessage( + { version: 1, type: "context", nonce, context: contextSnapshot }, + origin.origin, + ); + } else if ( + event.data.type === "size" && + Number.isInteger(event.data.height) && + event.data.height >= 0 && + event.data.height <= 2400 + ) { + frame.style.height = `${Math.max(320, event.data.height)}px`; + } else if (event.data.type === "close") { + close(); + } + } + function close() { + frame?.remove(); + frame = undefined; + panel.hidden = true; + entry.textContent = entryLabel; + lastNonce = undefined; + } + entry.addEventListener("click", () => { + if (frame) { + close(); + return; + } + frame = document.createElement("iframe"); + frame.title = entryLabel; + frame.src = `${origin.origin}/embed/${form}`; + frame.setAttribute("sandbox", "allow-scripts allow-same-origin allow-forms"); + frame.style.width = "100%"; + frame.style.height = "640px"; + frame.style.border = "0"; + panel.append(frame); + panel.hidden = false; + entry.textContent = closeLabel; + }); + window.addEventListener("message", receive); + target.append(entry, direct, panel); + return { + close, + destroy() { + close(); + window.removeEventListener("message", receive); + entry.remove(); + direct.remove(); + panel.remove(); + }, + }; +} diff --git a/examples/home-baking.json b/examples/home-baking.json index c0898a5..0bbad6b 100644 --- a/examples/home-baking.json +++ b/examples/home-baking.json @@ -6,6 +6,15 @@ "name": "Made-up Bread Study, Example Institute", "contact": "bread-study@example.org" }, + "embed": { + "origin": "http://localhost:4771", + "context": { + "product": ["bread-lab"], + "publicVersion": ["v1"], + "publicRoute": ["/recipes", "/plans"], + "planCategory": ["free", "pro"] + } + }, "consent": { "title": "Before you start", "text": [ diff --git a/packages/schema/src/definition.ts b/packages/schema/src/definition.ts index 7da43b4..729fcb6 100644 --- a/packages/schema/src/definition.ts +++ b/packages/schema/src/definition.ts @@ -199,6 +199,50 @@ export const controllerSchema = z.strictObject({ */ export const withdrawalSchema = z.enum(["until-closed", "until-complete"]); +/** Exact public values a product may offer to an embedded respondent. */ +const embedValues = z + .array( + z + .string() + .min(1) + .max(64) + .regex(/^[a-zA-Z0-9_/-]+$/), + ) + .max(32); +export const embedSchema = z.strictObject({ + origin: z + .string() + .max(255) + .regex(/^(?:https:\/\/[a-z0-9.-]+|http:\/\/(?:localhost|127\.0\.0\.1))(?::[0-9]{1,5})?$/), + context: z.strictObject({ + product: embedValues.optional(), + publicVersion: embedValues.optional(), + publicRoute: embedValues.optional(), + planCategory: embedValues.optional(), + }), +}); + +export const embedContextSchema = z.strictObject({ + product: z.string().min(1).max(64).optional(), + publicVersion: z.string().min(1).max(64).optional(), + publicRoute: z.string().min(1).max(64).optional(), + planCategory: z.string().min(1).max(64).optional(), +}); + +export type EmbedContext = z.infer; + +export function acceptedEmbedContext( + definition: Pick, + value: unknown, +): EmbedContext | undefined { + const parsed = embedContextSchema.safeParse(value); + if (!parsed.success || !definition.embed) return undefined; + for (const [key, given] of Object.entries(parsed.data)) { + if (!definition.embed.context[key as keyof EmbedContext]?.includes(given)) return undefined; + } + return parsed.data; +} + /** What a definition that does not say gets: the rule that leaves the person more. */ export const DEFAULT_WITHDRAWAL = "until-closed" satisfies z.infer; @@ -226,6 +270,8 @@ export const definitionSchema = z.strictObject({ withdrawal: withdrawalSchema.optional(), /** Shown before any question, when the form has one. Nothing is stored until it is given. */ consent: consentSchema.optional(), + /** The one host origin and public context values allowed for this published definition. */ + embed: embedSchema.optional(), sections: z.array(sectionSchema).min(1), end: endSchema.optional(), }); diff --git a/packages/schema/src/index.ts b/packages/schema/src/index.ts index 3b247c6..1808de5 100644 --- a/packages/schema/src/index.ts +++ b/packages/schema/src/index.ts @@ -13,6 +13,7 @@ export { withAnswer, } from "./answers"; export { + acceptedEmbedContext, type Block, type Consent, type Controller, @@ -22,6 +23,8 @@ export { type Definition, type DefinitionInput, definitionSchema, + type EmbedContext, + embedContextSchema, type Group, type Item, idSchema, diff --git a/wrangler.jsonc b/wrangler.jsonc index e273a7e..ccd37f8 100644 --- a/wrangler.jsonc +++ b/wrangler.jsonc @@ -42,7 +42,8 @@ } ], // Signs the sessions of the people who run forms. A deploy without it is refused. - // Optional settings: BETTER_AUTH_URL, SIGN_UP_ALLOW, FORMS_EXAMPLES, FORMS_PRIVATE_ENTRY + // Optional settings: BETTER_AUTH_URL, FORMS_RESPONDENT_ORIGIN, SIGN_UP_ALLOW, + // FORMS_EXAMPLES, FORMS_PRIVATE_ENTRY // (see apps/web/src/server/env.d.ts). "secrets": { "required": ["BETTER_AUTH_SECRET"] }, // Responses: one row per response, one per answer, and the answers a form keeps apart.