From 4f3771b911f45000976097a3660437755074ae95 Mon Sep 17 00:00:00 2001 From: lin1er Date: Mon, 26 Oct 2026 21:57:04 +0700 Subject: [PATCH 1/4] feat(#95): an AdMob provider beside AdSense, selected by source on POST /proofs be/src/admob/ proves the trailing AdMob revenue the way be/src/adsense/ proves AdSense's: a POST to networkReport:generate whose JSON body carries the window (signed byte for byte, #93), with regexes written against the bytes #93 read from a real account, including the \n,\r\n separator. - The figure is extracted as revenueMicros, an integer; the contract truncates it to cents (#94). At zero AdMob sends no row, and the relay stops with provider before the attestor. - The AdSense audit takes a ClaimShape, so both sources share one allow-list, credential scan and signature check. AdSense's behaviour and its request JSON are unchanged. - POST /proofs takes source: "adsense" | "admob", defaulting to adsense. - prove:admob produces one real proof, with the token passed inline, as the input to the AdMob template (#96). - A test pins the signed value order for AdMob, dates before pub_id, which is what the contract has to rebuild (#94). docs/admob-provider.md and docs/api.md describe it. 117 BE tests pass. --- be/.env.example | 6 ++ be/package.json | 1 + be/src/admob/account.ts | 88 ++++++++++++++++++++++ be/src/admob/audit.test.ts | 68 +++++++++++++++++ be/src/admob/audit.ts | 56 ++++++++++++++ be/src/admob/request.test.ts | 93 ++++++++++++++++++++++++ be/src/admob/request.ts | 137 +++++++++++++++++++++++++++++++++++ be/src/adsense/audit.ts | 104 ++++++++++++++++---------- be/src/api/app.test.ts | 19 +++++ be/src/api/app.ts | 17 +++-- be/src/api/server.ts | 2 + be/src/cli/prove-adsense.ts | 30 +++++--- be/src/relay/fake-reclaim.ts | 43 ++++++++++- be/src/relay/prove.test.ts | 38 +++++++++- be/src/relay/prove.ts | 52 ++++++++++--- docs/admob-provider.md | 99 +++++++++++++++++++++++++ docs/api.md | 17 ++++- 17 files changed, 798 insertions(+), 72 deletions(-) create mode 100644 be/src/admob/account.ts create mode 100644 be/src/admob/audit.test.ts create mode 100644 be/src/admob/audit.ts create mode 100644 be/src/admob/request.test.ts create mode 100644 be/src/admob/request.ts create mode 100644 docs/admob-provider.md diff --git a/be/.env.example b/be/.env.example index 563cc1a..7506b7b 100644 --- a/be/.env.example +++ b/be/.env.example @@ -12,6 +12,9 @@ RECLAIM_APP_SECRET= # for the Google account that owns the AdSense account. Expires after about an hour. # Quickest way: OAuth 2.0 Playground (https://developers.google.com/oauthplayground), # step 1 pick "AdSense Management API v2" → adsense.readonly, authorize, exchange for tokens. +# For `prove:admob` (#95) the scope is https://www.googleapis.com/auth/admob.readonly +# instead. A token set in the environment wins over this file, so for someone else's +# account pass it inline and leave this empty: GOOGLE_ACCESS_TOKEN="$(wl-paste)" … GOOGLE_ACCESS_TOKEN= # The borrower's Stellar testnet account (G…). Public; bound into the signed claim. @@ -24,6 +27,9 @@ STELLAR_SECRET_KEY= # Optional. If empty, the script uses the only AdSense account the token can read. ADSENSE_PUBLISHER_ID= +# Optional, for prove:admob. If empty, the only AdMob account the token can read. +ADMOB_PUBLISHER_ID= + # Optional. Complete calendar months to prove. Default 3. TRAILING_MONTHS= diff --git a/be/package.json b/be/package.json index ec3b45d..c54c112 100644 --- a/be/package.json +++ b/be/package.json @@ -8,6 +8,7 @@ "typecheck": "tsc --noEmit", "test": "tsx --test \"src/**/*.test.ts\"", "prove:adsense": "tsx src/cli/prove-adsense.ts", + "prove:admob": "tsx src/cli/prove-adsense.ts --admob", "prove:smoke": "tsx src/cli/prove-smoke.ts", "zk:files": "tsx src/cli/zk-files.ts", "verify:proof": "tsx src/cli/verify-proof.ts", diff --git a/be/src/admob/account.ts b/be/src/admob/account.ts new file mode 100644 index 0000000..e337edd --- /dev/null +++ b/be/src/admob/account.ts @@ -0,0 +1,88 @@ +/** + * The checks that run before an AdMob proof is attempted (#95): which AdMob account the + * token reads, and whether the live report has the shape the provider's regexes expect. + * The sibling of `../adsense/account.ts`, with the same `ProveError` codes. + * + * There is no READY check: an AdMob account has no approval state in the API. An + * account with no revenue in the window is found by the live check instead, because + * Google then sends no `row` (#93). + */ +import { ProveError } from "../adsense/account.js"; +import { assertPublisherId } from "../adsense/request.js"; +import { ADMOB_API, ADMOB_SCOPE, type AdmobRequest } from "./request.js"; + +/** One AdMob API call. Returns the response text unparsed: the regexes run on raw bytes. */ +export type AdmobFetch = (url: string, accessToken: string, body?: string) => Promise; + +/** GET, or POST a JSON body, with the token. Errors never carry the token. */ +export const admobFetch: AdmobFetch = async (url, accessToken, body) => { + const res = await fetch(url, { + method: body === undefined ? "GET" : "POST", + headers: { + Authorization: `Bearer ${accessToken}`, + accept: "application/json", + ...(body === undefined ? {} : { "content-type": "application/json" }), + }, + body, + signal: AbortSignal.timeout(15_000), + }); + const text = await res.text(); + if (res.ok) return text; + if (res.status === 401) { + throw new ProveError("token", `Google refused the access token (401). It is missing, expired (they last an hour) or lacks ${ADMOB_SCOPE}.`); + } + if (res.status === 403) { + throw new ProveError( + "account", + `Google answered 403 for ${url}: the token lacks ${ADMOB_SCOPE}, the account has no AdMob access, or the AdMob API is not enabled for the OAuth client.`, + ); + } + throw new ProveError("prove", `AdMob API returned ${res.status} for ${url}: ${text.slice(0, 300)}`); +}; + +/** The configured publisher id, or the only AdMob account the token can read. */ +export async function resolveAdmobPublisherId(fetchAdmob: AdmobFetch, accessToken: string, configured = ""): Promise { + if (configured) { + assertPublisherId(configured); + return configured; + } + const body = JSON.parse(await fetchAdmob(`${ADMOB_API}/accounts`, accessToken)) as { account?: { publisherId: string }[] }; + const ids = (body.account ?? []).map((a) => a.publisherId); + if (ids.length === 1) return ids[0]; + throw new ProveError( + "account", + ids.length === 0 + ? "This Google account has no AdMob account." + : `This Google account can read ${ids.length} AdMob accounts (${ids.join(", ")}); choose one.`, + ); +} + +/** + * Run the provider's regexes against the live report, on the raw response text, which + * is what the attestor sees. Unlike AdSense, nothing is re-serialised first: AdMob's + * separators carry a `\r` (#93) that a JSON round trip would lose. + */ +export async function checkLiveReport(fetchAdmob: AdmobFetch, accessToken: string, request: AdmobRequest): Promise { + const raw = await fetchAdmob(request.url, accessToken, request.options.body); + for (const m of request.secretOptions.responseMatches) { + if (new RegExp(m.value).test(raw)) continue; + const zero = !raw.includes('"row"'); + throw new ProveError( + "provider", + zero + ? "AdMob reports no earnings for this window: the report has no row, which is how AdMob says zero." + : `the live AdMob response does not match ${m.value}\nResponse keys: ${elementKeys(raw)}`, + ); + } +} + +/** The top-level key of each element of the streamed array, never a value. */ +function elementKeys(raw: string): string { + try { + const parsed = JSON.parse(raw) as unknown; + if (Array.isArray(parsed)) return parsed.map((e) => Object.keys(e as object).join("+")).join(", "); + } catch { + // fall through + } + return "not a JSON array"; +} diff --git a/be/src/admob/audit.test.ts b/be/src/admob/audit.test.ts new file mode 100644 index 0000000..6814ff8 --- /dev/null +++ b/be/src/admob/audit.test.ts @@ -0,0 +1,68 @@ +/** + * Forepay #95: an AdMob claim passes the same audit as an AdSense one, with its own + * shape, and a claim from the other product, or for another window, does not. + */ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { AuditError, auditRevenueProof, type RevenueProof } from "../adsense/audit.js"; +import { buildRevenueRequest, withAccessToken as withAdsenseToken } from "../adsense/request.js"; +import { ALICE, ATTESTOR, NOW, PUB, Q3, TOKEN, fakeZkFetch, type FakeZk } from "../relay/fake-reclaim.js"; +import { admobExpectationsFromClaim, auditAdmobProof } from "./audit.js"; +import { buildAdmobRequest, withAccessToken } from "./request.js"; + +const expectations = { publisherId: PUB, stellarAddress: ALICE, window: Q3, accessToken: TOKEN, now: NOW, attestor: ATTESTOR }; +const MICROS = { extracted: { revenueMicros: "12345678" } }; + +async function admobProof(o: FakeZk = MICROS, window = Q3): Promise { + const call = withAccessToken(buildAdmobRequest({ publisherId: PUB, stellarAddress: ALICE, window }), TOKEN); + return (await fakeZkFetch(o)(call.url, call.options, call.secretOptions)) as RevenueProof; +} + +function failuresOf(fn: () => unknown): string[] { + try { + fn(); + } catch (e) { + if (e instanceof AuditError) return e.failures; + throw e; + } + return []; +} + +test("a well-formed AdMob claim passes, with the figure in micros and in USD", async () => { + const result = auditAdmobProof(await admobProof(), expectations); + assert.deepEqual(result.figure, { name: "revenueMicros", value: "12345678" }); + assert.equal(result.revenueUsd, "12.345678"); + const fields = result.fields.map((f) => f.field); + for (const f of ["parameters.url", "parameters.method", "parameters.body", "parameters.headers.content-type", "context.extractedParameters.revenueMicros", "signature"]) { + assert.ok(fields.includes(f), `report is missing ${f}`); + } +}); + +test("a claim for another window is refused: the body is the window", async () => { + const june = { start: { year: 2026, month: 4, day: 1 }, end: { year: 2026, month: 6, day: 30 } }; + const proof = await admobProof(MICROS, june); + assert.ok(failuresOf(() => auditAdmobProof(proof, expectations)).some((f) => f.startsWith("parameters.body"))); +}); + +test("the figure must be revenueMicros, an integer", async () => { + const decimal = await admobProof({ extracted: { revenueMicros: "12.34" } }); + assert.ok(failuresOf(() => auditAdmobProof(decimal, expectations)).some((f) => f.includes("extractedParameters"))); + const usd = await admobProof({ extracted: { revenueUsd: "12.34" } }); + assert.ok(failuresOf(() => auditAdmobProof(usd, expectations)).some((f) => f.includes("extractedParameters"))); +}); + +test("an AdSense claim does not pass as AdMob, nor the reverse", async () => { + const adsenseCall = withAdsenseToken(buildRevenueRequest({ publisherId: PUB, stellarAddress: ALICE, window: Q3 }), TOKEN); + const adsense = (await fakeZkFetch()(adsenseCall.url, adsenseCall.options, adsenseCall.secretOptions)) as RevenueProof; + assert.ok(failuresOf(() => auditAdmobProof(adsense, expectations)).some((f) => f.startsWith("parameters.url"))); + const admob = await admobProof(); + assert.ok(failuresOf(() => auditRevenueProof(admob, expectations)).some((f) => f.startsWith("parameters.url"))); +}); + +test("the publisher id, window and borrower read back from an AdMob claim", async () => { + assert.deepEqual(admobExpectationsFromClaim(await admobProof()), { publisherId: PUB, window: Q3, stellarAddress: ALICE }); + const adsenseCall = withAdsenseToken(buildRevenueRequest({ publisherId: PUB, stellarAddress: ALICE, window: Q3 }), TOKEN); + const adsense = (await fakeZkFetch()(adsenseCall.url, adsenseCall.options, adsenseCall.secretOptions)) as RevenueProof; + assert.equal(admobExpectationsFromClaim(adsense), null); +}); diff --git a/be/src/admob/audit.ts b/be/src/admob/audit.ts new file mode 100644 index 0000000..d9f0526 --- /dev/null +++ b/be/src/admob/audit.ts @@ -0,0 +1,56 @@ +/** + * Field-by-field audit of an AdMob revenue claim (#95). The audit itself is AdSense's + * (`../adsense/audit.ts`): the same allow-list, the same credential scan, the same + * signature check. This file only states what an AdMob claim must look like. + */ +import { PUBLIC_HEADERS, auditRevenueProof, type AuditExpectations, type AuditResult, type ClaimShape, type RevenueProof } from "../adsense/audit.js"; +import type { RevenueWindow } from "../adsense/request.js"; +import { FIGURE, buildAdmobRequest, microsToUsd } from "./request.js"; + +/** `content-type` is public here: the POST needs it, and it says only that the body is JSON. */ +const ADMOB_PUBLIC_HEADERS: ReadonlySet = new Set([...PUBLIC_HEADERS, "content-type"]); + +const ADMOB_URL = /^https:\/\/admob\.googleapis\.com\/v1\/accounts\/(pub-\d{16})\/networkReport:generate$/; + +export function admobShape(expect: Pick): ClaimShape { + const req = buildAdmobRequest(expect); + return { + url: req.url, + urlWhy: "Host and publisher id. The publisher id is public (it is in every app's ad unit ids) and cannot authenticate anyone.", + method: "POST", + body: req.options.body, + bodyWhy: "The report spec: the window, one metric, USD. Signed, so the window cannot be swapped (#93).", + responseMatches: req.secretOptions.responseMatches, + responseRedactions: req.secretOptions.responseRedactions, + matchesWhy: "What the response had to contain: USD and one total row; the window is fixed by the body. Patterns only, no response data.", + publicHeaders: ADMOB_PUBLIC_HEADERS, + figure: { + name: FIGURE, + format: /^\d+$/, + why: "The figure being proven: estimated earnings over the window, in millionths of a USD. Disclosed on purpose.", + toUsd: microsToUsd, + }, + }; +} + +export function auditAdmobProof(proof: RevenueProof, expect: AuditExpectations): AuditResult { + return auditRevenueProof(proof, expect, admobShape(expect)); +} + +/** Publisher id, window and borrower as written in an AdMob claim, or null if it is not one. */ +export function admobExpectationsFromClaim(proof: RevenueProof) { + const params = JSON.parse(proof.claimData.parameters) as { url?: string; body?: string }; + const m = ADMOB_URL.exec(String(params.url ?? "")); + if (!m) return null; + let spec: { reportSpec?: { dateRange?: { startDate?: unknown; endDate?: unknown } } }; + try { + spec = JSON.parse(String(params.body ?? "")); + } catch { + return null; + } + const range = spec.reportSpec?.dateRange; + if (!range?.startDate || !range.endDate) return null; + const window = { start: range.startDate, end: range.endDate } as RevenueWindow; + const context = JSON.parse(proof.claimData.context) as { contextAddress?: string }; + return { publisherId: m[1], window, stellarAddress: String(context.contextAddress ?? "") }; +} diff --git a/be/src/admob/request.test.ts b/be/src/admob/request.test.ts new file mode 100644 index 0000000..af2e050 --- /dev/null +++ b/be/src/admob/request.test.ts @@ -0,0 +1,93 @@ +/** + * Forepay #95: the AdMob request is deterministic, its regexes read the bytes #93 got + * from a real account, and the signed parameters carry the window before the publisher + * id, which is the order the contract has to rebuild them in (#94). + */ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { canonicalStringify } from "../reclaim/claim-digest.js"; +import { ALICE, PUB, Q3, admobReport } from "../relay/fake-reclaim.js"; +import { FIGURE, buildAdmobRequest, buildReportBody, buildReportUrl, microsToUsd, withAccessToken } from "./request.js"; + +function figureOf(raw: string): string | null { + const req = buildAdmobRequest({ publisherId: PUB, stellarAddress: ALICE, window: Q3 }); + let figure: string | null = null; + for (const m of req.secretOptions.responseMatches) { + const hit = new RegExp(m.value).exec(raw); + if (!hit) return null; + figure ??= hit.groups?.[FIGURE] ?? null; + } + return figure; +} + +test("the body is the window, one metric and USD, in fixed bytes", () => { + assert.equal( + buildReportBody(Q3), + '{"reportSpec":{"dateRange":{"startDate":{"year":2026,"month":7,"day":1},"endDate":{"year":2026,"month":9,"day":30}},' + + '"metrics":["ESTIMATED_EARNINGS"],"localizationSettings":{"currencyCode":"USD"}}}', + ); + // The body is valid JSON with no dimensions, so Google answers with one total row. + const spec = JSON.parse(buildReportBody(Q3)) as { reportSpec: Record }; + assert.deepEqual(Object.keys(spec.reportSpec), ["dateRange", "metrics", "localizationSettings"]); +}); + +test("the URL names the host and the account, nothing else", () => { + assert.equal(buildReportUrl(PUB), `https://admob.googleapis.com/v1/accounts/${PUB}/networkReport:generate`); + assert.throws(() => buildReportUrl("pub-123"), /publisher id/); +}); + +test("the regexes read the total from the bytes AdMob sends, \\r and all", () => { + const raw = admobReport(Q3, "12345678"); + assert.ok(raw.includes("}\n,\r\n{"), "the fixture keeps #93's separator"); + assert.equal(figureOf(raw), "12345678"); +}); + +test("at zero AdMob sends no row, and nothing matches", () => { + assert.equal(figureOf(admobReport(Q3)), null); +}); + +test("another currency, or a per-dimension row, does not match", () => { + assert.equal(figureOf(admobReport(Q3, "1000000").replace('"USD"', '"IDR"')), null); + const byMonth = admobReport(Q3, "1000000").replace('"row": {\n', '"row": {\n "dimensionValues": {"MONTH": {"value": "202609"}},\n'); + assert.equal(figureOf(byMonth), null); +}); + +test("the token goes into the secret headers only", () => { + const req = buildAdmobRequest({ publisherId: PUB, stellarAddress: ALICE, window: Q3 }); + const call = withAccessToken(req, "ya29.test-token"); + assert.deepEqual(call.secretOptions.headers, { Authorization: "Bearer ya29.test-token" }); + assert.ok(!JSON.stringify([call.url, call.options]).includes("ya29")); +}); + +test("in the signed parameters the six date numbers come before the publisher id (#94)", () => { + // The attestor canonicalises the parameters with sorted keys, so `body` precedes `url`. + // The contract interleaves its template with the values positionally: for AdMob the + // order is [sy, sm, sd, ey, em, ed, pub_id], the reverse of AdSense's. + const req = buildAdmobRequest({ publisherId: PUB, stellarAddress: ALICE, window: Q3 }); + const params = canonicalStringify({ + body: req.options.body, + headers: { "User-Agent": "reclaim/0.0.1", ...req.options.headers }, + method: "POST", + responseMatches: req.secretOptions.responseMatches, + responseRedactions: req.secretOptions.responseRedactions, + url: req.url, + }); + const at = (needle: string, from: number) => { + const i = params.indexOf(needle, from); + assert.ok(i >= 0, `${needle} after ${from}`); + return i + needle.length; + }; + let pos = 0; + for (const sep of ['{\\"year\\":2026', '\\"month\\":7', ',\\"day\\":1', '{\\"year\\":2026', '\\"month\\":9', ',\\"day\\":30', `/accounts/${PUB}`]) { + pos = at(sep, pos); + } +}); + +test("micros read as an exact USD decimal", () => { + assert.equal(microsToUsd("12345678"), "12.345678"); + assert.equal(microsToUsd("250000"), "0.25"); + assert.equal(microsToUsd("5000000"), "5"); + assert.equal(microsToUsd("0"), "0"); + assert.throws(() => microsToUsd("1.5"), /micros/); +}); diff --git a/be/src/admob/request.ts b/be/src/admob/request.ts new file mode 100644 index 0000000..0c5f38f --- /dev/null +++ b/be/src/admob/request.ts @@ -0,0 +1,137 @@ +/** + * The Forepay AdMob provider (#95): one zkFetch request that proves a creator's + * trailing AdMob revenue, in USD micros, and nothing else. The sibling of + * `../adsense/request.ts`; read that first, this only says what differs. + * + * What differs from AdSense, and why: + * + * - `POST …/networkReport:generate`, with the window in a JSON body, not the URL. + * #93 proved the attestor signs the body byte for byte: `parameters.body` is the + * string sent, and a different window recovers to a different signer. So the body + * fixes the window here the way the query string does for AdSense, and it must be + * the same bytes for the same inputs: `buildReportBody` writes it by hand, in a + * fixed key order, with no whitespace. + * - The figure is `microsValue`, an integer string of millionths of a dollar, so it + * is extracted as `revenueMicros`, not `revenueUsd`. The contract converts it to + * cents, truncating (#94). + * - The response is a pretty-printed JSON array, `[header, row, footer]`, whose + * elements are separated by `\n,\r\n` (#93, read from a real account). The regexes + * therefore stay inside one element each and never span a separator. + * - At zero there is no `row` at all, only `[header, footer {}]` (#93). The earnings + * regex then does not match, and the relay stops before the attestor, as it does + * for an AdSense response without `totals`. + * + * The AdMob and AdSense publisher ids share one format, and can be the same id for + * one creator (#93). Which product a claim is about is fixed by the host in the + * signed URL, never by the id. + * + * Regexes here are evaluated by the attestor, which uses RE2: no lookarounds, no + * backreferences. + */ +import { + CONTEXT_MESSAGE, + assertPublisherId, + assertStellarAccount, + type RevenueRequestInput, + type RevenueWindow, +} from "../adsense/request.js"; + +export const ADMOB_API = "https://admob.googleapis.com/v1"; + +/** Read-only AdMob scope. The token needs nothing broader. */ +export const ADMOB_SCOPE = "https://www.googleapis.com/auth/admob.readonly"; + +/** The name the figure is extracted under, inside the signed context. */ +export const FIGURE = "revenueMicros"; + +/** What `ReclaimClient.zkFetch(url, options, secretOptions)` takes, minus the token. */ +export interface AdmobRequest { + url: string; + options: { + method: "POST"; + body: string; + headers: Record; + context: { contextAddress: string; contextMessage: string }; + }; + secretOptions: { + responseMatches: { type: "regex"; value: string }[]; + responseRedactions: { regex: string }[]; + }; +} + +export function buildReportUrl(publisherId: string): string { + assertPublisherId(publisherId); + return `${ADMOB_API}/accounts/${publisherId}/networkReport:generate`; +} + +/** + * The exact body that goes into the signed claim: one metric, no dimensions, USD. + * + * No dimensions, so the response carries exactly one row, the window's total. With a + * dimension it would carry a row per value, and a total would have to be summed from + * rows that Google rounds separately (#93 saw a 1-micro difference). + */ +export function buildReportBody(window: RevenueWindow): string { + const date = (d: RevenueWindow["start"]) => `{"year":${d.year},"month":${d.month},"day":${d.day}}`; + return ( + `{"reportSpec":{"dateRange":{"startDate":${date(window.start)},"endDate":${date(window.end)}},` + + `"metrics":["ESTIMATED_EARNINGS"],"localizationSettings":{"currencyCode":"USD"}}}` + ); +} + +/** The header echoes the currency the report was computed in. */ +export const CURRENCY_REGEX = `"localizationSettings":\\s*\\{\\s*"currencyCode":\\s*"USD"\\s*\\}`; + +/** + * `"row": { "metricValues": { "ESTIMATED_EARNINGS": { "microsValue": "12345678" } } }`, + * capturing the figure. A row that opens with `metricValues` has no `dimensionValues`, + * so this cannot match a per-dimension row of some other report. + */ +export const EARNINGS_REGEX = `"row":\\s*\\{\\s*"metricValues":\\s*\\{\\s*"ESTIMATED_EARNINGS":\\s*\\{\\s*"microsValue":\\s*"(?<${FIGURE}>\\d+)"\\s*\\}\\s*\\}\\s*\\}`; + +export function buildAdmobRequest(input: RevenueRequestInput): AdmobRequest { + assertStellarAccount(input.stellarAddress); + const url = buildReportUrl(input.publisherId); + + // As for AdSense, each redaction reveals exactly the span its match needs: the + // currency and the one total, not the account, the window echo or the footer. + const reveal = [CURRENCY_REGEX, EARNINGS_REGEX]; + return { + url, + options: { + method: "POST", + body: buildReportBody(input.window), + headers: { accept: "application/json", "content-type": "application/json" }, + context: { contextAddress: input.stellarAddress, contextMessage: CONTEXT_MESSAGE }, + }, + secretOptions: { + responseMatches: reveal.map((value) => ({ type: "regex", value })), + responseRedactions: reveal.map((regex) => ({ regex })), + }, + }; +} + +/** The token goes into the secret headers only, exactly as for AdSense. */ +export function withAccessToken(request: AdmobRequest, accessToken: string) { + if (!accessToken) throw new Error("an OAuth access token is required"); + return { + url: request.url, + options: request.options, + secretOptions: { + ...request.secretOptions, + headers: { Authorization: `Bearer ${accessToken}` }, + }, + }; +} + +/** + * Micros as an exact USD decimal, for display: `"12345678"` → `"12.345678"`. Exact, + * not rounded; sizing truncates to cents on chain (#94), not here. + */ +export function microsToUsd(micros: string): string { + if (!/^\d+$/.test(micros)) throw new Error(`not a micros value: ${micros}`); + const padded = micros.padStart(7, "0"); + const frac = padded.slice(-6).replace(/0+$/, ""); + const whole = padded.slice(0, -6).replace(/^0+(?=\d)/, ""); + return frac ? `${whole}.${frac}` : whole; +} diff --git a/be/src/adsense/audit.ts b/be/src/adsense/audit.ts index 05bd871..633f80b 100644 --- a/be/src/adsense/audit.ts +++ b/be/src/adsense/audit.ts @@ -99,7 +99,10 @@ export interface FieldReport { } export interface AuditResult { + /** The figure in USD, as a decimal. For AdSense it is the extracted figure itself. */ revenueUsd: string; + /** The extracted parameter exactly as signed: what the contract rebuilds the context from. */ + figure: { name: string; value: string }; timestampS: number; signer: string; fields: FieldReport[]; @@ -125,7 +128,7 @@ const PARAMETER_KEYS = new Set([ ]); /** Request headers allowed in the public parameters (compared lowercased). */ -const PUBLIC_HEADERS = new Set(["accept", "user-agent"]); +export const PUBLIC_HEADERS: ReadonlySet = new Set(["accept", "user-agent"]); const CONTEXT_KEYS = ["contextAddress", "contextMessage", "extractedParameters", "providerHash"]; @@ -145,13 +148,56 @@ const CREDENTIAL_PATTERNS: [string, RegExp][] = [ const DECIMAL = /^\d+(?:\.\d+)?$/; +/** + * What a claim from one provider must look like, field by field. The audit is the + * same for every source; only these differ (#95). + */ +export interface ClaimShape { + url: string; + urlWhy: string; + method: "GET" | "POST"; + /** `""` for a GET. For a POST, the exact body: it carries the window (#93). */ + body: string; + bodyWhy: string; + responseMatches: { type: string; value: string }[]; + responseRedactions: { regex: string }[]; + matchesWhy: string; + /** Request headers allowed in the public parameters, lowercased. */ + publicHeaders: ReadonlySet; + /** The one extracted parameter, its format, and how to read it as USD. */ + figure: { name: string; format: RegExp; why: string; toUsd: (v: string) => string }; +} + +/** The AdSense claim shape (#4): a GET whose URL carries the account and the window. */ +export function adsenseShape(expect: Pick): ClaimShape { + const req = buildRevenueRequest(expect); + return { + url: req.url, + urlWhy: + "Host, publisher id and window. The publisher id is public (it appears in the ad code on every page that shows AdSense ads) and cannot authenticate anyone.", + method: "GET", + body: "", + bodyWhy: "Empty: the report endpoint takes no body.", + responseMatches: req.secretOptions.responseMatches, + responseRedactions: req.secretOptions.responseRedactions, + matchesWhy: "What the response had to contain: USD and a total; the window is fixed by the URL. Patterns only, no response data.", + publicHeaders: PUBLIC_HEADERS, + figure: { + name: "revenueUsd", + format: DECIMAL, + why: "The figure being proven: estimated earnings in USD over the window. Disclosed on purpose.", + toUsd: (v) => v, + }, + }; +} + export function recoverSigner(messageDigest: Uint8Array, sig64: Uint8Array, recoveryId: number) { const sig = secp256k1.Signature.fromCompact(sig64).addRecoveryBit(recoveryId); const pub = sig.recoverPublicKey(messageDigest).toRawBytes(false); return `0x${Buffer.from(keccak_256(pub.subarray(1))).subarray(12).toString("hex")}`; } -export function auditRevenueProof(proof: RevenueProof, expect: AuditExpectations): AuditResult { +export function auditRevenueProof(proof: RevenueProof, expect: AuditExpectations, shape: ClaimShape = adsenseShape(expect)): AuditResult { const failures: string[] = []; const fields: FieldReport[] = []; const fail = (msg: string) => failures.push(msg); @@ -159,11 +205,6 @@ export function auditRevenueProof(proof: RevenueProof, expect: AuditExpectations const claim = proof.claimData; const now = expect.now ?? new Date(); - const expected = buildRevenueRequest({ - publisherId: expect.publisherId, - stellarAddress: expect.stellarAddress, - window: expect.window, - }); // 1. Nothing credential-shaped, anywhere in the proof. const whole = JSON.stringify(proof); @@ -190,26 +231,22 @@ export function auditRevenueProof(proof: RevenueProof, expect: AuditExpectations if (!PARAMETER_KEYS.has(key)) fail(`parameters carries an unexpected key: ${key}`); } - if (params.url === expected.url) { - ok( - "parameters.url", - String(params.url), - "Host, publisher id and window. The publisher id is public (it appears in the ad code on every page that shows AdSense ads) and cannot authenticate anyone.", - ); + if (params.url === shape.url) { + ok("parameters.url", String(params.url), shape.urlWhy); } else { - fail(`parameters.url is ${JSON.stringify(params.url)}, expected ${expected.url}`); + fail(`parameters.url is ${JSON.stringify(params.url)}, expected ${shape.url}`); } - if (params.method === "GET") ok("parameters.method", "GET", "A constant."); - else fail(`parameters.method is ${JSON.stringify(params.method)}, expected GET`); + if (params.method === shape.method) ok("parameters.method", shape.method, "A constant."); + else fail(`parameters.method is ${JSON.stringify(params.method)}, expected ${shape.method}`); - if (params.body === undefined || params.body === "") { - ok("parameters.body", '""', "Empty: the report endpoint takes no body."); - } else fail("parameters.body is not empty"); + if ((params.body ?? "") === shape.body) { + ok("parameters.body", shape.body === "" ? '""' : shape.body, shape.bodyWhy); + } else fail(shape.body === "" ? "parameters.body is not empty" : `parameters.body is ${JSON.stringify(params.body)}, expected ${shape.body}`); const headers = (params.headers ?? {}) as Record; for (const [name, value] of Object.entries(headers)) { - if (PUBLIC_HEADERS.has(name.toLowerCase())) { + if (shape.publicHeaders.has(name.toLowerCase())) { ok( `parameters.headers.${name}`, String(value), @@ -230,7 +267,7 @@ export function auditRevenueProof(proof: RevenueProof, expect: AuditExpectations } else fail(`parameters.paramValues is not empty: ${Object.keys(paramValues).join(", ")}`); const matches = (params.responseMatches ?? []) as { type?: string; value?: string }[]; - const expectedMatches = expected.secretOptions.responseMatches; + const expectedMatches = shape.responseMatches; if ( matches.length === expectedMatches.length && matches.every( @@ -240,15 +277,11 @@ export function auditRevenueProof(proof: RevenueProof, expect: AuditExpectations m.value === expectedMatches[i].value, ) ) { - ok( - "parameters.responseMatches", - `${matches.length} regexes`, - "What the response had to contain: USD and a total; the window is fixed by the URL. Patterns only, no response data.", - ); + ok("parameters.responseMatches", `${matches.length} regexes`, shape.matchesWhy); } else fail("parameters.responseMatches differ from the provider's"); const redactions = (params.responseRedactions ?? []) as Record[]; - const expectedRedactions = expected.secretOptions.responseRedactions; + const expectedRedactions = shape.responseRedactions; if ( redactions.length === expectedRedactions.length && redactions.every( @@ -290,15 +323,12 @@ export function auditRevenueProof(proof: RevenueProof, expect: AuditExpectations const extracted = (context.extractedParameters ?? {}) as Record; const extractedKeys = Object.keys(extracted); - let revenueUsd = ""; - if (extractedKeys.length === 1 && extractedKeys[0] === "revenueUsd" && DECIMAL.test(String(extracted.revenueUsd))) { - revenueUsd = String(extracted.revenueUsd); - ok( - "context.extractedParameters.revenueUsd", - revenueUsd, - "The figure being proven: estimated earnings in USD over the window. Disclosed on purpose.", - ); - } else fail(`context.extractedParameters must be exactly { revenueUsd: }, got ${JSON.stringify(extracted)}`); + const { name } = shape.figure; + let figure = ""; + if (extractedKeys.length === 1 && extractedKeys[0] === name && shape.figure.format.test(String(extracted[name]))) { + figure = String(extracted[name]); + ok(`context.extractedParameters.${name}`, figure, shape.figure.why); + } else fail(`context.extractedParameters must be exactly { ${name}: <${shape.figure.format.source}> }, got ${JSON.stringify(extracted)}`); if (typeof context.providerHash === "string" && /^0x[0-9a-f]{64}$/.test(context.providerHash)) { ok("context.providerHash", context.providerHash, "Hash of the provider configuration. Derived from public parameters."); @@ -348,7 +378,7 @@ export function auditRevenueProof(proof: RevenueProof, expect: AuditExpectations if (proof.identifier !== claim.identifier) fail("top-level identifier differs from claimData.identifier"); if (failures.length > 0) throw new AuditError(failures); - return { revenueUsd, timestampS: claim.timestampS, signer, fields }; + return { revenueUsd: shape.figure.toUsd(figure), figure: { name, value: figure }, timestampS: claim.timestampS, signer, fields }; } /** The audit as a Markdown table, for the comment on #4. */ diff --git a/be/src/api/app.test.ts b/be/src/api/app.test.ts index 09f3ff5..af6cf5c 100644 --- a/be/src/api/app.test.ts +++ b/be/src/api/app.test.ts @@ -325,6 +325,7 @@ test("POST /proofs refuses what is not a proof request", async () => { [{ borrower: BORROWER, accessToken: "" }, 400], [{ borrower: BORROWER, accessToken: "x" }, 400], [{ borrower: BORROWER, accessToken: TOKEN, publisherId: "pub-1" }, 400], + [{ borrower: BORROWER, accessToken: TOKEN, source: "youtube" }, 400], [{ borrower: BORROWER, accessToken: "x".repeat(9000) }, 413], ]; for (const [body, status] of cases) { @@ -333,6 +334,24 @@ test("POST /proofs refuses what is not a proof request", async () => { } }); +test("source admob reaches the prover; adsense or none leaves the input as before", async () => { + const seen: unknown[] = []; + const api = relayApp(async (input) => { + seen.push(input); + return REQUEST; + }); + for (const extra of [{ source: "admob" }, { source: "adsense" }, {}]) { + const borrower = BORROWER; + const res = await api.request(post({ borrower, accessToken: TOKEN, ...extra })); + assert.equal(res.status, 202); + await finished(api, ((await res.json()) as { id: string }).id); + } + assert.deepEqual( + seen.map((i) => (i as { source?: string }).source), + ["admob", undefined, undefined], + ); +}); + test("a second proof for the same borrower while one runs is 409 running, without the running job's id", async () => { let release!: () => void; const api = relayApp( diff --git a/be/src/api/app.ts b/be/src/api/app.ts index 65f51bc..77d31b8 100644 --- a/be/src/api/app.ts +++ b/be/src/api/app.ts @@ -9,8 +9,9 @@ * the contract's current record of each (principal, repaid, window). * GET /transactions?borrower=G… advances, repayments and the USDC trustline, * newest first, failed ones included. - * POST /proofs the relay (#17): prove the creator's AdSense revenue, bound to their - * `G…`. Answers 202 with a job id at once; proving takes minutes. + * POST /proofs the relay (#17): prove the creator's AdSense revenue (or AdMob's, with + * `source: "admob"`, #95), bound to their `G…`. Answers 202 with a job + * id at once; proving takes minutes. * GET /proofs/:id the job's stage, then `request_advance`'s arguments or an error. * * Amounts are stroops and times are seconds, both as decimal strings: JSON numbers @@ -168,27 +169,31 @@ export function createApp({ loaded, rpc, chain, prover, jobs = new ProofJobs(), async (c) => { c.header("Cache-Control", "no-store"); if (!prover) return c.json({ error: "the proof relay is not configured on this server", code: "unconfigured" }, 503); - let body: { borrower?: unknown; accessToken?: unknown; publisherId?: unknown }; + let body: { borrower?: unknown; accessToken?: unknown; publisherId?: unknown; source?: unknown }; try { body = await c.req.json(); } catch { return c.json({ error: "expected a JSON body" }, 400); } - const { borrower, accessToken, publisherId } = body ?? {}; + const { borrower, accessToken, publisherId, source } = body ?? {}; if (typeof borrower !== "string" || !StrKey.isValidEd25519PublicKey(borrower)) { return c.json({ error: "borrower must be a Stellar account address (G…)" }, 400); } // Google's tokens run to hundreds of characters. A short string is not one, and scrubbing it out // of error messages would cut every word it appears in. if (typeof accessToken !== "string" || accessToken.length < 16 || accessToken.length > 4096) { - return c.json({ error: "accessToken must be a Google OAuth access token with adsense.readonly" }, 400); + return c.json({ error: "accessToken must be a Google OAuth access token with adsense.readonly (or admob.readonly for source admob)" }, 400); } if (publisherId !== undefined && (typeof publisherId !== "string" || !/^pub-\d{16}$/.test(publisherId))) { return c.json({ error: "publisherId, when given, must be pub- and 16 digits" }, 400); } + // AdSense unless asked, so a client written before AdMob (#95) is unchanged. + if (source !== undefined && source !== "adsense" && source !== "admob") { + return c.json({ error: 'source, when given, must be "adsense" or "admob"' }, 400); + } try { const job = jobs.submit(borrower, (onStep) => - prover({ borrower, accessToken, publisherId }, onStep).catch((e: unknown) => { + prover({ borrower, accessToken, publisherId, ...(source === "admob" ? { source } : {}) }, onStep).catch((e: unknown) => { // Whatever failed, its message must not carry this job's token. if (e instanceof ProveError) throw new ProveError(e.code, e.message.split(accessToken).join("[redacted]")); throw new Error(String((e as Error)?.stack ?? e).split(accessToken).join("[redacted]")); diff --git a/be/src/api/server.ts b/be/src/api/server.ts index ff32f5d..983138a 100644 --- a/be/src/api/server.ts +++ b/be/src/api/server.ts @@ -14,6 +14,7 @@ import { serve } from "@hono/node-server"; import { ReclaimClient } from "@reclaimprotocol/zk-fetch"; import { rpc } from "@stellar/stellar-sdk"; +import { admobFetch } from "../admob/account.js"; import { googleGet } from "../adsense/account.js"; import { die, keepSecret, loadEnv, optional, scrub } from "../cli/env.js"; import { readAdvance } from "../chain/advance.js"; @@ -58,6 +59,7 @@ function relay(): Prover | undefined { const deps = { owner: appId, google: googleGet, + admob: admobFetch, zkFetch: ((url, options, secretOptions) => client.zkFetch(url, { ...options, zkEngine: ZK_ENGINE }, secretOptions)) as Parameters< typeof proveRevenue >[0]["zkFetch"], diff --git a/be/src/cli/prove-adsense.ts b/be/src/cli/prove-adsense.ts index 4fd3f50..3c02f2a 100644 --- a/be/src/cli/prove-adsense.ts +++ b/be/src/cli/prove-adsense.ts @@ -1,8 +1,14 @@ /** - * Produce one real AdSense revenue proof (#4), audit it, and save it for #5. + * Produce one real AdSense revenue proof (#4), audit it, and save it for #5. With + * `--admob` (`pnpm -C be prove:admob`), the same for AdMob (#95): the proof the AdMob + * claim template is derived from (#96). * * pnpm -C be zk:files once: the circuit files zkFetch proves with * pnpm -C be prove:adsense + * GOOGLE_ACCESS_TOKEN="$(wl-paste)" pnpm -C be prove:admob + * + * A token in the environment wins over be/.env, so a short-lived token for someone + * else's account never has to be written to a file. * * Reads be/.env (see be/.env.example). The file must be chmod 600, per the working * agreement; this script refuses to run otherwise. @@ -26,14 +32,18 @@ import { join } from "node:path"; import { ReclaimClient } from "@reclaimprotocol/zk-fetch"; +import { admobFetch } from "../admob/account.js"; import { ProveError, googleGet } from "../adsense/account.js"; import { formatFieldReport } from "../adsense/audit.js"; import { DEFAULT_TRAILING_MONTHS } from "../adsense/request.js"; import { prepareVerification } from "../reclaim/claim-digest.js"; import { ZK_ENGINE, hasZkFiles } from "../reclaim/zk-files.js"; -import { isoDate, proveRevenue, type ProveStep, type Proven } from "../relay/prove.js"; +import { isoDate, proveRevenue, type ProveStep, type Proven, type Source } from "../relay/prove.js"; import { BE_ROOT, die, keepSecret, loadEnv, need, optional } from "./env.js"; +const SOURCE: Source = process.argv.includes("--admob") ? "admob" : "adsense"; +const PRODUCT = SOURCE === "admob" ? "AdMob" : "AdSense"; + function readConfig() { loadEnv(true); if (!hasZkFiles()) die("the ZK circuit files are missing. Run: pnpm -C be zk:files"); @@ -42,13 +52,13 @@ function readConfig() { appSecret: keepSecret(need("RECLAIM_APP_SECRET")), accessToken: keepSecret(need("GOOGLE_ACCESS_TOKEN")), stellarAddress: need("STELLAR_ADDRESS"), - publisherId: optional("ADSENSE_PUBLISHER_ID"), + publisherId: optional(SOURCE === "admob" ? "ADMOB_PUBLISHER_ID" : "ADSENSE_PUBLISHER_ID"), months: Number(optional("TRAILING_MONTHS") || DEFAULT_TRAILING_MONTHS), }; } const STEPS: Record = { - checking: "[1/3] Checking the account and the provider against the live AdSense response…", + checking: `[1/3] Checking the account and the provider against the live ${PRODUCT} response…`, proving: "[2/3] Proving through Reclaim's attestor (this takes a while)…", auditing: "[3/3] Auditing the claim field by field…", }; @@ -56,7 +66,7 @@ const STEPS: Record = { async function main() { const env = readConfig(); - console.log("Forepay #4: AdSense revenue proof\n"); + console.log(`Forepay ${SOURCE === "admob" ? "#95" : "#4"}: ${PRODUCT} revenue proof\n`); console.log(` borrower: ${env.stellarAddress}`); const client = new ReclaimClient(env.appId, env.appSecret, false, 2); let proven: Proven; @@ -65,10 +75,11 @@ async function main() { { owner: env.appId, google: googleGet, + admob: admobFetch, zkFetch: (url, options, secretOptions) => client.zkFetch(url, { ...options, zkEngine: ZK_ENGINE }, secretOptions), months: env.months, }, - { borrower: env.stellarAddress, accessToken: env.accessToken, publisherId: env.publisherId }, + { borrower: env.stellarAddress, accessToken: env.accessToken, publisherId: env.publisherId, source: SOURCE }, (step) => console.log(`\n${STEPS[step]}`), ); } catch (e) { @@ -76,12 +87,12 @@ async function main() { die(`${(e as Error).message}${notSaved}`); } const { proof, publisherId, window, audit } = proven; - console.log(` publisher id: ${publisherId} (READY)`); + console.log(` publisher id: ${publisherId}${SOURCE === "adsense" ? " (READY)" : ""}`); console.log(` window: ${isoDate(window.start)} → ${isoDate(window.end)} (${env.months} complete months)`); const dir = join(BE_ROOT, "proofs"); mkdirSync(dir, { recursive: true }); - const file = join(dir, `adsense-${publisherId}-${proof.claimData.timestampS}.json`); + const file = join(dir, `${SOURCE}-${publisherId}-${proof.claimData.timestampS}.json`); writeFileSync(file, JSON.stringify(proof, null, 2) + "\n", { mode: 0o644 }); const v = prepareVerification( @@ -90,7 +101,8 @@ async function main() { proof.signatures[0], ); - console.log(`\n✔ Audit passed. Proven revenue: ${audit.revenueUsd} USD`); + const signed = audit.figure.name === "revenueUsd" ? "" : ` (signed as ${audit.figure.name} ${audit.figure.value})`; + console.log(`\n✔ Audit passed. Proven revenue: ${audit.revenueUsd} USD${signed}`); console.log(` saved: ${file}\n`); console.log(formatFieldReport(audit.fields)); console.log("\nverify_proof inputs (for #5):"); diff --git a/be/src/relay/fake-reclaim.ts b/be/src/relay/fake-reclaim.ts index 8f4fd32..c6e5b5e 100644 --- a/be/src/relay/fake-reclaim.ts +++ b/be/src/relay/fake-reclaim.ts @@ -1,10 +1,12 @@ /** - * Test support for #17: a Google AdSense API and a zkFetch that behave like the real + * Test support for #17 and #95: Google's AdSense and AdMob APIs and a zkFetch that behave like the real * ones for one account, with claims signed by a throwaway key standing in for the * attestor. Not imported by the relay itself. */ import { secp256k1 } from "@noble/curves/secp256k1"; +import type { AdmobFetch } from "../admob/account.js"; +import { ADMOB_API } from "../admob/request.js"; import { ProveError, type GoogleGet } from "../adsense/account.js"; import { ADSENSE_API, CONTEXT_MESSAGE, type RevenueWindow } from "../adsense/request.js"; import { canonicalStringify, createSignDataForClaim, getIdentifierFromClaimInfo, messageDigest } from "../reclaim/claim-digest.js"; @@ -58,10 +60,45 @@ export function fakeGoogle(o: FakeGoogle = {}): GoogleGet & { calls: string[] } return Object.assign(get, { calls }); } +/** + * An AdMob networkReport response with the bytes #93 read from a real account: two-space + * indents inside elements, and `\n,\r\n` between them. Without `micros` it is the zero + * case, `[header, footer {}]`. + */ +export function admobReport(w: RevenueWindow, micros?: string): string { + const el = (o: unknown) => JSON.stringify(o, null, 2); + const header = el({ header: { dateRange: { startDate: w.start, endDate: w.end }, localizationSettings: { currencyCode: "USD" } } }); + const row = el({ row: { metricValues: { ESTIMATED_EARNINGS: { microsValue: micros } } } }); + const footer = micros === undefined ? el({ footer: {} }) : el({ footer: { matchingRowCount: "1" } }); + return `[${[header, ...(micros === undefined ? [] : [row]), footer].join("\n,\r\n")}\n]`; +} + +export interface FakeAdmob { + accounts?: string[]; + report?: string; +} + +export function fakeAdmob(o: FakeAdmob = {}): AdmobFetch & { calls: { url: string; body?: string }[] } { + const calls: { url: string; body?: string }[] = []; + const fetchAdmob = async (url: string, token: string, body?: string) => { + calls.push({ url, body }); + if (token !== TOKEN) throw new ProveError("token", "Google refused the access token (401)."); + const path = url.slice(ADMOB_API.length); + if (path === "/accounts") { + return JSON.stringify({ account: (o.accounts ?? [PUB]).map((p) => ({ name: `accounts/${p}`, publisherId: p, currencyCode: "USD" })) }); + } + if (path === `/accounts/${PUB}/networkReport:generate` && body !== undefined) return o.report ?? admobReport(Q3, "12345678"); + throw new Error(`unexpected AdMob call ${url}`); + }; + return Object.assign(fetchAdmob, { calls }); +} + export interface FakeZk { /** Overrides applied to the signed context, e.g. another contextAddress. */ context?: Record; revenueUsd?: string; + /** Replaces `{ revenueUsd }` as the extracted parameters, e.g. `{ revenueMicros }`. */ + extracted?: Record; timestampS?: number; fail?: Error; } @@ -76,7 +113,7 @@ export function fakeZkFetch(o: FakeZk = {}): ZkFetch & { calls: Parameters = {}): ProveDeps { @@ -116,3 +116,39 @@ test("a proof whose owner is not this relay's Reclaim app is refused by the audi assert.equal(await code(proveRevenue(deps({ owner: other }), { borrower: ALICE, accessToken: TOKEN })), "audit"); await proveRevenue(deps({ owner: "0x96faf173bb7171a530b3e44f35f32d1307bda4fa" }), { borrower: ALICE, accessToken: TOKEN }); }); + +// AdMob (#95): the same pipeline, selected by `source`. + +function admobDeps(o: Partial = {}): ProveDeps { + return deps({ admob: fakeAdmob(), zkFetch: fakeZkFetch({ extracted: { revenueMicros: "12345678" } }), ...o }); +} + +test("source admob proves through AdMob, and the arguments carry the micros as signed", async () => { + const google = fakeGoogle(); + const admob = fakeAdmob(); + const proven = await proveRevenue(admobDeps({ google, admob }), { borrower: ALICE, accessToken: TOKEN, source: "admob" }); + assert.equal(google.calls.length, 0); + assert.deepEqual(admob.calls.map((c) => c.url.split("/v1")[1]), ["/accounts", `/accounts/${PUB}/networkReport:generate`]); + const req = toAdvanceRequest(proven); + assert.equal(req.source, "admob"); + assert.equal(req.revenueMicros, "12345678"); + assert.equal(req.revenueUsd, "12.345678"); + assert.equal(req.windowStart, "2026-07-01"); +}); + +test("AdMob at zero stops before the attestor", async () => { + const zk = fakeZkFetch(); + const admob = fakeAdmob({ report: admobReport(Q3) }); + assert.equal(await code(proveRevenue(admobDeps({ admob, zkFetch: zk }), { borrower: ALICE, accessToken: TOKEN, source: "admob" })), "provider"); + assert.equal(zk.calls.length, 0); +}); + +test("no AdMob account is the creator's to resolve", async () => { + const admob = fakeAdmob({ accounts: [] }); + assert.equal(await code(proveRevenue(admobDeps({ admob }), { borrower: ALICE, accessToken: TOKEN, source: "admob" })), "account"); +}); + +test("an AdMob proof extracted as revenueUsd is refused by the audit", async () => { + const zk = fakeZkFetch(); + assert.equal(await code(proveRevenue(admobDeps({ zkFetch: zk }), { borrower: ALICE, accessToken: TOKEN, source: "admob" })), "audit"); +}); diff --git a/be/src/relay/prove.ts b/be/src/relay/prove.ts index bdd38b3..54567c0 100644 --- a/be/src/relay/prove.ts +++ b/be/src/relay/prove.ts @@ -16,6 +16,9 @@ * headers, and nowhere else. It is not stored, logged or returned; the audit fails a * proof that contains it. */ +import { checkLiveReport, resolveAdmobPublisherId, type AdmobFetch } from "../admob/account.js"; +import { auditAdmobProof } from "../admob/audit.js"; +import { buildAdmobRequest, withAccessToken as withAdmobToken } from "../admob/request.js"; import { auditRevenueProof, type AuditResult, type RevenueProof } from "../adsense/audit.js"; import { ProveError, assertAccountReady, checkLiveResponse, resolvePublisherId, type GoogleGet } from "../adsense/account.js"; import { @@ -32,12 +35,17 @@ import { prepareVerification } from "../reclaim/claim-digest.js"; /** `ReclaimClient.zkFetch`, bound to an engine. Returns the proof or nothing. */ export type ZkFetch = ( url: string, - options: ReturnType["options"], + options: ReturnType["options"] | ReturnType["options"], secretOptions: ReturnType["secretOptions"], ) => Promise; +/** Which Google product the revenue is proven from (#90). AdSense unless asked. */ +export type Source = "adsense" | "admob"; + export interface ProveDeps { google: GoogleGet; + /** Required for `source: "admob"` only. */ + admob?: AdmobFetch; zkFetch: ZkFetch; now?: () => Date; months?: number; @@ -52,12 +60,14 @@ export interface ProveInput { accessToken: string; /** Optional; the only account the token can read when empty. */ publisherId?: string; + source?: Source; } /** `checking`: the pre-flight reads. `proving`: zkFetch, minutes. `auditing`: local, instant. */ export type ProveStep = "checking" | "proving" | "auditing"; export interface Proven { + source: Source; proof: RevenueProof; publisherId: string; window: RevenueWindow; @@ -70,17 +80,28 @@ const MAX_AGE_S = 3600; export async function proveRevenue(deps: ProveDeps, input: ProveInput, onStep: (s: ProveStep) => void = () => {}): Promise { assertStellarAccount(input.borrower); if (!input.accessToken) throw new ProveError("token", "an access token is required"); - const { google } = deps; + const source = input.source ?? "adsense"; + const window = trailingMonths((deps.now ?? (() => new Date()))(), deps.months ?? DEFAULT_TRAILING_MONTHS); onStep("checking"); - const publisherId = await resolvePublisherId(google, input.accessToken, input.publisherId); - await assertAccountReady(google, input.accessToken, publisherId); - const window = trailingMonths((deps.now ?? (() => new Date()))(), deps.months ?? DEFAULT_TRAILING_MONTHS); - const request = buildRevenueRequest({ publisherId, stellarAddress: input.borrower, window }); - await checkLiveResponse(google, input.accessToken, request); + let publisherId: string; + let call: { url: string; options: Parameters[1]; secretOptions: Parameters[2] }; + if (source === "admob") { + if (!deps.admob) throw new ProveError("provider", "this relay does not prove AdMob revenue"); + publisherId = await resolveAdmobPublisherId(deps.admob, input.accessToken, input.publisherId); + const request = buildAdmobRequest({ publisherId, stellarAddress: input.borrower, window }); + await checkLiveReport(deps.admob, input.accessToken, request); + call = withAdmobToken(request, input.accessToken); + } else { + const { google } = deps; + publisherId = await resolvePublisherId(google, input.accessToken, input.publisherId); + await assertAccountReady(google, input.accessToken, publisherId); + const request = buildRevenueRequest({ publisherId, stellarAddress: input.borrower, window }); + await checkLiveResponse(google, input.accessToken, request); + call = withAccessToken(request, input.accessToken); + } onStep("proving"); - const call = withAccessToken(request, input.accessToken); let proof: RevenueProof | undefined; try { proof = (await deps.zkFetch(call.url, call.options, call.secretOptions)) as RevenueProof | undefined; @@ -92,7 +113,7 @@ export async function proveRevenue(deps: ProveDeps, input: ProveInput, onStep: ( onStep("auditing"); let audit: AuditResult; try { - audit = auditRevenueProof(proof, { + const expect = { publisherId, stellarAddress: input.borrower, window, @@ -101,11 +122,12 @@ export async function proveRevenue(deps: ProveDeps, input: ProveInput, onStep: ( maxAgeS: MAX_AGE_S, attestor: deps.attestor, owner: deps.owner, - }); + }; + audit = source === "admob" ? auditAdmobProof(proof, expect) : auditRevenueProof(proof, expect); } catch (e) { throw new ProveError("audit", (e as Error).message); } - return { proof, publisherId, window, audit }; + return { source, proof, publisherId, window, audit }; } /** @@ -114,6 +136,7 @@ export async function proveRevenue(deps: ProveDeps, input: ProveInput, onStep: ( * decimal strings here: JSON numbers lose precision past 2^53. */ export interface AdvanceRequestJson { + /** For AdMob, the exact USD decimal for display; the contract takes `revenueMicros`. */ revenueUsd: string; pubId: string; windowStart: string; @@ -123,13 +146,17 @@ export interface AdvanceRequestJson { /** 64 bytes, hex, no 0x. */ signature: string; recoveryId: number; + /** Present for AdMob only, so an AdSense response is unchanged (#95). */ + source?: "admob"; + /** The figure as signed, in USD micros. AdMob only. */ + revenueMicros?: string; } export function isoDate(d: CivilDate): string { return `${d.year}-${String(d.month).padStart(2, "0")}-${String(d.day).padStart(2, "0")}`; } -export function toAdvanceRequest({ proof, publisherId, window, audit }: Proven): AdvanceRequestJson { +export function toAdvanceRequest({ source, proof, publisherId, window, audit }: Proven): AdvanceRequestJson { const c = proof.claimData; if (proof.signatures.length !== 1) throw new ProveError("audit", "expected exactly one attestor signature"); // Rebuilds the identifier from the claim info: a claim info that is not what was @@ -148,5 +175,6 @@ export function toAdvanceRequest({ proof, publisherId, window, audit }: Proven): epoch: String(c.epoch), signature: v.sig64.toString("hex"), recoveryId: v.recoveryId, + ...(source === "admob" ? { source, revenueMicros: audit.figure.value } : {}), }; } diff --git a/docs/admob-provider.md b/docs/admob-provider.md new file mode 100644 index 0000000..ac0ec52 --- /dev/null +++ b/docs/admob-provider.md @@ -0,0 +1,99 @@ +# The AdMob revenue provider (#95) + +How Forepay proves a creator's trailing AdMob revenue, as a sibling of +[the AdSense provider](adsense-provider.md). Read that first; this page covers only what is +different. Code: `be/src/admob/`. Run: `GOOGLE_ACCESS_TOKEN="$(wl-paste)" pnpm -C be prove:admob`, +or `POST /proofs` with `source: "admob"` ([api.md](api.md)). + +The facts below come from #93: a zkFetch POST to a public echo (part 1), and AdMob's real responses, +at zero and above zero, read from two accounts (part 2). + +--- + +## One request, a POST with the window in the body + +``` +POST https://admob.googleapis.com/v1/accounts/{pub-id}/networkReport:generate +content-type: application/json +Authorization: Bearer ← secret header, not in the claim + +{"reportSpec":{"dateRange":{"startDate":{"year":2026,"month":7,"day":1},"endDate":{"year":2026,"month":9,"day":30}},"metrics":["ESTIMATED_EARNINGS"],"localizationSettings":{"currencyCode":"USD"}}} +``` + +- **The body is signed.** The attestor puts it in `parameters.body`, byte for byte, and a claim + with a different window recovers to a different signer (#93 part 1). So the body pins the + window, the way the query string does for AdSense. `buildReportBody` writes it by hand, in a + fixed key order with no whitespace, so the same window always gives the same bytes. +- **No dimensions.** The response then carries exactly one row: the window's total. Monthly rows + are rounded separately, and their sum can differ from the total by a micro (#93). +- **Same window as AdSense:** the last three complete calendar months (`trailingMonths`). +- **The publisher id can be the same as the creator's AdSense id** (#93). The host in the signed + URL is what says which product a claim is about. + +## The response, as the attestor reads it + +A pretty-printed JSON array. The elements use LF and two-space indents, and are separated by +`}\n,\r\n{` (with a CR): + +``` +[{ + "header": { … "localizationSettings": { "currencyCode": "USD" } } +} +,\r +{ + "row": { "metricValues": { "ESTIMATED_EARNINGS": { "microsValue": "12345678" } } } +} +,\r +{ + "footer": { "matchingRowCount": "1" } +} +] +``` + +At **zero there is no `row`**, and the footer is `{}`. This is the same situation as an AdSense +response with no `totals`, and it gets the same handling: the local check finds no match, and the +relay stops with `provider` before the attestor. + +The two regexes (RE2) each stay within one element, so the separator never matters to them: + +| Match | Reveals | +| --- | --- | +| `"localizationSettings": { "currencyCode": "USD" }` | the currency | +| `"row": { "metricValues": { "ESTIMATED_EARNINGS": { "microsValue": "(?\d+)" } } }` | the total | + +A row that opens with `metricValues` has no `dimensionValues`, so the second match cannot be +satisfied by a per-dimension row. + +The live check before proving runs on the **raw** response text. AdSense's check re-serialises the +JSON first; here that would drop the `\r`. + +## The signed claim: what differs from AdSense + +| Field | AdMob | +| --- | --- | +| `parameters.method` | `POST` | +| `parameters.body` | the report spec above: the window, one metric, USD | +| `parameters.headers` | `accept`, `content-type`, `User-Agent`, all public | +| `parameters.url` | host and publisher id only | +| `context.extractedParameters` | `{ "revenueMicros": "" }`, millionths of a USD | + +Everything else is the same as for AdSense: the context message, the borrower in +`contextAddress`, the allow-list audit, and the credential scan. + +## What the contract must check (#94) + +- **Its own template per source.** The host is in the template, so an AdMob claim can never be + checked against the AdSense template, or the reverse. +- **The value order.** The attestor sorts the parameters' keys, so `body` comes before `url`. In + the signed bytes the six date numbers therefore come **before** the publisher id: + `[sy, sm, sd, ey, em, ed, pub_id]`. AdSense's order is the reverse. `be/src/admob/request.test.ts` + pins this order. +- **Micros to cents, truncating:** `revenueMicros / 10_000`, never rounded up. +- **A nullifier tagged with the source**, because the publisher id can be shared with AdSense. + +## Open points + +- **The first real proof.** The bytes above were read with curl. The first `prove:admob` run on a + real account confirms them as signed. That proof is the input to the template (#96). +- **The OAuth client** asks only for `adsense.readonly` until #86 is through (#98). Until then, an + AdMob token comes from the OAuth Playground. diff --git a/docs/api.md b/docs/api.md index 32c4a73..8026cf5 100644 --- a/docs/api.md +++ b/docs/api.md @@ -141,6 +141,10 @@ anything, and the contract reads the borrower from that context, never from an a `publisherId` is optional: without it, the relay uses the only AdSense account the token can read. +`source` is optional, `"adsense"` (the default) or `"admob"` (#95). With `"admob"` the token needs +`admob.readonly` instead, `publisherId` names an AdMob account, and the proof is of AdMob's +`networkReport:generate` over the same window. A client that does not send `source` is unchanged. + `202`, with `Location: /proofs/`: ```json @@ -149,7 +153,7 @@ anything, and the contract reads the borrower from that context, never from an a | Status | When | | --- | --- | -| `400` | Not JSON, a borrower that is not a `G…`, no token or one too short to be Google's, or a malformed `publisherId` | +| `400` | Not JSON, a borrower that is not a `G…`, no token or one too short to be Google's, a malformed `publisherId`, or a `source` other than `adsense` or `admob` | | `409` | A proof for this borrower is already in progress (`code: "running"`). The running job's id is not returned: a borrower's address is public, and the id reads their revenue. Keep the id from the `202` | | `413` | Body over 8 KB | | `503` | The relay is busy (`code: "busy"`, `Retry-After: 120`), or not configured on this server (`code: "unconfigured"`; `/config` says `"relay": false`) | @@ -181,13 +185,18 @@ Poll every few seconds. `stage` goes `queued` → `checking` → `proving` → ` `epoch` are strings: pass them through `BigInt()`. The contract accepts the proof for an hour after `timestampS`. +For `source: "admob"`, `request` also carries `"source": "admob"` and `"revenueMicros"`, the figure +exactly as signed, in millionths of a USD (`"12345678"`). `revenueUsd` is then the same figure as an +exact decimal (`"12.345678"`), for display only: the contract takes `revenueMicros` and truncates it +to cents (#94). An AdSense `request` has neither field. + A failed job has `error: { code, message }`. The code says whose move it is: | `code` | Meaning | What the creator can do | | --- | --- | --- | -| `token` | Google refused the token: expired, or without `adsense.readonly` | Sign in again | -| `account` | No AdSense account, several (pass `publisherId`), or one that is not `READY` | Use an approved account | -| `provider` | AdSense answered in a shape the provider does not expect | Nothing; ours to fix | +| `token` | Google refused the token: expired, or without `adsense.readonly` (`admob.readonly` for AdMob) | Sign in again | +| `account` | No AdSense or AdMob account, several (pass `publisherId`), or an AdSense one that is not `READY` | Use an approved account | +| `provider` | Google answered in a shape the provider does not expect, or AdMob reports no earnings in the window (no `row`, #93) | Nothing; ours to fix, or no revenue to prove | | `prove` | The attestor or zkFetch failed | Try again | | `audit` | The proof came back but failed the audit, so it was not returned | Nothing; ours to fix | | `internal` | Anything else | Try again | From ae711147ac85c38745a2fea7bfdfab13e1826d16 Mon Sep 17 00:00:00 2001 From: lin1er Date: Tue, 27 Oct 2026 16:37:28 +0700 Subject: [PATCH 2/4] fix(#95): AdMob at zero fails with its own code, empty, not provider A report with no row is how AdMob says the account earned nothing. That is not a shape the relay failed to expect, so the front end should not tell the creator to try again in a few minutes (asked on #104). --- be/src/admob/account.ts | 11 ++++------- be/src/adsense/account.ts | 2 ++ be/src/relay/prove.test.ts | 2 +- docs/api.md | 3 ++- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/be/src/admob/account.ts b/be/src/admob/account.ts index e337edd..fc0f379 100644 --- a/be/src/admob/account.ts +++ b/be/src/admob/account.ts @@ -66,13 +66,10 @@ export async function checkLiveReport(fetchAdmob: AdmobFetch, accessToken: strin const raw = await fetchAdmob(request.url, accessToken, request.options.body); for (const m of request.secretOptions.responseMatches) { if (new RegExp(m.value).test(raw)) continue; - const zero = !raw.includes('"row"'); - throw new ProveError( - "provider", - zero - ? "AdMob reports no earnings for this window: the report has no row, which is how AdMob says zero." - : `the live AdMob response does not match ${m.value}\nResponse keys: ${elementKeys(raw)}`, - ); + if (!raw.includes('"row"')) { + throw new ProveError("empty", "AdMob reports no earnings for this window: the report has no row, which is how AdMob says zero."); + } + throw new ProveError("provider", `the live AdMob response does not match ${m.value}\nResponse keys: ${elementKeys(raw)}`); } } diff --git a/be/src/adsense/account.ts b/be/src/adsense/account.ts index eab79e4..e754606 100644 --- a/be/src/adsense/account.ts +++ b/be/src/adsense/account.ts @@ -19,6 +19,8 @@ export type ProveErrorCode = | "account" /** AdSense answered with a shape the provider does not match. Ours to fix. */ | "provider" + /** The account earned nothing in the window (AdMob sends no row, #93). Nothing to prove. */ + | "empty" /** The attestor or zkFetch failed. Worth retrying. */ | "prove" /** The proof came back but failed the audit. Ours to fix; nothing was returned. */ diff --git a/be/src/relay/prove.test.ts b/be/src/relay/prove.test.ts index 8d4d498..4d47582 100644 --- a/be/src/relay/prove.test.ts +++ b/be/src/relay/prove.test.ts @@ -139,7 +139,7 @@ test("source admob proves through AdMob, and the arguments carry the micros as s test("AdMob at zero stops before the attestor", async () => { const zk = fakeZkFetch(); const admob = fakeAdmob({ report: admobReport(Q3) }); - assert.equal(await code(proveRevenue(admobDeps({ admob, zkFetch: zk }), { borrower: ALICE, accessToken: TOKEN, source: "admob" })), "provider"); + assert.equal(await code(proveRevenue(admobDeps({ admob, zkFetch: zk }), { borrower: ALICE, accessToken: TOKEN, source: "admob" })), "empty"); assert.equal(zk.calls.length, 0); }); diff --git a/docs/api.md b/docs/api.md index 8026cf5..dfd2eee 100644 --- a/docs/api.md +++ b/docs/api.md @@ -196,7 +196,8 @@ A failed job has `error: { code, message }`. The code says whose move it is: | --- | --- | --- | | `token` | Google refused the token: expired, or without `adsense.readonly` (`admob.readonly` for AdMob) | Sign in again | | `account` | No AdSense or AdMob account, several (pass `publisherId`), or an AdSense one that is not `READY` | Use an approved account | -| `provider` | Google answered in a shape the provider does not expect, or AdMob reports no earnings in the window (no `row`, #93) | Nothing; ours to fix, or no revenue to prove | +| `provider` | Google answered in a shape the provider does not expect | Nothing; ours to fix | +| `empty` | AdMob reports no earnings in the window (no `row`, #93) | Nothing to prove for these months | | `prove` | The attestor or zkFetch failed | Try again | | `audit` | The proof came back but failed the audit, so it was not returned | Nothing; ours to fix | | `internal` | Anything else | Try again | From 4e1a5d4accbb5e282f0807a7a24a25862080da1f Mon Sep 17 00:00:00 2001 From: lin1er Date: Tue, 27 Oct 2026 16:38:47 +0700 Subject: [PATCH 3/4] fix(#95): AdSense at zero fails as empty too An approved AdSense account with no earnings answers with only its headers and dates: no totals, no averages, no row count. That failed as provider, the same as a shape we did not expect. It is now empty, before the attestor, like AdMob. --- be/src/adsense/account.ts | 11 ++++++++++- be/src/relay/prove.test.ts | 9 +++++++++ docs/api.md | 2 +- 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/be/src/adsense/account.ts b/be/src/adsense/account.ts index e754606..c609717 100644 --- a/be/src/adsense/account.ts +++ b/be/src/adsense/account.ts @@ -19,7 +19,7 @@ export type ProveErrorCode = | "account" /** AdSense answered with a shape the provider does not match. Ours to fix. */ | "provider" - /** The account earned nothing in the window (AdMob sends no row, #93). Nothing to prove. */ + /** The account earned nothing in the window: AdMob sends no row (#93), AdSense only headers and dates. */ | "empty" /** The attestor or zkFetch failed. Worth retrying. */ | "prove" @@ -108,11 +108,20 @@ export function shapeOf(v: unknown): unknown { * in a second, with the response's structure (keys only, never values), instead of as * an opaque attestor failure minutes later. */ +/** A report for an account that earned nothing: its headers and dates, and no other key. */ +function isEmptyReport(live: unknown): boolean { + if (typeof live !== "object" || live === null || !("headers" in live)) return false; + return Object.keys(live).every((k) => k === "headers" || k === "startDate" || k === "endDate"); +} + export async function checkLiveResponse(get: GoogleGet, accessToken: string, request: RevenueRequest): Promise { const live = await get(request.url, accessToken); const pretty = JSON.stringify(live, null, 2); for (const m of request.secretOptions.responseMatches) { if (!new RegExp(m.value).test(pretty)) { + if (isEmptyReport(live)) { + throw new ProveError("empty", "AdSense reports no earnings for this window: the report has only its headers and dates, which is how AdSense says zero."); + } throw new ProveError( "provider", `the live response does not match ${m.value}\nResponse structure (values hidden):\n${JSON.stringify(shapeOf(live), null, 2)}`, diff --git a/be/src/relay/prove.test.ts b/be/src/relay/prove.test.ts index 4d47582..a2eca77 100644 --- a/be/src/relay/prove.test.ts +++ b/be/src/relay/prove.test.ts @@ -136,6 +136,15 @@ test("source admob proves through AdMob, and the arguments carry the micros as s assert.equal(req.windowStart, "2026-07-01"); }); +test("AdSense at zero stops before the attestor, as empty", async () => { + const zk = fakeZkFetch(); + // What AdSense sent for an approved account with no earnings: no totals, no averages, no row count. + const { headers, startDate, endDate } = report(Q3); + const google = fakeGoogle({ report: { headers, startDate, endDate } }); + assert.equal(await code(proveRevenue(deps({ google, zkFetch: zk }), { borrower: ALICE, accessToken: TOKEN })), "empty"); + assert.equal(zk.calls.length, 0); +}); + test("AdMob at zero stops before the attestor", async () => { const zk = fakeZkFetch(); const admob = fakeAdmob({ report: admobReport(Q3) }); diff --git a/docs/api.md b/docs/api.md index dfd2eee..9278556 100644 --- a/docs/api.md +++ b/docs/api.md @@ -197,7 +197,7 @@ A failed job has `error: { code, message }`. The code says whose move it is: | `token` | Google refused the token: expired, or without `adsense.readonly` (`admob.readonly` for AdMob) | Sign in again | | `account` | No AdSense or AdMob account, several (pass `publisherId`), or an AdSense one that is not `READY` | Use an approved account | | `provider` | Google answered in a shape the provider does not expect | Nothing; ours to fix | -| `empty` | AdMob reports no earnings in the window (no `row`, #93) | Nothing to prove for these months | +| `empty` | No earnings in the window: AdMob sends no `row` (#93), AdSense only `headers` and the dates | Nothing to prove for these months | | `prove` | The attestor or zkFetch failed | Try again | | `audit` | The proof came back but failed the audit, so it was not returned | Nothing; ours to fix | | `internal` | Anything else | Try again | From 8097128f28e914219a8bc0a4dbac1282343ad6ba Mon Sep 17 00:00:00 2001 From: lin1er Date: Fri, 30 Oct 2026 06:34:18 +0700 Subject: [PATCH 4/4] test(#95): an AdMob proof is held to the relay's own claim owner too (#102) --- be/src/relay/prove.test.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/be/src/relay/prove.test.ts b/be/src/relay/prove.test.ts index a2eca77..9a5c3dc 100644 --- a/be/src/relay/prove.test.ts +++ b/be/src/relay/prove.test.ts @@ -152,6 +152,11 @@ test("AdMob at zero stops before the attestor", async () => { assert.equal(zk.calls.length, 0); }); +test("an AdMob proof whose owner is not this relay's Reclaim app is refused by the audit (#102)", async () => { + const other = "0x6415200c713135e77157e1536d488df4f2bb7d04"; + assert.equal(await code(proveRevenue(admobDeps({ owner: other }), { borrower: ALICE, accessToken: TOKEN, source: "admob" })), "audit"); +}); + test("no AdMob account is the creator's to resolve", async () => { const admob = fakeAdmob({ accounts: [] }); assert.equal(await code(proveRevenue(admobDeps({ admob }), { borrower: ALICE, accessToken: TOKEN, source: "admob" })), "account");