Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .dev.vars.example
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
374 changes: 374 additions & 0 deletions apps/web/e2e/embed.spec.ts
Original file line number Diff line number Diff line change
@@ -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: "<!doctype html><title>Synthetic host</title><main><h1>Product content</h1></main>",
}),
);
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: "<!doctype html><main>Host content</main>" }),
);
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: "<!doctype html><title>Other device</title>",
}),
);
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: `<iframe src="${hostPage}"></iframe>`,
}),
);
await page.route(hostPage, (route) =>
route.fulfill({
contentType: "text/html",
body: `<iframe src="${respondent}/f/home-baking"></iframe>`,
}),
);
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: `<script>addEventListener("message", (event) => {
if (event.origin === "${respondent}" && event.data?.type === "ready")
window.formNonce = event.data.nonce;
})</script><iframe sandbox="allow-scripts allow-same-origin allow-forms" src="${respondent}/f/home-baking"></iframe>`,
}),
);
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<string, string>) =>
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: '<script>parent.postMessage({ version: 1, type: "ready", nonce: "00000000-0000-4000-8000-000000000000" }, "*")</script>',
}),
);
await page.route(hostPage, (route) =>
route.fulfill({ contentType: "text/html", body: "<!doctype html><main>Host content</main>" }),
);
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: `<iframe src="${respondent}/f/home-baking/unknown"></iframe>`,
}),
);
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: `<iframe src="${respondent}/f/home-baking"></iframe>`,
}),
);
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();
},
);
Loading
Loading