SPB Git

Repository Public

app.spec.ts 16.0 KB 272 lines typescript

1import { expect, test, type Browser, type BrowserContext, type Page } from "@playwright/test"2import crypto from "node:crypto"3import fs from "node:fs"4import postgres from "postgres"56const SHOTS = process.env.SPM_SHOTS ?? "/tmp/spm-shots"7fs.mkdirSync(SHOTS, { recursive: true })8const sql = postgres(process.env.SPM_TEST_DB ?? "postgres://127.0.0.1/sp_message_test", { onnotice: () => {} })910/** A browser profile with its own platform authenticator (passkeys with user verification). */11async function profile(browser: Browser, opts: Parameters<Browser["newContext"]>[0] = {}): Promise<{ ctx: BrowserContext; page: Page; authId: string; cdp: any }> {12  const ctx = await browser.newContext({ permissions: ["camera", "microphone"], ...opts })13  const page = await ctx.newPage()14  const cdp = await ctx.newCDPSession(page)15  await cdp.send("WebAuthn.enable")16  const { authenticatorId } = await cdp.send("WebAuthn.addVirtualAuthenticator", {17    options: { protocol: "ctap2", transport: "internal", hasResidentKey: true, hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true },18  })19  page.on("pageerror", (e) => console.log("PAGE ERROR:", e.message))20  page.on("console", (m) => (m.type() === "warning" || m.type() === "error") && console.log(`[browser ${m.type()}]`, m.text().slice(0, 300)))21  return { ctx, page, authId: authenticatorId, cdp }22}2324async function onboard(page: Page, url: string, name: string) {25  await page.goto(url)26  await page.getByRole("button", { name: "Continue" }).click()27  await page.getByLabel("Name shown to your contacts").fill(name)28  await page.getByRole("button", { name: "Create my passkey" }).click()29  const key = await page.getByTestId("recovery-key").innerText()30  expect(key).toMatch(/^([A-Z2-9]{4}-){7}[A-Z2-9]{4}$/)31  await page.getByRole("checkbox").check()32  await page.getByRole("button", { name: "Open SP Message" }).click()33  await expect(page.getByRole("heading", { name: "Chats" })).toBeVisible()34  return key35}3637let alice: Awaited<ReturnType<typeof profile>>, bob: Awaited<ReturnType<typeof profile>>38let aliceRecovery = ""3940test.describe.configure({ mode: "serial" })41test.afterAll(async () => {42  await sql.end()43})4445test("sign-in page, and an invalid invitation link", async ({ browser }) => {46  alice = await profile(browser, { viewport: { width: 1360, height: 860 }, colorScheme: "dark" })47  await alice.page.goto("/")48  await expect(alice.page.getByRole("button", { name: "Sign in with a passkey" })).toBeVisible()49  await alice.page.screenshot({ path: `${SHOTS}/01-signin-dark.png` })50  await alice.page.goto(`/invite#${"z".repeat(43)}`)51  await expect(alice.page.getByRole("heading", { name: "This link is no longer valid" })).toBeVisible()52})5354test("administrator bootstrap with a passkey and client-side key generation", async () => {55  const token = crypto.randomBytes(32).toString("base64url")56  await sql`insert into bootstrap_tokens (token_hash, expires_at) values (${crypto.createHash("sha256").update(token).digest()}, now() + interval '10 minutes')`57  await alice.page.goto(`/bootstrap#${token}`)58  await expect(alice.page.getByRole("heading", { name: "Set up the administrator" })).toBeVisible()59  await alice.page.screenshot({ path: `${SHOTS}/02-bootstrap.png` })60  aliceRecovery = await onboard(alice.page, `/bootstrap#${token}`, "Alice Martin")61  const [u] = await sql`select role, identity_key from users where handle = 'alice.martin'`62  expect(u.role).toBe("admin")63  expect(Buffer.from(u.identity_key).length).toBe(32)64  // the same link cannot create a second administrator65  const other = await alice.ctx.browser()!.newContext()66  const p = await other.newPage()67  await p.goto(`/bootstrap#${token}`)68  await expect(p.getByRole("heading", { name: "This link is no longer valid" })).toBeVisible()69  await other.close()70})7172test("invitation dashboard, onboarding of an invited person, first encrypted conversation", async ({ browser }) => {73  const a = alice.page74  await a.getByRole("button", { name: "Admin" }).first().click()75  await a.getByRole("tab", { name: /Invitations/ }).click()76  await a.getByRole("button", { name: "New invitation" }).click()77  await a.getByLabel("Intended for (optional note)").fill("Bob")78  await a.getByRole("button", { name: "Create the link" }).click()79  const link = await a.getByTestId("invite-link").innerText()80  expect(link).toMatch(/\/invite#[\w-]{43}$/)81  await a.screenshot({ path: `${SHOTS}/03-admin-invitation.png` })82  await a.keyboard.press("Escape")8384  bob = await profile(browser, { viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true, colorScheme: "light", deviceScaleFactor: 2 })85  await bob.page.goto(link)86  await expect(bob.page.getByText("invites you to")).toBeVisible()87  await bob.page.screenshot({ path: `${SHOTS}/04-invite-mobile-light.png` })88  await onboard(bob.page, link, "Bob Tremblay")89  // the welcome conversation with the inviter is created automatically90  await expect(bob.page.getByRole("button", { name: /Alice Martin/ }).first()).toBeVisible({ timeout: 20_000 })91  // on a phone the new conversation opens by itself; open it from the list otherwise92  const box = bob.page.getByLabel("Message", { exact: true })93  await box.waitFor({ state: "visible", timeout: 4000 }).catch(() => bob.page.getByRole("button", { name: /Alice Martin/ }).first().click({ timeout: 5000 }).catch(() => {}))94  await expect(box).toBeVisible()95  await bob.page.getByLabel("Message", { exact: true }).fill("Bonjour Alice, ici Bob 🔐")96  await bob.page.getByRole("button", { name: "Send", exact: true }).click()97  await expect(bob.page.locator(".msg.me")).toContainText("Bonjour Alice")9899  await a.getByRole("button", { name: "Chats" }).first().click()100  await a.getByRole("button", { name: /Bob Tremblay/ }).first().click()101  await expect(a.locator(".msg")).toContainText("Bonjour Alice, ici Bob", { timeout: 20_000 })102  await a.getByLabel("Message", { exact: true }).fill("Bienvenue Bob. Tout est chiffré de bout en bout.")103  await a.keyboard.press("Enter")104  await expect(bob.page.locator(".msg").last()).toContainText("Bienvenue Bob", { timeout: 20_000 })105106  // the invitation is used up107  const again = await browser.newContext()108  const p = await again.newPage()109  await p.goto(link)110  await expect(p.getByRole("heading", { name: "This link is no longer valid" })).toBeVisible()111  await again.close()112  // what the server stored is ciphertext113  for (const r of await sql`select data from messages`) expect(Buffer.from(r.data).includes("Bonjour Alice")).toBe(false)114})115116test("reply, reaction, edit, typing indicator, delivery and read state", async () => {117  const a = alice.page, b = bob.page118  await a.locator(".msg:not(.me)").first().click({ button: "right" })119  await a.getByRole("menuitem", { name: "Reply" }).click()120  await a.getByLabel("Message", { exact: true }).fill("Réponse citée")121  await expect(b.locator(".typing")).toContainText("is typing", { timeout: 10_000 })122  await a.keyboard.press("Enter")123  await expect(b.locator(".reply-ref").last()).toContainText("Bonjour Alice")124  await a.locator(".msg:not(.me)").first().click({ button: "right" })125  await a.getByRole("button", { name: "❤️" }).click()126  await expect(b.locator(".react")).toContainText("❤️", { timeout: 10_000 })127  // edit the last message with the keyboard shortcut128  await a.getByLabel("Message", { exact: true }).press("ArrowUp")129  await a.getByLabel("Message", { exact: true }).fill("Réponse citée (corrigée)")130  await a.keyboard.press("Enter")131  await expect(b.locator(".msg").last()).toContainText("Réponse citée (corrigée)", { timeout: 10_000 })132  await expect(b.locator(".msg").last()).toContainText("edited")133  // bob has the conversation open: alice sees the read state134  await expect(a.locator(".msg.me").last().locator('[title="Read"]')).toBeVisible({ timeout: 15_000 })135  await a.screenshot({ path: `${SHOTS}/05-conversation-desktop-dark.png` })136  await b.screenshot({ path: `${SHOTS}/06-conversation-mobile-light.png` })137})138139test("encrypted attachment: image upload, preview, download", async () => {140  const a = alice.page, b = bob.page141  const dataUrl = await a.evaluate(() => {142    const c = document.createElement("canvas")143    c.width = 640144    c.height = 420145    const g = c.getContext("2d")!146    const grad = g.createLinearGradient(0, 0, 640, 420)147    grad.addColorStop(0, "#ffb347")148    grad.addColorStop(1, "#e83e8c")149    g.fillStyle = grad150    g.fillRect(0, 0, 640, 420)151    return c.toDataURL("image/png")152  })153  const png = Buffer.from(dataUrl.split(",")[1], "base64")154  await a.locator('input[type=file]').first().setInputFiles({ name: "photo.png", mimeType: "image/png", buffer: png })155  await expect(a.locator(".tray .item")).toHaveCount(1)156  await a.getByRole("button", { name: "Send", exact: true }).click()157  await expect(b.locator(".att-img img").last()).toBeVisible({ timeout: 20_000 })158  await expect.poll(async () => b.locator(".att-img img:not(.blur)").count(), { timeout: 20_000 }).toBeGreaterThan(0)159  const files = await sql`select id, size from files where completed_at is not null`160  expect(files.length).toBe(1)161  // the stored object does not start with a PNG signature: it is ciphertext162  const res = await a.request.get(`/api/files/${files[0].id}/chunks/0`)163  expect(res.status()).toBe(200)164  expect((await res.body()).subarray(0, 4).toString("hex")).not.toBe("89504e47")165  // a text file, downloaded and compared166  await a.locator('input[type=file]').first().setInputFiles({ name: "notes.txt", mimeType: "text/plain", buffer: Buffer.from("contenu confidentiel") })167  await a.getByRole("button", { name: "Send", exact: true }).click()168  await expect(b.locator(".file").last()).toContainText("notes.txt", { timeout: 20_000 })169  const dl = b.waitForEvent("download")170  await b.locator(".file").last().click()171  const file = await (await dl).path()172  expect(fs.readFileSync(file, "utf8")).toBe("contenu confidentiel")173})174175test("contact verification shows the same safety number on both sides", async () => {176  const a = alice.page, b = bob.page177  await a.getByRole("button", { name: "Details", exact: true }).click()178  await a.locator(".side .btn.sm").first().click()179  const na = await a.getByTestId("safety-number").innerText()180  await a.screenshot({ path: `${SHOTS}/07-verify-desktop.png` })181  await a.getByRole("button", { name: "Mark as verified" }).click()182  await a.keyboard.press("Escape")183  await expect(a.locator(".side .badge.ok")).toContainText("Verified")184  await a.screenshot({ path: `${SHOTS}/08-details-desktop.png` })185  await b.getByRole("button", { name: "Details", exact: true }).click()186  await b.locator(".side .btn.sm").first().click()187  const nb = await b.getByTestId("safety-number").innerText()188  expect(na.replace(/\s+/g, "")).toBe(nb.replace(/\s+/g, ""))189  expect(na.replace(/\s+/g, "")).toMatch(/^\d{60}$/)190  await b.screenshot({ path: `${SHOTS}/09-verify-mobile.png` })191  await b.keyboard.press("Escape")192  await b.getByRole("button", { name: "Close" }).click()193})194195test("audio/video call between two browsers with authenticated signalling", async () => {196  const a = alice.page, b = bob.page197  await a.getByRole("button", { name: "Video call" }).click()198  await expect(a.locator(".call")).toBeVisible({ timeout: 10_000 })199  await expect(b.getByText("incoming video call")).toBeVisible({ timeout: 20_000 })200  await b.screenshot({ path: `${SHOTS}/10-incoming-call-mobile.png` })201  await b.getByRole("button", { name: "Answer" }).click()202  for (const p of [a, b]) {203    await expect(p.locator(".tile .label")).toBeVisible({ timeout: 30_000 })204    await expect(p.locator(".tile .label")).not.toContainText("connecting", { timeout: 30_000 })205    // real media is flowing: the remote video element has decoded frames206    await expect.poll(() => p.evaluate(() => (document.querySelector(".tile video") as HTMLVideoElement)?.videoWidth ?? 0), { timeout: 30_000 }).toBeGreaterThan(0)207  }208  await a.screenshot({ path: `${SHOTS}/11-call-desktop.png` })209  await a.getByRole("button", { name: "Mute" }).click()210  await expect(a.getByRole("button", { name: "Unmute" })).toBeVisible()211  await a.getByRole("button", { name: "Hang up" }).click()212  await expect(b.locator(".call")).toHaveCount(0, { timeout: 15_000 })213  await expect(a.locator(".sysmsg").last()).toContainText("Video call")214})215216test("second device: approval with matching codes, then messages arrive on both", async ({ browser }) => {217  // Same passkey (as iCloud Keychain would sync it): copy the credential to a new browser profile.218  const { credentials } = await alice.cdp.send("WebAuthn.getCredentials", { authenticatorId: alice.authId })219  const second = await profile(browser, { viewport: { width: 1100, height: 800 }, colorScheme: "light" })220  for (const credential of credentials) await second.cdp.send("WebAuthn.addCredential", { authenticatorId: second.authId, credential })221  await second.page.goto("/")222  await second.page.getByRole("button", { name: "Sign in with a passkey" }).click()223  await second.page.getByRole("button", { name: "Approve from another device" }).click()224  await expect(second.page.getByTestId("link-code")).toHaveText(/\d{3} \d{3}/, { timeout: 15_000 })225  const code = (await second.page.getByTestId("link-code").innerText()).replace(/\s/g, "")226  expect(code).toMatch(/^\d{6}$/)227  await expect(alice.page.getByTestId("approve-code")).toBeVisible({ timeout: 15_000 })228  expect((await alice.page.getByTestId("approve-code").innerText()).replace(/\s/g, "")).toBe(code)229  await alice.page.screenshot({ path: `${SHOTS}/12-device-approval.png` })230  await alice.page.getByRole("button", { name: /approve/i }).click()231  await expect(second.page.getByRole("heading", { name: "Chats" })).toBeVisible({ timeout: 20_000 })232  await second.page.getByRole("button", { name: /Bob Tremblay/ }).first().click()233  await expect(second.page.getByLabel("Message", { exact: true })).toBeEnabled({ timeout: 30_000 })234  await bob.page.getByLabel("Message", { exact: true }).fill("Message pour les deux appareils")235  await bob.page.getByRole("button", { name: "Send", exact: true }).click()236  await expect(second.page.locator(".msg").last()).toContainText("Message pour les deux appareils", { timeout: 20_000 })237  await expect(alice.page.locator(".msg").last()).toContainText("Message pour les deux appareils", { timeout: 20_000 })238  await second.page.screenshot({ path: `${SHOTS}/13-second-device-light.png` })239  await second.ctx.close()240})241242test("settings, admin people view, mobile navigation, sign-out and sign-in again", async () => {243  const a = alice.page, b = bob.page244  await a.getByRole("button", { name: "Settings" }).first().click()245  await a.getByRole("button", { name: /Security/ }).click()246  await expect(a.getByText("Your identity key fingerprint")).toBeVisible()247  await a.screenshot({ path: `${SHOTS}/14-settings-security.png` })248  await a.getByRole("button", { name: /Devices and sessions/ }).click()249  await expect(a.locator(".page .badge", { hasText: "this device" })).toBeVisible()250  await a.getByRole("button", { name: "Admin" }).first().click()251  await a.getByRole("tab", { name: /People/ }).click()252  await expect(a.locator(".table")).toContainText("Bob Tremblay")253  await a.screenshot({ path: `${SHOTS}/15-admin-people.png` })254  // mobile: back to the list, tabs255  await b.getByRole("button", { name: "Back" }).first().click()256  await expect(b.locator(".tabbar")).toBeVisible()257  await b.screenshot({ path: `${SHOTS}/16-list-mobile-light.png` })258  await b.locator(".tabbar").getByRole("button", { name: "Calls" }).click()259  await expect(b.locator(".pane")).toContainText("Video call")260  await b.locator(".tabbar").getByRole("button", { name: "Settings" }).click()261  await b.getByRole("button", { name: "Sign out", exact: true }).click()262  await expect(b.getByRole("button", { name: "Sign in with a passkey" })).toBeVisible()263  // API is closed after sign-out264  expect((await b.request.get("/api/sync")).status()).toBe(401)265  await b.getByRole("button", { name: "Sign in with a passkey" }).click()266  await expect(b.getByRole("heading", { name: "Chats" })).toBeVisible({ timeout: 20_000 })267  // history is still there: it lives on this device268  await b.getByRole("button", { name: /Alice Martin/ }).first().click()269  await expect(b.locator(".msgs")).toContainText("Bonjour Alice, ici Bob")270  void aliceRecovery271})272
Files main
Menu

Theme