Cotton code
43 lines · 2.6 KB · TypeScriptRaw
/** * A new device asks to sign in, and the person's other devices that take pushes are told (GETTING-IN.md): APNs with * the words, FCM a data message the app draws in the core's words. Every number, device and token is invented. */import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { askCommit } from "../src/approval.ts";import { approvalTitle } from "../src/chat/push.ts";import { fakes, open, type Fakes } from "./calling.ts";import { chatPhone } from "./chat.ts";let world: Fakes;beforeEach(() => {  world = fakes();});afterEach(() => vi.restoreAllMocks());const b64u = (bytes: Uint8Array): string => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");const random32 = (): string => b64u(crypto.getRandomValues(new Uint8Array(32)));describe("a new device's ask is pushed to the person's other devices", () => {  it("says Your Mac on an iPhone and sends a data message to an Android phone", async () => {    const number = "+919000007001";    await chatPhone(number, "phone-ios", { platform: "ios", token: "a0b1c2d3e4f5a0b1c2d3e4f5a0b1c2d3e4f5a0b1c2d3e4f5a0b1c2d3e4f5a0b1" });    await chatPhone(number, "phone-android", { platform: "android", token: "fcm:synthetic-android-token-for-approval" });    const device = random32();    const vault = random32();    const asked = await open("POST", "/v1/approval/ask", { phone: number, device_id: device, device_name: "mac-c", device_kind: "mac", vault_key: vault, commit: await askCommit(device, vault, random32()) }, { "cf-connecting-ip": "203.0.113.201" });    expect(asked.status, JSON.stringify(asked.body)).toBe(200);    await vi.waitFor(() => {      if (world.pushes.filter((p) => (p.token.endsWith("-for-approval") || p.token.startsWith("a0b1c2"))).length < 2) throw new Error("waiting for both pushes");    }, { timeout: 3000, interval: 20 });    const ios = world.pushes.find((p) => p.token === "a0b1c2d3e4f5a0b1c2d3e4f5a0b1c2d3e4f5a0b1c2d3e4f5a0b1c2d3e4f5a0b1")!;    expect(ios.body).toMatchObject({ aps: { alert: { title: "Your Mac wants to sign in to your Cotton", body: "mac-c asked just now. If you're holding it yourself, open this to approve." } }, approval: 1 });    const android = world.pushes.find((p) => p.token === "fcm:synthetic-android-token-for-approval")!;    expect(android.body).toEqual({ kind: "approval", title: "Your Mac wants to sign in to your Cotton" });  });  it("names an unknown device plainly", () => {    expect(approvalTitle(null)).toBe("A new device wants to sign in to your Cotton");    expect(approvalTitle("android")).toBe("Your Android phone wants to sign in to your Cotton");  });});