diff --git a/fe/.env.example b/fe/.env.example index 0e44fc4..7ec6fee 100644 --- a/fe/.env.example +++ b/fe/.env.example @@ -15,12 +15,16 @@ NEXT_PUBLIC_USDC_ASSET= # The backend API from #16. Its /config must report the same addresses as above. NEXT_PUBLIC_API_URL= -# The proof relay from #17. While empty, proving revenue runs on a mock (src/lib/reclaim/mock.ts) whose -# proofs the real contract refuses. Only the e2e RPC stub accepts them. +# The proof relay from #17 (the same server as the API; see docs/api.md). While empty, proving revenue runs +# on a mock (src/lib/reclaim/mock.ts) whose proofs the real contract refuses. Only the e2e RPC stub accepts them. NEXT_PUBLIC_RELAY_URL= +# Google OAuth client id (type "Web application") for the AdSense sign-in popup. Its authorized JavaScript +# origins must list this front end's origins. Public by design; the client secret is never used here. +NEXT_PUBLIC_GOOGLE_CLIENT_ID= # WalletConnect, for mobile wallets. From the Reown dashboard. NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID= -# Set to 1 only for Playwright runs: swaps the real wallet for a test wallet. +# Set to 1 only for Playwright runs: swaps the real wallet for a test wallet, and shortens the +# Reclaim mock's delays and the wait between polls of a relay job. NEXT_PUBLIC_E2E= diff --git a/fe/ARCHITECTURE.md b/fe/ARCHITECTURE.md index bf796db..af5957e 100644 --- a/fe/ARCHITECTURE.md +++ b/fe/ARCHITECTURE.md @@ -113,8 +113,8 @@ Deliberately left out: - **Animation libraries.** CSS transitions cover what the design needs (§7). - **vaul.** Mobile sheets start as a Base UI dialog styled as a sheet. Add vaul only if swipe to dismiss turns out to matter, after checking it is still maintained. -- **A Reclaim browser SDK, for now.** Which one depends on how the #17 relay is built. Ask - @Lin1er before installing anything. +- **A Reclaim browser SDK.** The #17 relay makes the proof with zkFetch; the browser only signs in + with Google Identity Services, loaded as Google's script, not a package (`lib/reclaim/relay.ts`). ## 4. State diff --git a/fe/README.md b/fe/README.md index 7f222f9..ae59758 100644 --- a/fe/README.md +++ b/fe/README.md @@ -42,11 +42,15 @@ pnpm test:e2e # Playwright, tests/e2e It uses Playwright's own Chromium. Google Chrome works too (`PW_CHANNEL=chrome`), but on a Mac with a Chrome update pending, Chrome's updater can keep a finished run from exiting. It starts its own `next dev` on port 3219 (or `PW_PORT`), built into `.next-e2e` (`NEXT_DIST_DIR`), so it runs -alongside your own `next dev`. Any other `NEXT_DIST_DIR` makes Next add its type folder to -`tsconfig.json`; do not commit that. It sets its own environment (`playwright.config.ts`): the test -wallet (`NEXT_PUBLIC_E2E=1`), a fake RPC URL and a fake #16 API URL whose answers each spec decides -(`tests/e2e/rpc.ts`, `tests/e2e/api.ts`), so a run never touches testnet or a real API and needs no -browser extension. +alongside your own `next dev`. A second one, on the port after it and built into `.next-e2e-relay`, +has the relay and the Google client id set, for `tests/e2e/relay.spec.ts`: there Google's sign-in is +a stub and the spec answers the relay. Every run starts both, which takes longer and needs both +ports free; `PW_RELAY=0` leaves the relay build and its specs out. Both folders' types are in +`tsconfig.json`; any other `NEXT_DIST_DIR` makes Next add its own, so do not commit that. + +It sets its own environment (`playwright.config.ts`): the test wallet (`NEXT_PUBLIC_E2E=1`), a fake +RPC URL and a fake #16 API URL whose answers each spec decides (`tests/e2e/rpc.ts`, +`tests/e2e/api.ts`), so a run never touches testnet or a real API and needs no browser extension. ## Environment @@ -60,10 +64,15 @@ browser. Never put a secret in one. - **`NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID`** is only needed for mobile wallets. Without it, desktop browser wallets still work. -## Proving revenue is mocked until #17 +## Proving revenue: the relay, or a mock + +With `NEXT_PUBLIC_RELAY_URL` and `NEXT_PUBLIC_GOOGLE_CLIENT_ID` set, the creator signs in with Google's +own popup (`adsense.readonly` only) and the #17 relay makes the proof, which takes about a minute, more +behind a queue (`src/lib/reclaim/relay.ts`, `docs/api.md`). No Reclaim SDK runs in the browser. The job +id is kept in `sessionStorage`, so leaving /advance or reloading while it proves comes back to the same +job without a second sign-in. -The Reclaim session and the proof relay (#17) do not exist yet, so `src/lib/reclaim/` answers from a -mock while `NEXT_PUBLIC_RELAY_URL` is empty. It walks through the session (window open, reading) and +`src/lib/reclaim/` answers from a mock while `NEXT_PUBLIC_RELAY_URL` is empty. It walks through the session (window open, reading) and returns fixed values. Everything after it, the offer from `quote`, the proof check, `request_advance` and the receipt, is the real contract client. On testnet the contract refuses the mock's proof, so the whole flow only completes in the e2e run, against the stubbed RPC. diff --git a/fe/playwright.config.ts b/fe/playwright.config.ts index 3692093..98863b3 100644 --- a/fe/playwright.config.ts +++ b/fe/playwright.config.ts @@ -3,35 +3,68 @@ import { defineConfig, devices } from "@playwright/test"; // End to end runs with the test wallet (NEXT_PUBLIC_E2E=1) and with every Stellar RPC call and #16 API // call answered by the spec itself (tests/e2e/rpc.ts, tests/e2e/api.ts), so a run never touches testnet // or a real API and never needs a browser extension. -// PW_PORT lets two worktrees run their e2e suites side by side. +// PW_PORT (and the port after it, for the relay build) lets two worktrees run their e2e suites side by side. const PORT = Number(process.env.PW_PORT ?? 3219); +const RELAY_PORT = PORT + 1; +// PW_RELAY=0 leaves out the relay build and its specs, for a quicker run of the others. +const RELAY = process.env.PW_RELAY !== "0"; +const RELAY_SPEC = /relay\.spec\.ts$/; -export default defineConfig({ - testDir: "tests/e2e", - fullyParallel: true, - // Playwright's own Chromium (`npx playwright install chromium`, once). Google Chrome can hold a run - // open after it ends while an update is pending; PW_CHANNEL=chrome still uses it when wanted. - use: { baseURL: `http://localhost:${PORT}`, channel: process.env.PW_CHANNEL, trace: "retain-on-failure" }, - projects: [ - { name: "desktop", use: { ...devices["Desktop Chrome"], viewport: { width: 1440, height: 960 } } }, - { name: "mobile", use: { ...devices["Pixel 7"], viewport: { width: 390, height: 844 } } }, - ], - webServer: { - command: `npx next dev --port ${PORT}`, - port: PORT, +/** One dev server. `proving` sets the Reclaim seam: the mock (no relay) or the relay. */ +function server(port: number, distDir: string, proving: Record) { + return { + command: `npx next dev --port ${port}`, + port, // Never reuse whatever already listens on the port: it may be another app entirely. reuseExistingServer: false, timeout: 180_000, env: { - NEXT_DIST_DIR: ".next-e2e", + NEXT_DIST_DIR: distDir, NEXT_PUBLIC_E2E: "1", - // The Reclaim mock, whatever .env.local says. - NEXT_PUBLIC_RELAY_URL: "", + // The Reclaim mock or the stubbed relay, whatever .env.local says. + NEXT_PUBLIC_GOOGLE_CLIENT_ID: "", + ...proving, NEXT_PUBLIC_STELLAR_RPC_URL: "https://rpc.e2e.invalid", NEXT_PUBLIC_API_URL: "https://api.e2e.invalid", // Advance contract (dev), from docs/deployments.md. The stub answers for it; nothing is sent. NEXT_PUBLIC_ADVANCE_CONTRACT_ID: "CA3YGQHU42EL2TAOG7NJ5DDT5FLKKQNDWIUFFU6KV7QJHCFGLAGYXLID", NEXT_PUBLIC_USDC_ASSET: "USDC:GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5", }, - }, + }; +} + +/** + * The real proving seam (#17), on a second build whose relay and Google client are set. The relay + * and Google's sign-in are answered by the spec (tests/e2e/relay.spec.ts). + */ +function relayProjects() { + const use = { baseURL: `http://localhost:${RELAY_PORT}` }; + return [ + { name: "relay-desktop", testMatch: RELAY_SPEC, use: { ...devices["Desktop Chrome"], viewport: { width: 1440, height: 960 }, ...use } }, + { name: "relay-mobile", testMatch: RELAY_SPEC, use: { ...devices["Pixel 7"], viewport: { width: 390, height: 844 }, ...use } }, + ]; +} + +export default defineConfig({ + testDir: "tests/e2e", + fullyParallel: true, + // Playwright's own Chromium (`npx playwright install chromium`, once). Google Chrome can hold a run + // open after it ends while an update is pending; PW_CHANNEL=chrome still uses it when wanted. + use: { baseURL: `http://localhost:${PORT}`, channel: process.env.PW_CHANNEL, trace: "retain-on-failure" }, + projects: [ + { name: "desktop", testIgnore: RELAY_SPEC, use: { ...devices["Desktop Chrome"], viewport: { width: 1440, height: 960 } } }, + { name: "mobile", testIgnore: RELAY_SPEC, use: { ...devices["Pixel 7"], viewport: { width: 390, height: 844 } } }, + ...(RELAY ? relayProjects() : []), + ], + webServer: [ + server(PORT, ".next-e2e", { NEXT_PUBLIC_RELAY_URL: "" }), + ...(RELAY + ? [ + server(RELAY_PORT, ".next-e2e-relay", { + NEXT_PUBLIC_RELAY_URL: "https://relay.e2e.invalid", + NEXT_PUBLIC_GOOGLE_CLIENT_ID: "e2e.apps.googleusercontent.com", + }), + ] + : []), + ], }); diff --git a/fe/src/lib/errors.test.ts b/fe/src/lib/errors.test.ts index fc87891..fda9173 100644 --- a/fe/src/lib/errors.test.ts +++ b/fe/src/lib/errors.test.ts @@ -123,6 +123,15 @@ describe("proveFailureCopy", () => { "walletWrongNetwork", "walletNoAnswer", "relayNotReady", + "googleSignIn", + "noAdsense", + "relayFailed", + "relayBusy", + "proofRunning", + "proofGone", + "relayUnreachable", + "googleUnavailable", + "popupBlocked", ]; it("keeps every failure inside the copy rules, and never says Something went wrong", () => { @@ -134,6 +143,13 @@ describe("proveFailureCopy", () => { it("says nothing was charged only when that is true", () => { expect(proveFailureCopy("refused").body).toMatch(/Nothing was charged/); + // The relay's failures happen before anything reaches Stellar. + for (const k of ["googleSignIn", "noAdsense", "relayFailed", "proofRunning", "proofGone", "relayUnreachable"] as const) { + expect(proveFailureCopy(k).body).toMatch(/Nothing was charged/); + } + for (const k of ["relayBusy", "googleUnavailable", "popupBlocked"] as const) { + expect(proveFailureCopy(k).body).toMatch(/Nothing was read or charged/); + } expect(proveFailureCopy("charged").body).not.toMatch(/Nothing was charged/); expect(proveFailureCopy("unconfirmed").body).not.toMatch(/Nothing was charged/); }); diff --git a/fe/src/lib/errors.ts b/fe/src/lib/errors.ts index bbb9072..9656763 100644 --- a/fe/src/lib/errors.ts +++ b/fe/src/lib/errors.ts @@ -209,7 +209,16 @@ export function contractFailureCopy(code: number): FailureCopy { * - `simulationFailed`: Stellar answered, but could not run the request, with no contract code to say why. * - `notConfigured`: this build is missing an address it needs, so nothing reached the network. * - `walletLocked`, `walletWrongNetwork`, `walletNoAnswer`: the wallet could not sign, for that reason. - * - `relayNotReady`: proofs are meant to come from the #17 relay, and its client is not built yet. + * - `relayNotReady`: proofs are meant to come from the #17 relay, and this build cannot reach it. + * - `googleSignIn`: Google refused the sign-in the relay was handed, for example an expired one. + * - `noAdsense`: the Google account has no AdSense account, several, or one that is not approved (relay `account`). + * - `relayFailed`: the relay could not make the proof, on its side. Nothing was charged. + * - `relayBusy`: the relay is proving for others and its queue is full. + * - `proofRunning`: a proof for this wallet is already running, started from a tab that lost it. + * - `proofGone`: the relay no longer has the proof this tab was waiting on (it restarted, or an hour passed). + * - `relayUnreachable`: the relay did not answer. Not Stellar: nothing on chain was asked. + * - `googleUnavailable`: Google's sign-in did not load. + * - `popupBlocked`: the browser blocked Google's sign-in window. The creator closed nothing. */ export type ProveFailure = | "cancelled" @@ -225,13 +234,22 @@ export type ProveFailure = | "walletLocked" | "walletWrongNetwork" | "walletNoAnswer" - | "relayNotReady"; + | "relayNotReady" + | "googleSignIn" + | "noAdsense" + | "relayFailed" + | "relayBusy" + | "proofRunning" + | "proofGone" + | "relayUnreachable" + | "googleUnavailable" + | "popupBlocked"; export function proveFailureCopy(kind: ProveFailure, walletName = "Freighter"): FailureCopy { switch (kind) { case "cancelled": return { - title: "You closed the AdSense window", + title: "You closed the Google window", body: "Nothing was read or saved. Start again when you are ready.", }; case "declined": @@ -303,6 +321,51 @@ export function proveFailureCopy(kind: ProveFailure, walletName = "Freighter"): title: "Proving revenue is not open yet", body: "Forepay cannot read AdSense revenue yet. Try again later.", }; + case "googleSignIn": + return { + title: "Google did not let us read AdSense", + body: "Sign in again and allow Forepay to see your AdSense reports. Nothing was charged.", + }; + case "noAdsense": + return { + title: "We could not use your AdSense account", + body: "We could not find one approved AdSense account on this Google account. Sign in with the account that owns your AdSense, then try again. Nothing was charged.", + }; + case "relayFailed": + return { + title: "We could not finish your proof", + body: "Nothing was charged. Try again in a few minutes.", + }; + case "relayBusy": + return { + title: "Forepay is busy right now", + body: "Many creators are proving at once. Nothing was read or charged. Try again in a few minutes.", + }; + case "proofRunning": + return { + title: "Your proof is already being made", + body: "A proof for this wallet started earlier, in a tab that no longer has it. Wait a few minutes for it to end, then prove again. Nothing was charged.", + }; + case "proofGone": + return { + title: "Your earlier proof is gone", + body: "We no longer have the proof you started earlier. Prove your revenue again, it takes about a minute. Nothing was charged.", + }; + case "relayUnreachable": + return { + title: "We could not reach Forepay", + body: "Nothing was charged. Check your connection, then try again.", + }; + case "googleUnavailable": + return { + title: "Google sign-in did not load", + body: "Nothing was read or charged. Check your connection, then try again.", + }; + case "popupBlocked": + return { + title: "Your browser blocked the Google window", + body: "Allow pop-ups for Forepay, then try again. Nothing was read or charged.", + }; } } diff --git a/fe/src/lib/reclaim/index.test.ts b/fe/src/lib/reclaim/index.test.ts index 90d373b..b1ad6e0 100644 --- a/fe/src/lib/reclaim/index.test.ts +++ b/fe/src/lib/reclaim/index.test.ts @@ -15,8 +15,9 @@ describe("proveRevenue", () => { session.abandon(); }); - it("says the relay is not ready rather than pretending, once a relay URL is set", async () => { + it("says the relay is not ready rather than pretending, when the Google client id is missing", async () => { vi.stubEnv("NEXT_PUBLIC_RELAY_URL", "https://relay.example"); + vi.stubEnv("NEXT_PUBLIC_GOOGLE_CLIENT_ID", ""); const { proveRevenue, RelayNotReadyError } = await import("./index"); await expect(proveRevenue("GA6H", () => {}).result).rejects.toBeInstanceOf(RelayNotReadyError); }); diff --git a/fe/src/lib/reclaim/index.ts b/fe/src/lib/reclaim/index.ts index 7db4ef4..6b0e172 100644 --- a/fe/src/lib/reclaim/index.ts +++ b/fe/src/lib/reclaim/index.ts @@ -1,20 +1,42 @@ /** - * Proving AdSense revenue with Reclaim, and getting back the attested values `request_advance` takes + * Proving AdSense revenue, and getting back the attested values `request_advance` takes * (ARCHITECTURE.md §2, `lib/reclaim/`). The seam between the app and the #17 relay. * - * The Reclaim session and the relay do not exist yet (#17), and which Reclaim SDK runs in the browser - * depends on how the relay is built (ARCHITECTURE.md §3), so none is installed. Until - * NEXT_PUBLIC_RELAY_URL is set, a mock walks through the same stages with realistic delays and + * With NEXT_PUBLIC_RELAY_URL and NEXT_PUBLIC_GOOGLE_CLIENT_ID set, the creator signs in with Google's + * own popup and the relay makes the proof (`relay.ts`). No Reclaim SDK runs in the browser. While + * NEXT_PUBLIC_RELAY_URL is empty, a mock walks through the same stages with realistic delays and * returns fixed values. Everything after this seam (quote, request_advance, signing, errors) is real. */ import { mockProveRevenue } from "./mock"; +import { googleSignIn, preloadGoogleSignIn, relayProveRevenue, sessionJobs } from "./relay"; import { RelayNotReadyError, type ProveSession, type ProveStage } from "./session"; -export { ReclaimCancelledError, RelayNotReadyError, type ProveSession, type ProveStage } from "./session"; +export { + ReclaimCancelledError, + RelayError, + RelayNotReadyError, + type ProveSession, + type ProveStage, + type RelayErrorCode, +} from "./session"; const RELAY_URL = process.env.NEXT_PUBLIC_RELAY_URL ?? ""; +const GOOGLE_CLIENT_ID = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID ?? ""; +// The e2e relay answers at once, so its jobs are polled faster than a real one's. +const POLL_MS = process.env.NEXT_PUBLIC_E2E === "1" ? 200 : undefined; export function proveRevenue(borrower: string, onStage: (stage: ProveStage) => void): ProveSession { if (!RELAY_URL) return mockProveRevenue(borrower, onStage); - return { result: Promise.reject(new RelayNotReadyError()), reopen: () => {}, abandon: () => {} }; + if (!GOOGLE_CLIENT_ID) return { result: Promise.reject(new RelayNotReadyError()), reopen: () => {}, abandon: () => {} }; + return relayProveRevenue(borrower, onStage, { relayUrl: RELAY_URL, signIn: googleSignIn(GOOGLE_CLIENT_ID), pollMs: POLL_MS }); +} + +/** A proof the relay is still making for this wallet, started from this tab before the creator left. */ +export function proofRunning(borrower: string): boolean { + return !!RELAY_URL && !!GOOGLE_CLIENT_ID && sessionJobs.load(borrower) !== null; +} + +/** Load Google's sign-in ahead of "Prove my revenue", so the popup opens inside the press. */ +export function preloadSignIn(): void { + if (RELAY_URL && GOOGLE_CLIENT_ID) preloadGoogleSignIn(); } diff --git a/fe/src/lib/reclaim/relay.test.ts b/fe/src/lib/reclaim/relay.test.ts new file mode 100644 index 0000000..92b5be6 --- /dev/null +++ b/fe/src/lib/reclaim/relay.test.ts @@ -0,0 +1,262 @@ +import { describe, expect, it } from "vitest"; +import { relayProveRevenue, type JobStore, type SignIn } from "./relay"; +import { ReclaimCancelledError, RelayError, type ProveStage } from "./session"; + +const BORROWER = "GA2CD6PMHMBTCFAQDO3R22BSZN5ZSVTAKVNOKXL2SONZBLGRAYIOWWH2"; +const REQUEST = { + revenueUsd: "1234.56", + pubId: "pub-1234567890123456", + windowStart: "2026-07-01", + windowEnd: "2026-09-30", + timestampS: "1792467390", + epoch: "1", + signature: "ab".repeat(64), + recoveryId: 1, +}; + +/** A relay that answers POST /proofs, then `polls` job states in turn. */ +function relay(polls: object[], post: { status: number; body: object } = { status: 202, body: { id: "j1", stage: "queued" } }) { + const calls: { url: string; init?: RequestInit }[] = []; + let i = 0; + const fetch = (async (url: string, init?: RequestInit) => { + calls.push({ url, init }); + if (init?.method === "POST") return new Response(JSON.stringify(post.body), { status: post.status }); + return new Response(JSON.stringify(polls[Math.min(i++, polls.length - 1)])); + }) as unknown as typeof globalThis.fetch; + return { fetch, calls }; +} + +const signedIn: SignIn = async () => "ya29.token"; + +/** A tab's job store, in memory. */ +function store(kept: { borrower: string; id: string } | null = null) { + const s = { kept }; + const jobs: JobStore = { + load: (b) => (s.kept?.borrower === b ? s.kept.id : null), + save: (borrower, id) => (s.kept = { borrower, id }), + clear: () => (s.kept = null), + }; + return Object.assign(s, { jobs }); +} +const noSleep = async () => {}; + +describe("relayProveRevenue", () => { + it("signs in, hands the relay the borrower and the token, and returns request_advance's arguments", async () => { + const r = relay([{ id: "j1", stage: "proving" }, { id: "j1", stage: "done", request: REQUEST }]); + const stages: ProveStage[] = []; + const s = relayProveRevenue(BORROWER, (st) => stages.push(st), { + relayUrl: "https://relay.example/", + signIn: signedIn, + fetch: r.fetch, + sleep: noSleep, + jobs: store().jobs, + }); + const req = await s.result; + expect(stages).toEqual(["waiting", "reading"]); + expect(req).toEqual({ ...REQUEST, timestampS: 1792467390n, epoch: 1n }); + expect(r.calls[0].url).toBe("https://relay.example/proofs"); + expect(JSON.parse(String(r.calls[0].init?.body))).toEqual({ borrower: BORROWER, accessToken: "ya29.token" }); + expect(r.calls.slice(1).map((c) => c.url)).toEqual(["https://relay.example/proofs/j1", "https://relay.example/proofs/j1"]); + }); + + it("closing Google's popup is the same as closing the AdSense window", async () => { + const r = relay([]); + const s = relayProveRevenue(BORROWER, () => {}, { + relayUrl: "https://relay.example", + signIn: async () => { + throw new ReclaimCancelledError(); + }, + fetch: r.fetch, + sleep: noSleep, + jobs: store().jobs, + }); + await expect(s.result).rejects.toBeInstanceOf(ReclaimCancelledError); + expect(r.calls).toEqual([]); + }); + + it("a failed job keeps the relay's code", async () => { + const r = relay([{ id: "j1", stage: "failed", error: { code: "account", message: "not READY" } }]); + const s = relayProveRevenue(BORROWER, () => {}, { relayUrl: "https://r", signIn: signedIn, fetch: r.fetch, sleep: noSleep, jobs: store().jobs }); + const e = await s.result.catch((x) => x); + expect(e).toBeInstanceOf(RelayError); + expect((e as RelayError).code).toBe("account"); + }); + + it("names the relay's refusal by its code, and by the status when there is none", async () => { + const cases: [number, object, string][] = [ + [409, { error: "x", code: "running" }, "running"], + [503, { error: "x", code: "busy" }, "busy"], + [503, { error: "x", code: "unconfigured" }, "unconfigured"], + [409, {}, "running"], + [503, {}, "busy"], + [500, {}, "internal"], + ]; + for (const [status, body, code] of cases) { + const r = relay([], { status, body }); + const s = relayProveRevenue(BORROWER, () => {}, { relayUrl: "https://r", signIn: signedIn, fetch: r.fetch, sleep: noSleep, jobs: store().jobs }); + expect(((await s.result.catch((x) => x)) as RelayError).code, `${status} ${JSON.stringify(body)}`).toBe(code); + } + }); + + it("a relay that does not answer is unreachable, not Stellar", async () => { + const fetch = (async () => { + throw new TypeError("Failed to fetch"); + }) as unknown as typeof globalThis.fetch; + const s = relayProveRevenue(BORROWER, () => {}, { relayUrl: "https://r", signIn: signedIn, fetch, sleep: noSleep, jobs: store().jobs }); + const e = await s.result.catch((x) => x); + expect(e).toBeInstanceOf(RelayError); + expect((e as RelayError).code).toBe("unreachable"); + }); + + it("keeps the job id while proving and forgets it once the job ends", async () => { + const t = store(); + let seen: string | null = null; + const fetch = (async (_url: string, init?: RequestInit) => { + if (init?.method === "POST") return new Response(JSON.stringify({ id: "j1", stage: "queued" }), { status: 202 }); + seen = t.jobs.load(BORROWER); + return new Response(JSON.stringify({ id: "j1", stage: "done", request: REQUEST })); + }) as unknown as typeof globalThis.fetch; + await relayProveRevenue(BORROWER, () => {}, { relayUrl: "https://r", signIn: signedIn, fetch, sleep: noSleep, jobs: t.jobs }).result; + expect(seen).toBe("j1"); + expect(t.kept).toBeNull(); + }); + + it("coming back to a job still running waits on it, with no second sign-in and no second proof", async () => { + const t = store({ borrower: BORROWER, id: "j1" }); + const r = relay([{ id: "j1", stage: "proving" }, { id: "j1", stage: "done", request: REQUEST }]); + let signIns = 0; + const stages: ProveStage[] = []; + const s = relayProveRevenue(BORROWER, (st) => stages.push(st), { + relayUrl: "https://r", + signIn: async () => { + signIns++; + return "ya29.token"; + }, + fetch: r.fetch, + sleep: noSleep, + jobs: t.jobs, + }); + expect(await s.result).toEqual({ ...REQUEST, timestampS: 1792467390n, epoch: 1n }); + expect(signIns).toBe(0); + expect(stages).toEqual(["reading"]); + expect(r.calls.every((c) => c.init?.method !== "POST")).toBe(true); + expect(t.kept).toBeNull(); + }); + + it("a kept job the relay no longer has ends as gone, and never opens Google's popup outside a press", async () => { + const t = store({ borrower: BORROWER, id: "gone" }); + const calls: string[] = []; + const fetch = (async (url: string, init?: RequestInit) => { + calls.push(`${init?.method ?? "GET"} ${url}`); + return new Response(JSON.stringify({ error: "no such proof job" }), { status: 404 }); + }) as unknown as typeof globalThis.fetch; + let signIns = 0; + const signIn: SignIn = async () => { + signIns++; + return "ya29.token"; + }; + const stages: ProveStage[] = []; + const s = relayProveRevenue(BORROWER, (st) => stages.push(st), { relayUrl: "https://r", signIn, fetch, sleep: noSleep, jobs: t.jobs }); + const e = await s.result.catch((x) => x); + expect(e).toBeInstanceOf(RelayError); + expect((e as RelayError).code).toBe("gone"); + expect(signIns).toBe(0); + expect(stages).toEqual(["reading"]); + expect(calls).toEqual(["GET https://r/proofs/gone"]); + expect(t.kept).toBeNull(); + }); + + it("a poll that fails on the network keeps the id; the next press follows it and a 404 is still gone, with no sign-in", async () => { + const t = store({ borrower: BORROWER, id: "gone" }); + let down = true; + const fetch = (async () => { + if (down) throw new TypeError("Failed to fetch"); + return new Response(JSON.stringify({ error: "no such proof job" }), { status: 404 }); + }) as unknown as typeof globalThis.fetch; + let signIns = 0; + const signIn: SignIn = async () => { + signIns++; + return "ya29.token"; + }; + const o = { relayUrl: "https://r", signIn, fetch, sleep: noSleep, jobs: t.jobs }; + const first = await relayProveRevenue(BORROWER, () => {}, o).result.catch((x) => x); + expect((first as RelayError).code).toBe("unreachable"); + expect(t.kept).toEqual({ borrower: BORROWER, id: "gone" }); + down = false; + const second = await relayProveRevenue(BORROWER, () => {}, o).result.catch((x) => x); + expect((second as RelayError).code).toBe("gone"); + expect(signIns).toBe(0); + expect(t.kept).toBeNull(); + }); + + it("after a gone job, the next press signs in and starts a fresh proof", async () => { + const t = store({ borrower: BORROWER, id: "gone" }); + const fetch = (async (url: string, init?: RequestInit) => { + if (init?.method === "POST") return new Response(JSON.stringify({ id: "j2", stage: "queued" }), { status: 202 }); + if (url.endsWith("/gone")) return new Response(JSON.stringify({ error: "no such proof job" }), { status: 404 }); + return new Response(JSON.stringify({ id: "j2", stage: "done", request: REQUEST })); + }) as unknown as typeof globalThis.fetch; + const o = { relayUrl: "https://r", signIn: signedIn, fetch, sleep: noSleep, jobs: t.jobs }; + await relayProveRevenue(BORROWER, () => {}, o).result.catch(() => {}); + const stages: ProveStage[] = []; + await relayProveRevenue(BORROWER, (st) => stages.push(st), o).result; + expect(stages).toEqual(["waiting", "reading"]); + }); + + it("a job kept for another wallet is not this one's", async () => { + const t = store({ borrower: "GOTHER", id: "j9" }); + const r = relay([{ id: "j1", stage: "done", request: REQUEST }]); + await relayProveRevenue(BORROWER, () => {}, { relayUrl: "https://r", signIn: signedIn, fetch: r.fetch, sleep: noSleep, jobs: t.jobs }).result; + expect(r.calls[0].init?.method).toBe("POST"); + }); + + it("opening the window again waits on the newest popup, and an older one closing does not end it", async () => { + let n = 0; + const releases: ((t: string) => void)[] = []; + const rejects: ((e: unknown) => void)[] = []; + const signIn: SignIn = () => + new Promise((res, rej) => { + n++; + releases.push(res); + rejects.push(rej); + }); + const r = relay([{ id: "j1", stage: "done", request: REQUEST }]); + const stages: ProveStage[] = []; + const s = relayProveRevenue(BORROWER, (st) => stages.push(st), { relayUrl: "https://r", signIn, fetch: r.fetch, sleep: noSleep, jobs: store().jobs }); + s.reopen(); + expect(n).toBe(2); + rejects[0](new ReclaimCancelledError()); + releases[1]("ya29.second"); + await s.result; + expect(stages).toEqual(["waiting", "waiting", "reading"]); + expect(JSON.parse(String(r.calls[0].init?.body)).accessToken).toBe("ya29.second"); + }); + + it("an abandoned session stops polling and never settles", async () => { + let polls = 0; + const fetch = (async (_url: string, init?: RequestInit) => { + if (init?.method === "POST") return new Response(JSON.stringify({ id: "j1", stage: "queued" }), { status: 202 }); + polls++; + return new Response(JSON.stringify({ id: "j1", stage: "proving" })); + }) as unknown as typeof globalThis.fetch; + let wake!: () => void; + const s = relayProveRevenue(BORROWER, () => {}, { + relayUrl: "https://r", + signIn: signedIn, + fetch, + sleep: () => new Promise((r) => (wake = r)), + jobs: store().jobs, + }); + let settled = false; + s.result.then( + () => (settled = true), + () => (settled = true), + ); + await new Promise((r) => setTimeout(r, 0)); + s.abandon(); + wake(); + await new Promise((r) => setTimeout(r, 0)); + expect(polls).toBe(0); + expect(settled).toBe(false); + }); +}); diff --git a/fe/src/lib/reclaim/relay.ts b/fe/src/lib/reclaim/relay.ts new file mode 100644 index 0000000..63d8028 --- /dev/null +++ b/fe/src/lib/reclaim/relay.ts @@ -0,0 +1,295 @@ +/** + * The real session (#17): Google's own sign-in popup for a read-only AdSense token, then the relay + * proves the revenue with zkFetch and answers with `request_advance`'s arguments. The relay's API is in + * docs/api.md, "The proof relay". + * + * No Reclaim SDK runs here. The proof is made on the relay because the engine Reclaim's attestor accepts + * needs ~330 MB of circuit files and a minute or more of a whole CPU. The browser's part is the sign-in, and + * the token goes once to the relay, which binds the borrower's G… inside the signed claim. + * + * Stages: `waiting` while Google's popup is open, `reading` from the moment the relay has the job until + * it ends. + * + * The job id is kept for the length of the tab (`sessionJobs`). A creator who leaves /advance or reloads + * while the relay proves comes back to the same job, without a second sign-in, instead of starting a + * second proof the relay would refuse as already running (409). A kept job the relay no longer has + * ends the session as `gone`, so the sign-in it needs starts from a press. + */ +import type { AdvanceRequest } from "@/lib/stellar/contract"; +import { ReclaimCancelledError, RelayError, type ProveSession, type ProveStage, type RelayErrorCode } from "./session"; + +export const ADSENSE_SCOPE = "https://www.googleapis.com/auth/adsense.readonly"; +const GIS_SRC = "https://accounts.google.com/gsi/client"; + +/** The slice of Google Identity Services' token client used here. */ +type TokenResponse = { access_token?: string; error?: string; scope?: string }; +type TokenClient = { requestAccessToken: (o?: { prompt?: string }) => void }; +type Gis = { + initTokenClient: (config: { + client_id: string; + scope: string; + callback: (r: TokenResponse) => void; + error_callback?: (e: { type?: string }) => void; + }) => TokenClient; +}; +declare global { + interface Window { + google?: { accounts?: { oauth2?: Gis } }; + } +} + +let gisLoading: Promise | undefined; + +/** Load Google's script once. */ +function loadGis(): Promise { + const ready = () => window.google?.accounts?.oauth2; + const existing = ready(); + if (existing) return Promise.resolve(existing); + gisLoading ??= new Promise((resolve, reject) => { + const s = document.createElement("script"); + s.src = GIS_SRC; + s.async = true; + s.onload = () => { + const gis = ready(); + if (gis) resolve(gis); + else reject(new RelayError("googleUnavailable", "Google sign-in failed to load")); + }; + s.onerror = () => { + gisLoading = undefined; + reject(new RelayError("googleUnavailable", "Google sign-in failed to load (network)")); + }; + document.head.appendChild(s); + }); + return gisLoading; +} + +/** + * Load Google's script ahead of the press, so "Prove my revenue" opens the popup inside the click. + * Loaded only then, the popup opens after an await, outside the click, and browsers may block it. + */ +export function preloadGoogleSignIn(): void { + loadGis().catch(() => { + // The press will try again and report it. + }); +} + +/** Opens the popup each time it is called; resolves with the token, or rejects when the popup closes. */ +export type SignIn = () => Promise; + +export function googleSignIn(clientId: string): SignIn { + return async () => { + const gis = await loadGis(); + return new Promise((resolve, reject) => { + const client = gis.initTokenClient({ + client_id: clientId, + scope: ADSENSE_SCOPE, + callback: (r) => { + if (r.access_token && (r.scope ?? "").split(" ").includes(ADSENSE_SCOPE)) resolve(r.access_token); + // Denied, or allowed without the AdSense box ticked: the creator stopped, nothing was read. + else reject(new ReclaimCancelledError()); + }, + error_callback: (e) => + reject( + e.type === "popup_failed_to_open" + ? new RelayError("popupBlocked", "the browser blocked Google's sign-in window") + : new ReclaimCancelledError(), + ), + }); + client.requestAccessToken(); + }); + }; +} + +/** A relay job, as `GET /proofs/:id` answers it. */ +type Job = { + id: string; + stage: "queued" | "checking" | "proving" | "auditing" | "done" | "failed"; + request?: Omit & { timestampS: string; epoch: string }; + error?: { code: RelayErrorCode; message: string }; +}; + +/** Where the running job's id waits while the creator is away from /advance. */ +export type JobStore = { + load: (borrower: string) => string | null; + save: (borrower: string, id: string) => void; + clear: () => void; +}; + +// One slot for the tab: proving with a second wallet in the same tab replaces the first wallet's id. +// Rare, and that wallet then proves again once its job ends. +const JOB_KEY = "forepay.proof.job"; + +/** + * The job id, for the length of the tab. Only the id: the token never leaves the sign-in, and the id + * reads nothing the relay would not show this tab anyway. One for another wallet is not this one's. + */ +export const sessionJobs: JobStore = { + load: (borrower) => { + try { + const s = JSON.parse(window.sessionStorage.getItem(JOB_KEY) ?? "null") as { borrower: string; id: string } | null; + return s?.borrower === borrower ? s.id : null; + } catch { + return null; + } + }, + save: (borrower, id) => { + try { + window.sessionStorage.setItem(JOB_KEY, JSON.stringify({ borrower, id })); + } catch { + // Storage unavailable: leaving the page while proving loses the job, as before. + } + }, + clear: () => { + try { + window.sessionStorage.removeItem(JOB_KEY); + } catch { + // nothing to clear + } + }, +}; + +export type RelayOptions = { + relayUrl: string; + signIn: SignIn; + fetch?: typeof fetch; + jobs?: JobStore; + pollMs?: number; + /** + * Give up on a job after this long. A proof takes about a minute on the relay, more behind a queue; + * past an hour the claim is too old for the contract anyway, and the relay has forgotten the job. + */ + timeoutMs?: number; + sleep?: (ms: number) => Promise; +}; + +const CODES: readonly RelayErrorCode[] = ["token", "account", "running", "busy", "unconfigured", "provider", "prove", "audit", "internal"]; + +class Abandoned extends Error {} + +export function relayProveRevenue(borrower: string, onStage: (stage: ProveStage) => void, o: RelayOptions): ProveSession { + const base = o.relayUrl.replace(/\/+$/, ""); + const send = o.fetch ?? ((...a: Parameters) => fetch(...a)); + const jobs = o.jobs ?? sessionJobs; + const pollMs = o.pollMs ?? 5000; + const timeoutMs = o.timeoutMs ?? 60 * 60_000; + const sleep = o.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms))); + let abandoned = false; + let reading = false; + let attempt = 0; + let settleToken!: { resolve: (t: string) => void; reject: (e: unknown) => void }; + const token = new Promise((resolve, reject) => { + settleToken = { resolve, reject }; + }); + + const alive = () => { + if (abandoned) throw new Abandoned(); + }; + + /** + * Open Google's popup. Opened again ("Open the window again"), the newest popup is the one whose + * closing counts: a popup lost behind another window may never answer. + */ + function signIn() { + const mine = ++attempt; + onStage("waiting"); + o.signIn().then(settleToken.resolve, (e) => { + if (mine === attempt) settleToken.reject(e); + }); + } + + /** A relay that does not answer is the relay's, not Stellar's (review on #75). */ + async function call(url: string, init?: RequestInit): Promise { + try { + return await send(url, init); + } catch (e) { + throw new RelayError("unreachable", `the relay did not answer: ${(e as Error)?.message ?? e}`); + } + } + + async function json(res: Response): Promise { + const body = (await res.json().catch(() => ({}))) as T & { error?: unknown; code?: unknown }; + if (!res.ok) { + const message = typeof body.error === "string" ? body.error : `the relay answered ${res.status}`; + // The relay names the refusal in `code` (docs/api.md); the status is the fallback. + const code = CODES.find((c) => c === body.code) ?? (res.status === 409 ? "running" : res.status === 503 ? "busy" : "internal"); + throw new RelayError(code, message); + } + return body; + } + + /** Poll a job until it ends. Null when the relay no longer has it (it restarted, or an hour passed). */ + async function follow(id: string, first?: Job): Promise { + const deadline = Date.now() + timeoutMs; + let job = first; + while (!job || (job.stage !== "done" && job.stage !== "failed")) { + if (Date.now() > deadline) throw new RelayError("prove", "the proof took too long"); + if (job) await sleep(pollMs); + alive(); + const res = await call(`${base}/proofs/${encodeURIComponent(id)}`, { cache: "no-store" }); + if (res.status === 404) return null; + job = await json(res); + } + return job; + } + + async function prove(): Promise { + // A job this tab started before the creator left: wait on it rather than sign in again. + const kept = jobs.load(borrower); + if (kept) { + reading = true; + onStage("reading"); + const job = await follow(kept); + if (job) return job; + // The relay no longer has it (it restarted, or the hour passed). Signing in again here would open + // Google's popup outside any press, on mount or after an await, and the browser would block it + // (review on #75). The creator's next press opens it instead. + jobs.clear(); + throw new RelayError("gone", "the relay no longer has this proof job"); + } + signIn(); + const accessToken = await token; + alive(); + reading = true; + onStage("reading"); + const started = await json( + await call(`${base}/proofs`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ borrower, accessToken }), + }), + ); + jobs.save(borrower, started.id); + const job = await follow(started.id, started); + if (!job) throw new RelayError("internal", "the relay lost the proof job"); + return job; + } + + async function run(): Promise { + const job = await prove(); + alive(); + // Ended either way: the next press starts a new proof. Left alone while abandoned, so coming back + // finds the result. + jobs.clear(); + if (job.stage === "failed" || !job.request) { + throw new RelayError(job.error?.code ?? "internal", job.error?.message ?? "the proof failed"); + } + return { ...job.request, timestampS: BigInt(job.request.timestampS), epoch: BigInt(job.request.epoch) }; + } + + // Never settles once abandoned, as the session promises. + const result = new Promise((resolve, reject) => { + run().then(resolve, (e) => { + if (!(e instanceof Abandoned) && !abandoned) reject(e); + }); + }); + + return { + result, + reopen: () => { + if (!reading && !abandoned) signIn(); + }, + abandon: () => { + abandoned = true; + }, + }; +} diff --git a/fe/src/lib/reclaim/session.ts b/fe/src/lib/reclaim/session.ts index 5f12002..159609c 100644 --- a/fe/src/lib/reclaim/session.ts +++ b/fe/src/lib/reclaim/session.ts @@ -2,9 +2,9 @@ import type { AdvanceRequest } from "@/lib/stellar/contract"; export type ProveStage = - /** A Reclaim window is open. The creator logs in to AdSense there, not on our page. */ + /** Google's sign-in window is open. The creator signs in to AdSense there, not on our page. */ | "waiting" - /** The login worked. The revenue figure is being turned into a proof. */ + /** The sign-in worked. The relay is turning the revenue figure into a proof (#17). */ | "reading"; export type ProveSession = { @@ -24,10 +24,48 @@ export class ReclaimCancelledError extends Error { } } -/** The relay is configured, but its client is not written yet (#17). */ +/** The relay is configured without the Google OAuth client id the sign-in needs (#17). */ export class RelayNotReadyError extends Error { constructor() { - super("NEXT_PUBLIC_RELAY_URL is set, but the #17 relay client is not built yet"); + super("NEXT_PUBLIC_RELAY_URL is set, but NEXT_PUBLIC_GOOGLE_CLIENT_ID is not"); this.name = "RelayNotReadyError"; } } + +/** + * Why the relay could not make the proof, by whose move it is (docs/api.md): + * - `token`: Google refused the sign-in, for example an expired one. Signing in again fixes it. + * - `account`: no approved AdSense account behind that Google account. + * - `running`: a proof for this wallet is already running, started from a tab that no longer has it. + * - `gone`: the proof this tab was waiting on is no longer on the relay (it restarted, or an hour passed). + * - `busy`: the relay is proving for others and its queue is full. + * - `unconfigured`: the relay answers, but proving is not set up on it. + * - `unreachable`: the relay did not answer at all. + * - `googleUnavailable`: Google's sign-in script did not load. + * - `popupBlocked`: the browser blocked Google's sign-in window. The creator closed nothing. + * - `provider`, `prove`, `audit`, `internal`: the relay's side. Trying again may work. + */ +export type RelayErrorCode = + | "token" + | "account" + | "running" + | "gone" + | "busy" + | "unconfigured" + | "unreachable" + | "googleUnavailable" + | "popupBlocked" + | "provider" + | "prove" + | "audit" + | "internal"; + +export class RelayError extends Error { + constructor( + readonly code: RelayErrorCode, + message: string, + ) { + super(message); + this.name = "RelayError"; + } +} diff --git a/fe/src/modules/advance/Advance.tsx b/fe/src/modules/advance/Advance.tsx index c2623ec..1994966 100644 --- a/fe/src/modules/advance/Advance.tsx +++ b/fe/src/modules/advance/Advance.tsx @@ -7,7 +7,7 @@ import { SkeletonBlock } from "@/components/ui/Skeleton"; import { notify } from "@/components/ui/Toaster"; import { isSignatureDeclined } from "@/lib/errors"; import { formatUsd, formatWindow } from "@/lib/format"; -import { proveRevenue, type ProveSession, type ProveStage } from "@/lib/reclaim"; +import { preloadSignIn, proofRunning, proveRevenue, type ProveSession, type ProveStage } from "@/lib/reclaim"; import { TransactionFailedError, awaitAdvance, @@ -56,6 +56,20 @@ class AbandonedError extends Error {} const quoteKey = (address: string, revenueUsd: string) => ["quote", address, revenueUsd] as const; const sizingKey = (address: string) => ["sizing", address] as const; +/** + * "Reading your revenue". The words describe the relay (#17): about a minute, more behind a queue, and + * the job id is kept for the tab, so other pages are safe and a closed tab loses it (lib/reclaim/relay.ts). + * The mock (no relay) does not resume after leaving, which is acceptable for a build without proofs. + */ +function ReadingRevenue() { + return ( + + ); +} + /** * 02 Prove and accept (#20): 2a Prove revenue, 2b Review offer, 2c Sign, 2d Receive, and every state on * the "Prove and accept / States and interactions" board. @@ -87,16 +101,24 @@ export function Advance() { [], ); - // Back on /advance with a `request_advance` still out from an earlier visit: wait on that one. Each + // Back on /advance with a `request_advance` still out from an earlier visit: wait on that one. Or with + // a proof the relay is still making for this wallet: wait on that, without signing in again. Each // mount waits afresh; the unmount above drops the answer of the one before. useEffect(() => { if (!address) return; const pending = loadPending(address); if (pending) void pickUp(pending); - // `pickUp` only reads refs and setters; it runs per mount and per wallet. + else if (proofRunning(address)) void prove(); + // `pickUp` and `prove` only read refs and setters; they run per mount and per wallet. // eslint-disable-next-line react-hooks/exhaustive-deps }, [address]); + // Google's sign-in script, loaded while 2a is open, so "Prove my revenue" opens the popup inside the + // press. Loaded only on the press, the popup opens after an await and browsers may block it. + useEffect(() => { + if (flow.at === "start" || flow.at === "failed") preloadSignIn(); + }, [flow.at]); + // The offer on 2b and 2c. Read in `check` before 2b opens, so it is already here. const req = "req" in flow ? flow.req : undefined; const offer = useQuery({ @@ -146,6 +168,9 @@ export function Advance() { // While an advance sent earlier is still being waited on, the start is that wait, not 2a. const pending = loadPending(me); if (pending) return void pickUp(pending); + // Likewise a proof the relay may still be making (a poll that failed kept its id): wait on it, so + // "Reading your revenue" on the start is always backed by a running session. + if (proofRunning(me)) return void prove(); setFlow({ at: "start" }); } @@ -200,6 +225,9 @@ export function Advance() { } async function accept(r: AdvanceRequest) { + // No clock check on the proof's age here: `requestAdvance` simulates before it asks the wallet, and the + // contract refuses a proof over an hour old with 12 ("This proof expired"), so no signature is asked + // for a stale proof (e2e "a proof that expires while the offer is open…"). leave(); const id = attempt.current; let signed = false; @@ -370,6 +398,16 @@ export function Advance() { if (flow.at === "start") { // A transaction left waiting from an earlier visit is picked up by the effect above, after this // first render. Show it as sending from the start, so 2a and its "Prove my revenue" never flash. + // Likewise a proof the relay is still making for this wallet: the effect waits on it. + if (proofRunning(me)) { + return ( + + + + + + ); + } if (loadPending(me)) { return ( @@ -405,8 +443,8 @@ export function Advance() { /> ) : flow.stage === "waiting" ? ( session.current?.reopen()}> Open the window again @@ -414,7 +452,7 @@ export function Advance() { } /> ) : ( - + )} diff --git a/fe/src/modules/advance/components/FailurePanel.tsx b/fe/src/modules/advance/components/FailurePanel.tsx index 1bd14cf..aeabd54 100644 --- a/fe/src/modules/advance/components/FailurePanel.tsx +++ b/fe/src/modules/advance/components/FailurePanel.tsx @@ -124,6 +124,24 @@ export function FailurePanel({ illustration = ; actions = ; break; + case "proofGone": + illustration = ; + actions = <>{proveAgain}{back}; + row = true; + break; + // The relay's failures (#17). Not on the board yet; "Prove again" with "Back", as its pairs are. + case "googleSignIn": + case "noAdsense": + case "relayFailed": + case "relayBusy": + case "proofRunning": + case "relayUnreachable": + case "googleUnavailable": + case "popupBlocked": + illustration = ; + actions = <>{proveAgain}{back}; + row = true; + break; case "declined": illustration = ; actions = ; diff --git a/fe/src/modules/advance/components/ProveRevenue.tsx b/fe/src/modules/advance/components/ProveRevenue.tsx index 014a1ad..5dce400 100644 --- a/fe/src/modules/advance/components/ProveRevenue.tsx +++ b/fe/src/modules/advance/components/ProveRevenue.tsx @@ -41,7 +41,7 @@ export function ProveRevenue({

See how much you can get

- Log in to AdSense in a secure window. We read your revenue for the last three months and nothing else. + Sign in with Google in a secure window. We read your AdSense revenue for the last three months and nothing else.

{/* Side by side only where each list keeps its longest item ("Revenue from the last three complete months", about 360 in Body) on one line: two of them and the 24 gap. */} diff --git a/fe/src/modules/advance/failures.test.ts b/fe/src/modules/advance/failures.test.ts index 2d23528..2327956 100644 --- a/fe/src/modules/advance/failures.test.ts +++ b/fe/src/modules/advance/failures.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { ReclaimCancelledError, RelayNotReadyError } from "@/lib/reclaim"; +import { ReclaimCancelledError, RelayError, RelayNotReadyError } from "@/lib/reclaim"; import { ContractError, MissingConfigError, SimulationError, TransactionFailedError } from "@/lib/stellar/contract"; import { WalletError } from "@/lib/stellar/wallet-error"; import { WalletSignError } from "@/lib/stellar/wallet-error"; @@ -9,6 +9,18 @@ describe("proveFailure", () => { it("names each cause on its own", () => { expect(proveFailure(new ReclaimCancelledError())).toEqual({ kind: "cancelled" }); expect(proveFailure(new RelayNotReadyError())).toEqual({ kind: "relayNotReady" }); + expect(proveFailure(new RelayError("token", "x"))).toEqual({ kind: "googleSignIn" }); + expect(proveFailure(new RelayError("account", "x"))).toEqual({ kind: "noAdsense" }); + expect(proveFailure(new RelayError("running", "x"))).toEqual({ kind: "proofRunning" }); + expect(proveFailure(new RelayError("gone", "x"))).toEqual({ kind: "proofGone" }); + expect(proveFailure(new RelayError("unconfigured", "x"))).toEqual({ kind: "relayNotReady" }); + expect(proveFailure(new RelayError("unreachable", "x"))).toEqual({ kind: "relayUnreachable" }); + expect(proveFailure(new RelayError("googleUnavailable", "x"))).toEqual({ kind: "googleUnavailable" }); + expect(proveFailure(new RelayError("popupBlocked", "x"))).toEqual({ kind: "popupBlocked" }); + expect(proveFailure(new RelayError("busy", "x"))).toEqual({ kind: "relayBusy" }); + for (const code of ["provider", "prove", "audit", "internal"] as const) { + expect(proveFailure(new RelayError(code, "x"))).toEqual({ kind: "relayFailed" }); + } expect(proveFailure(new ContractError(14, "x"))).toEqual({ code: 14 }); expect(proveFailure(new SimulationError("HostError: Error(Auth, InvalidAction)"))).toEqual({ kind: "simulationFailed" }); expect(proveFailure(new MissingConfigError("NEXT_PUBLIC_ADVANCE_CONTRACT_ID"))).toEqual({ kind: "notConfigured" }); diff --git a/fe/src/modules/advance/failures.ts b/fe/src/modules/advance/failures.ts index 80c63b2..2d7b4d0 100644 --- a/fe/src/modules/advance/failures.ts +++ b/fe/src/modules/advance/failures.ts @@ -1,6 +1,6 @@ import { classifySignError, type ProveFailure } from "@/lib/errors"; import { formatUsd } from "@/lib/format"; -import { ReclaimCancelledError, RelayNotReadyError } from "@/lib/reclaim"; +import { ReclaimCancelledError, RelayError, RelayNotReadyError, type RelayErrorCode } from "@/lib/reclaim"; import { ContractError, MissingConfigError, SimulationError, TransactionFailedError } from "@/lib/stellar/contract"; import { WalletSignError } from "@/lib/stellar/wallet-error"; @@ -14,6 +14,20 @@ export type AdvanceFailure = { code: number } | { kind: ProveFailure } | { kind: function sorted(e: unknown): AdvanceFailure { if (e instanceof ReclaimCancelledError) return { kind: "cancelled" }; if (e instanceof RelayNotReadyError) return { kind: "relayNotReady" }; + if (e instanceof RelayError) { + const kinds: Partial> = { + token: "googleSignIn", + account: "noAdsense", + running: "proofRunning", + gone: "proofGone", + busy: "relayBusy", + unconfigured: "relayNotReady", + unreachable: "relayUnreachable", + googleUnavailable: "googleUnavailable", + popupBlocked: "popupBlocked", + }; + return { kind: kinds[e.code] ?? "relayFailed" }; + } if (e instanceof ContractError) return { code: e.code }; if (e instanceof SimulationError) return { kind: "simulationFailed" }; if (e instanceof MissingConfigError) return { kind: "notConfigured" }; diff --git a/fe/tests/e2e/advance.spec.ts b/fe/tests/e2e/advance.spec.ts index a671147..8a014a4 100644 --- a/fe/tests/e2e/advance.spec.ts +++ b/fe/tests/e2e/advance.spec.ts @@ -55,7 +55,7 @@ test("prove, see the offer with its derivation, accept, and receive the USDC", a await page.getByRole("button", { name: "Prove my revenue" }).click(); // The Reclaim session, then the check on Stellar - await expect(heading(page, "Log in to AdSense in the new window")).toBeVisible(); + await expect(heading(page, "Sign in with Google in the new window")).toBeVisible(); await expect(page.getByRole("button", { name: "Open the window again" })).toBeVisible(); await expect(heading(page, "Reading your revenue")).toBeVisible(); await expect(heading(page, "Checking your proof")).toBeVisible(); @@ -272,10 +272,10 @@ test("an advance under 1 USDC is refused before anything is sent, and the proof await expect(heading(page, "See how much you can get")).toBeVisible(); }); -test("closing the AdSense window is named, and proving can start again", async ({ page }) => { +test("closing the Google window is named, and proving can start again", async ({ page }) => { await connect(page, { account: true, trustline: true }, { "forepay.mock.reclaim": "cancel" }); await page.getByRole("button", { name: "Prove my revenue" }).click(); - await expect(heading(page, "You closed the AdSense window")).toBeVisible(); + await expect(heading(page, "You closed the Google window")).toBeVisible(); await expect(page.getByText("Nothing was read or saved. Start again when you are ready.")).toBeVisible(); await page.evaluate(() => window.localStorage.removeItem("forepay.mock.reclaim")); await page.getByRole("button", { name: "Prove my revenue" }).click(); @@ -342,7 +342,7 @@ test("Open the window again keeps waiting for the AdSense login, then goes on", await connect(page, { account: true, trustline: true }); await page.getByRole("button", { name: "Prove my revenue" }).click(); await page.getByRole("button", { name: "Open the window again" }).click(); - await expect(heading(page, "Log in to AdSense in the new window")).toBeVisible(); + await expect(heading(page, "Sign in with Google in the new window")).toBeVisible(); await expect(page.getByRole("button", { name: "Accept 90.00 USDC" })).toBeVisible(); }); @@ -374,7 +374,7 @@ test("a proof that expires while the offer is open is named at accept, and Prove await expect(heading(page, "Approve the advance")).toBeVisible(); expect(chain.advance?.sent ?? 0).toBe(0); await page.getByRole("button", { name: "Prove again" }).click(); - await expect(heading(page, "Log in to AdSense in the new window")).toBeVisible(); + await expect(heading(page, "Sign in with Google in the new window")).toBeVisible(); }); test("a proof already used, found at accept, is named, and Back leaves the offer behind", async ({ page }) => { diff --git a/fe/tests/e2e/layout.spec.ts b/fe/tests/e2e/layout.spec.ts index f1390bf..f1ffc7f 100644 --- a/fe/tests/e2e/layout.spec.ts +++ b/fe/tests/e2e/layout.spec.ts @@ -302,7 +302,7 @@ test("advance in progress: proving, approving in the wallet, sending, and 2d", a // The mock's proving stages last under a second each: the walk measures whichever one shows. await page.goto("/advance"); await page.getByRole("button", { name: "Prove my revenue" }).click(); - await expect(heading(page, "Log in to AdSense in the new window")).toBeVisible(); + await expect(heading(page, "Sign in with Google in the new window")).toBeVisible(); await holdsAtEveryWidth(page, "2a proving"); await page.setViewportSize({ width: 1440, height: 900 }); await expect(page.getByRole("button", { name: "Accept 90.00 USDC" })).toBeVisible(); diff --git a/fe/tests/e2e/relay.spec.ts b/fe/tests/e2e/relay.spec.ts new file mode 100644 index 0000000..b361427 --- /dev/null +++ b/fe/tests/e2e/relay.spec.ts @@ -0,0 +1,291 @@ +import { expect, test, type Page } from "@playwright/test"; +import { E2E_ADDRESS } from "../../src/lib/stellar/wallet-e2e"; +import { frameLedger, mockApi } from "./api"; +import { mockRpc } from "./rpc"; + +// #17: proving through the relay, on the build whose NEXT_PUBLIC_RELAY_URL and Google client id are set +// (the relay-* projects in playwright.config.ts). Google's sign-in is a stub on `window.google`, which +// lib/reclaim/relay.ts uses when it is already there, and the relay is answered here as docs/api.md +// describes it. Everything after the proof is the stubbed contract, as in advance.spec.ts. + +test.afterEach(async ({ page }) => { + await page.unrouteAll({ behavior: "ignoreErrors" }); +}); + +/** What Google's popup does when it opens: hand back a token, close, be blocked, or stay open. */ +type Popup = "ok" | "closed" | "blocked" | "open"; + +type Gis = { mode: Popup; opened: number }; +declare global { + interface Window { + __gis: Gis; + } +} + +/** A stand-in for Google Identity Services' token client, counting the popups it opens. */ +async function stubGoogle(page: Page, mode: Popup) { + await page.addInitScript((m: Popup) => { + window.__gis = { mode: m, opened: 0 }; + type Config = { scope: string; callback: (r: object) => void; error_callback?: (e: object) => void }; + window.google = { + accounts: { + oauth2: { + initTokenClient: (c: Config) => ({ + requestAccessToken: () => { + window.__gis.opened++; + const now = window.__gis.mode; + setTimeout(() => { + if (now === "ok") c.callback({ access_token: "ya29.e2e", scope: c.scope }); + else if (now === "closed") c.error_callback?.({ type: "popup_closed" }); + else if (now === "blocked") c.error_callback?.({ type: "popup_failed_to_open" }); + }, 600); + }, + }), + }, + }, + } as unknown as Window["google"]; + }, mode); +} + +const opened = (page: Page) => page.evaluate(() => window.__gis.opened); + +const REQUEST = { + revenueUsd: "360.00", + pubId: "pub-4021783466891204", + windowStart: "2026-07-01", + windowEnd: "2026-09-30", + epoch: "1", + signature: "5a".repeat(64), + recoveryId: 0, +}; + +/** + * The relay. `post` answers POST /proofs; `jobs` lists the states each job id answers in turn (the last + * one repeats); an id not there answers 404. While `hold` is set, every job answers `proving`. + */ +type Relay = { + post: { status: number; body: object }; + jobs: Record; + hold?: boolean; + posts: { borrower: string; accessToken: string }[]; +}; + +function relayFor(jobs: Relay["jobs"] = { j1: [{ id: "j1", stage: "proving" }, done("j1")] }): Relay { + return { post: { status: 202, body: { id: "j1", stage: "queued" } }, jobs, posts: [] }; +} + +function done(id: string) { + return { id, stage: "done", request: { ...REQUEST, timestampS: String(Math.floor(Date.now() / 1000)) } }; +} + +async function mockRelay(page: Page, relay: Relay) { + await page.route("https://relay.e2e.invalid/**", async (route) => { + const headers = { "access-control-allow-origin": "*" }; + const req = route.request(); + const { pathname } = new URL(req.url()); + if (req.method() === "POST" && pathname === "/proofs") { + relay.posts.push(req.postDataJSON()); + return route.fulfill({ status: relay.post.status, headers, contentType: "application/json", body: JSON.stringify(relay.post.body) }); + } + const id = decodeURIComponent(pathname.replace(/^\/proofs\//, "")); + const states = relay.jobs[id]; + if (!states) return route.fulfill({ status: 404, headers, contentType: "application/json", body: '{"error":"no such proof job"}' }); + const state = relay.hold ? { id, stage: "proving" } : states.length > 1 ? states.shift() : states[0]; + return route.fulfill({ headers, contentType: "application/json", body: JSON.stringify(state) }); + }); +} + +/** `popup` null leaves `window.google` unset, so the app loads Google's script itself (routed by the test). */ +async function connect(page: Page, relay: Relay, popup: Popup | null) { + if (popup) await stubGoogle(page, popup); + await mockRelay(page, relay); + await mockRpc(page, { account: true, trustline: true }); + await mockApi(page, frameLedger()); + await page.goto("/start"); + await page.getByRole("button", { name: "Get started" }).click(); + await page.getByRole("button", { name: "Connect wallet" }).click(); + await page.getByRole("dialog", { name: "Connect wallet" }).getByRole("button").first().click(); + await expect(page).toHaveURL(/\/advance$/); +} + +const heading = (page: Page, name: string) => page.getByRole("heading", { name, exact: true }); +const prove = (page: Page) => page.getByRole("button", { name: "Prove my revenue" }).click(); +const proveAgain = (page: Page) => page.getByRole("button", { name: "Prove again" }).click(); + +test("signs in with Google, the relay proves, and the offer follows", async ({ page }) => { + const relay = relayFor(); + await connect(page, relay, "ok"); + await prove(page); + await expect(heading(page, "Sign in with Google in the new window")).toBeVisible(); + await expect(heading(page, "Reading your revenue")).toBeVisible(); + await expect(page.getByText("This takes about a minute, longer when others are proving too.", { exact: false })).toBeVisible(); + await expect(page.getByRole("button", { name: "Accept 90.00 USDC" })).toBeVisible(); + expect(relay.posts).toEqual([{ borrower: E2E_ADDRESS, accessToken: "ya29.e2e" }]); + expect(await opened(page)).toBe(1); +}); + +test("a Google account with no AdSense the relay can read is named", async ({ page }) => { + const relay = relayFor({ j1: [{ id: "j1", stage: "failed", error: { code: "account", message: "no AdSense account" } }] }); + await connect(page, relay, "ok"); + await prove(page); + await expect(heading(page, "We could not use your AdSense account")).toBeVisible(); + await expect(page.getByText("We could not find one approved AdSense account on this Google account.", { exact: false })).toBeVisible(); + await expect(page.getByRole("button", { name: "Prove again" })).toBeVisible(); + await expect(page.getByRole("button", { name: "Back" })).toBeVisible(); +}); + +test("closing Google's window is named, and proving can start again", async ({ page }) => { + const relay = relayFor(); + await connect(page, relay, "closed"); + await prove(page); + await expect(heading(page, "You closed the Google window")).toBeVisible(); + expect(relay.posts).toEqual([]); + await page.evaluate(() => (window.__gis.mode = "ok")); + await prove(page); + await expect(page.getByRole("button", { name: "Accept 90.00 USDC" })).toBeVisible(); +}); + +test("a blocked Google window is named as blocked, not closed", async ({ page }) => { + await connect(page, relayFor(), "blocked"); + await prove(page); + await expect(heading(page, "Your browser blocked the Google window")).toBeVisible(); +}); + +test("a relay whose queue is full says Forepay is busy", async ({ page }) => { + const relay = relayFor(); + relay.post = { status: 503, body: { error: "the prover is busy", code: "busy" } }; + await connect(page, relay, "ok"); + await prove(page); + await expect(heading(page, "Forepay is busy right now")).toBeVisible(); +}); + +test("a proof already running from a tab that lost it says to wait for it, not to pick it up", async ({ page }) => { + const relay = relayFor(); + relay.post = { status: 409, body: { error: "a proof for this borrower is already running", code: "running" } }; + await connect(page, relay, "ok"); + await prove(page); + await expect(heading(page, "Your proof is already being made")).toBeVisible(); + await expect(page.getByText("Wait a few minutes for it to end, then prove again.", { exact: false })).toBeVisible(); +}); + +test("leaving while the relay proves and coming back waits on the same job, with no second sign-in", async ({ page }) => { + const relay = relayFor(); + relay.hold = true; + await connect(page, relay, "ok"); + await prove(page); + await expect(heading(page, "Reading your revenue")).toBeVisible(); + // The top nav on desktop, the tab bar on a phone: whichever is shown. + await page.getByRole("link", { name: "History", exact: true }).filter({ visible: true }).click(); + await expect(page).toHaveURL(/\/history$/); + relay.hold = false; + await page.getByRole("link", { name: "Advance", exact: true }).filter({ visible: true }).click(); + await expect(page.getByRole("button", { name: "Accept 90.00 USDC" })).toBeVisible(); + expect(relay.posts).toHaveLength(1); + expect(await opened(page)).toBe(1); +}); + +test("a kept job the relay no longer has gets its own panel, and opens Google's window only from a press", async ({ page }) => { + await page.addInitScript((borrower) => { + if (window.location.pathname === "/start") { + window.sessionStorage.setItem("forepay.proof.job", JSON.stringify({ borrower, id: "old" })); + } + }, E2E_ADDRESS); + const relay = relayFor(); + await connect(page, relay, "ok"); + await expect(heading(page, "Your earlier proof is gone")).toBeVisible(); + expect(await opened(page)).toBe(0); + expect(relay.posts).toEqual([]); + await proveAgain(page); + await expect(page.getByRole("button", { name: "Accept 90.00 USDC" })).toBeVisible(); + expect(await opened(page)).toBe(1); +}); + +for (const { what, code, title } of [ + { what: "Google refusing the token", code: "token", title: "Google did not let us read AdSense" }, + { what: "a proof that failed on the relay", code: "prove", title: "We could not finish your proof" }, +]) { + test(`${what} is named, and Prove again starts over`, async ({ page }) => { + const relay = relayFor({ j1: [{ id: "j1", stage: "failed", error: { code, message: "x" } }] }); + await connect(page, relay, "ok"); + await prove(page); + await expect(heading(page, title)).toBeVisible(); + relay.jobs.j1 = [done("j1")]; + await proveAgain(page); + await expect(page.getByRole("button", { name: "Accept 90.00 USDC" })).toBeVisible(); + }); +} + +test("a relay that does not answer is named as Forepay, not Stellar", async ({ page }) => { + await connect(page, relayFor(), "ok"); + await page.route("https://relay.e2e.invalid/proofs", (route) => route.abort("connectionrefused")); + await prove(page); + await expect(heading(page, "We could not reach Forepay")).toBeVisible(); +}); + +test("Google's script loads while 2a is open, before any press", async ({ page }) => { + let loads = 0; + await page.route("https://accounts.google.com/gsi/client", (route) => { + loads++; + return route.fulfill({ contentType: "text/javascript", body: "window.google = { accounts: { oauth2: { initTokenClient: () => ({ requestAccessToken() {} }) } } };" }); + }); + await connect(page, relayFor(), null); + await expect(page.getByRole("button", { name: "Prove my revenue" })).toBeVisible(); + await expect.poll(() => loads).toBe(1); + await prove(page); + await expect(heading(page, "Sign in with Google in the new window")).toBeVisible(); + expect(loads).toBe(1); +}); + +test("Google's script failing to load is named, not taken for a closed window", async ({ page }) => { + await page.route("https://accounts.google.com/gsi/client", (route) => route.abort("connectionrefused")); + await connect(page, relayFor(), null); + await prove(page); + await expect(heading(page, "Google sign-in did not load")).toBeVisible(); +}); + +test("coming back with a proof still running shows it at once, never 2a's button", async ({ page }) => { + const relay = relayFor(); + relay.hold = true; + await connect(page, relay, "ok"); + await prove(page); + await expect(heading(page, "Reading your revenue")).toBeVisible(); + await page.getByRole("link", { name: "History", exact: true }).filter({ visible: true }).click(); + await expect(page).toHaveURL(/\/history$/); + // Watch every change to the page from here on: 2a's button must never be put on it. + await page.evaluate(() => { + const w = window as unknown as { __sawProve: boolean }; + w.__sawProve = false; + new MutationObserver(() => { + if ([...document.querySelectorAll("button")].some((b) => b.textContent === "Prove my revenue")) w.__sawProve = true; + }).observe(document.body, { childList: true, subtree: true }); + }); + await page.getByRole("link", { name: "Advance", exact: true }).filter({ visible: true }).click(); + await expect(heading(page, "Reading your revenue")).toBeVisible(); + expect(await page.evaluate(() => (window as unknown as { __sawProve: boolean }).__sawProve)).toBe(false); +}); + +test("Back after a poll that failed waits on the same job, never a spinner with nothing behind it", async ({ page }) => { + const relay = relayFor(); + await connect(page, relay, "ok"); + await page.route("https://relay.e2e.invalid/proofs/j1", (route) => route.abort("connectionrefused")); + await prove(page); + await expect(heading(page, "We could not reach Forepay")).toBeVisible(); + await page.unroute("https://relay.e2e.invalid/proofs/j1"); + await page.getByRole("button", { name: "Back" }).click(); + await expect(page.getByRole("button", { name: "Accept 90.00 USDC" })).toBeVisible(); + expect(relay.posts).toHaveLength(1); + expect(await opened(page)).toBe(1); +}); + +test("Back after a kept job the relay no longer has returns to 2a", async ({ page }) => { + await page.addInitScript((borrower) => { + if (window.location.pathname === "/start") { + window.sessionStorage.setItem("forepay.proof.job", JSON.stringify({ borrower, id: "old" })); + } + }, E2E_ADDRESS); + await connect(page, relayFor(), "ok"); + await expect(heading(page, "Your earlier proof is gone")).toBeVisible(); + await page.getByRole("button", { name: "Back" }).click(); + await expect(page.getByRole("button", { name: "Prove my revenue" })).toBeVisible(); + expect(await opened(page)).toBe(0); +}); diff --git a/fe/tsconfig.json b/fe/tsconfig.json index 86a7b93..38c3de8 100644 --- a/fe/tsconfig.json +++ b/fe/tsconfig.json @@ -36,7 +36,9 @@ ".next/dev/types/**/*.ts", "**/*.mts", ".next-e2e/types/**/*.ts", - ".next-e2e/dev/types/**/*.ts" + ".next-e2e/dev/types/**/*.ts", + ".next-e2e-relay/types/**/*.ts", + ".next-e2e-relay/dev/types/**/*.ts" ], "exclude": [ "node_modules"