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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions be/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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=

Expand Down
1 change: 1 addition & 0 deletions be/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
85 changes: 85 additions & 0 deletions be/src/admob/account.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/**
* 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<string>;

/** 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<string> {
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<void> {
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;
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)}`);
}
}

/** 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";
}
68 changes: 68 additions & 0 deletions be/src/admob/audit.test.ts
Original file line number Diff line number Diff line change
@@ -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<RevenueProof> {
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);
});
56 changes: 56 additions & 0 deletions be/src/admob/audit.ts
Original file line number Diff line number Diff line change
@@ -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<string> = 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<AuditExpectations, "publisherId" | "stellarAddress" | "window">): 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 ?? "") };
}
93 changes: 93 additions & 0 deletions be/src/admob/request.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown> };
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/);
});
Loading