apps / health / catalog / validate: fixes from a read-only run against live store accounts
- API error bodies on one line (errorBody): Google and App Store Connect pretty-print errors, which hid SERVICE_DISABLED from the Play account check (reported permission instead of api-disabled), broke tables and turned serve's apps.list error into a JSON fragment - apps list: failure says the reason and the fix (same words as apps check) - newest App Store version by createdDate, iOS first (the API groups versions by platform); all versions read so no platform is missed; per-app reads four at a time - apps check (apple): team app count from meta.paging.total with a one-app read - Play Money without units (prices under 1.00) read as 0.xx, not NaN (catalog diff, subscription diffs) - health: App Store Connect 404 for perfPowerMetrics / diagnosticSignatures means no field data yet; Play vitals behind a disabled Reporting API say so with the fix - validate: gracRatingClassificationNumber optional, socialMediaAgeRestricted only when socialMedia is yes, socialMedia unanswered is a warning - tests with sanitized recorded responses (tests/store-real-shapes.test.ts)
This commit is contained in:
parent
8bb28db45c
commit
b8da75e519
14 changed files with 342 additions and 34 deletions
|
|
@ -3,6 +3,7 @@
|
|||
import { createHash, createPrivateKey, sign } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { ascKey } from '../lib/credentials';
|
||||
import { errorBody } from '../lib/http';
|
||||
|
||||
const b64 = (b: Buffer | string): string => Buffer.from(b).toString('base64url');
|
||||
export const md5 = (b: Buffer | Uint8Array): string => createHash('md5').update(b).digest('hex');
|
||||
|
|
@ -42,7 +43,7 @@ export async function ascClient(root: string, bundleId: string, appIdHint?: stri
|
|||
});
|
||||
const t = await r.text();
|
||||
if ((r.status >= 500 || r.status === 429) && attempt < 5) { await Bun.sleep(2000 * attempt); return asc(method, path, body, attempt + 1); }
|
||||
if (!r.ok) throw new Error(`${method} ${path} -> ${r.status} ${t.slice(0, 1500)}`);
|
||||
if (!r.ok) throw new Error(`${method} ${path} -> ${r.status} ${errorBody(t)}`);
|
||||
return t ? JSON.parse(t) : {};
|
||||
}
|
||||
|
||||
|
|
@ -52,7 +53,7 @@ export async function ascClient(root: string, bundleId: string, appIdHint?: stri
|
|||
const r = await fetch('https://api.appstoreconnect.apple.com' + path, { headers: { Authorization: 'Bearer ' + jwt(), Accept: accept } });
|
||||
const t = await r.text();
|
||||
if ((r.status >= 500 || r.status === 429) && attempt < 5) { await Bun.sleep(2000 * attempt); continue; }
|
||||
if (!r.ok) throw new Error(`GET ${path} -> ${r.status} ${t.slice(0, 800)}`);
|
||||
if (!r.ok) throw new Error(`GET ${path} -> ${r.status} ${errorBody(t, 800)}`);
|
||||
return t ? JSON.parse(t) : {};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
19
cli/apps.ts
19
cli/apps.ts
|
|
@ -9,6 +9,7 @@ import type { Args } from './lib/args';
|
|||
import { ascKey, playServiceAccount } from './lib/credentials';
|
||||
import type { AccountCheck, AppsListResult } from './lib/desktop-protocol';
|
||||
import { PLAY_SCOPE, REPORTING_SCOPE, tokenSource } from './lib/google-auth';
|
||||
import { errorBody } from './lib/http';
|
||||
import { log, printJson, warn } from './lib/log';
|
||||
import { appleCheck, type Bytes, dataUrl, type Get, listAppleApps, listPlayApps, MAX_ICON_BYTES, playCheck } from './lib/store-apps';
|
||||
import { textTable } from './lib/table';
|
||||
|
|
@ -48,7 +49,7 @@ function googleGet(token: () => Promise<string>, base: string): Get {
|
|||
const r = await fetch(path.startsWith('http') ? path : base + path, { headers: { Authorization: 'Bearer ' + (await token()) } });
|
||||
const t = await r.text();
|
||||
if ((r.status === 429 || r.status >= 500) && attempt < 3) { await Bun.sleep(1500 * (attempt + 1)); continue; }
|
||||
if (!r.ok) throw new Error(`GET ${path.replace(/^https:\/\/[^/]+/, '')} -> ${r.status} ${/^\s*</.test(t) ? '(HTML error page)' : t.slice(0, 800)}`);
|
||||
if (!r.ok) throw new Error(`GET ${path.replace(/^https:\/\/[^/]+/, '')} -> ${r.status} ${errorBody(t, 800)}`);
|
||||
return t ? JSON.parse(t) : {};
|
||||
}
|
||||
};
|
||||
|
|
@ -61,7 +62,7 @@ function playIcon(root: string): (pkg: string) => Promise<string | null> {
|
|||
const call = async (method: string, url: string) => {
|
||||
const r = await fetch(url, { method, headers: { Authorization: 'Bearer ' + (await token()) } });
|
||||
const t = await r.text();
|
||||
if (!r.ok) throw new Error(`${method} -> ${r.status} ${t.slice(0, 300)}`);
|
||||
if (!r.ok) throw new Error(`${method} -> ${r.status} ${errorBody(t, 300)}`);
|
||||
return t ? JSON.parse(t) : {};
|
||||
};
|
||||
return async pkg => {
|
||||
|
|
@ -81,6 +82,8 @@ function playIcon(root: string): (pkg: string) => Promise<string | null> {
|
|||
};
|
||||
}
|
||||
|
||||
const principalOf = (root: string): string | null => { try { return playServiceAccount(root).client_email; } catch { return null; } };
|
||||
|
||||
export async function listApps(store: Store, root: string, icons: boolean): Promise<AppsListResult> {
|
||||
const at = new Date().toISOString();
|
||||
if (store === 'apple') {
|
||||
|
|
@ -95,8 +98,9 @@ export async function listApps(store: Store, root: string, icons: boolean): Prom
|
|||
export async function checkAccount(store: Store, root: string): Promise<AccountCheck> {
|
||||
if (store === 'apple') {
|
||||
try {
|
||||
const page = await (await appleGet(root))('/v1/apps?fields[apps]=bundleId&limit=200');
|
||||
return appleCheck({ apps: (page.data ?? []).length });
|
||||
// one app is enough to prove the key; the team's app count is meta.paging.total
|
||||
const page = await (await appleGet(root))('/v1/apps?fields[apps]=bundleId&limit=1');
|
||||
return appleCheck({ apps: Number(page.meta?.paging?.total ?? (page.data ?? []).length) });
|
||||
} catch (e) { return appleCheck({ error: e }); }
|
||||
}
|
||||
let principal: string | null = null;
|
||||
|
|
@ -116,8 +120,11 @@ export async function run(args: Args): Promise<void> {
|
|||
const out: AppsListResult[] = [];
|
||||
for (const s of stores(args, root)) {
|
||||
try { out.push(await listApps(s, root, args.has('icons'))); } catch (e) {
|
||||
if (args.get('store')) throw e;
|
||||
warn('apps', `${s}: ${(e as Error).message.split('\n')[0]}`);
|
||||
// say what is wrong and how to fix it (the same words as `apps check`), not the raw API error
|
||||
const c = s === 'apple' ? appleCheck({ error: e }) : playCheck(principalOf(root), { error: e });
|
||||
const why = `${c.message}${c.fix ? ` Fix: ${c.fix}` : ''}`;
|
||||
if (args.get('store')) throw new Error(why);
|
||||
warn('apps', `${s}: ${why}`);
|
||||
}
|
||||
}
|
||||
if (json) { printJson(args.get('store') ? out[0] : out); return; }
|
||||
|
|
|
|||
|
|
@ -41,12 +41,14 @@ export async function collectAppleHealth(root: string, bundleId: string, appIdHi
|
|||
const c = await ascClient(root, bundleId, appIdHint);
|
||||
const appId = await c.app();
|
||||
log('health', 'apple: power and performance metrics');
|
||||
const metrics = parsePerfPower(await c.getAs(`/v1/apps/${appId}/perfPowerMetrics?filter[platform]=IOS`, 'application/vnd.apple.xcode-metrics+json'));
|
||||
// App Store Connect answers 404 (not an empty list) while there is no field data yet: a new app, or TestFlight-only builds
|
||||
const none = <T>(fallback: T) => (e: unknown): T => { if (/-> 404\b/.test(String(e))) return fallback; throw e; };
|
||||
const metrics = parsePerfPower(await c.getAs(`/v1/apps/${appId}/perfPowerMetrics?filter[platform]=IOS`, 'application/vnd.apple.xcode-metrics+json').catch(none({})));
|
||||
const builds = (await c.asc('GET', `/v1/builds?filter[app]=${appId}&filter[processingState]=VALID&sort=-uploadedDate&limit=3`)).data as J[];
|
||||
const signatures: AppleHealth['signatures'] = [];
|
||||
for (const b of builds) {
|
||||
log('health', `apple: diagnostic signatures of build ${b.attributes.version}`);
|
||||
for (const s of (await c.asc('GET', `/v1/builds/${b.id}/diagnosticSignatures?limit=10`)).data as J[])
|
||||
for (const s of ((await c.asc('GET', `/v1/builds/${b.id}/diagnosticSignatures?limit=10`).catch(none({ data: [] }))).data ?? []) as J[])
|
||||
signatures.push({ build: b.attributes.version, type: s.attributes.diagnosticType, signature: s.attributes.signature ?? '', weight: Number(s.attributes.weight ?? 0) });
|
||||
}
|
||||
signatures.sort((a, b) => b.weight - a.weight);
|
||||
|
|
|
|||
|
|
@ -172,10 +172,18 @@ const levelFor = (v: number | null, limit: number): Level => (v === null ? 'ok'
|
|||
/** Health -> validate findings. Over a Play bad behavior threshold = blocker (Play lowers discoverability and may
|
||||
* warn users on the listing), from 80 % of it = warn. Apple publishes no thresholds: "poor" goals and heavy
|
||||
* diagnostic signatures are warnings. */
|
||||
/** A Google 403 for an API that is not enabled in the caller's Cloud project. */
|
||||
export const REPORTING_OFF = /SERVICE_DISABLED|has not been used in project|accessNotConfigured/;
|
||||
|
||||
export function healthFindings(h: HealthSnapshot, o: { unreadable?: Level } = {}): Finding[] {
|
||||
const f: Finding[] = [];
|
||||
const play = h.play;
|
||||
if (play && 'error' in play) f.push({ store: 'play', level: o.unreadable ?? 'warn', code: 'vitals', msg: `vitals not readable: ${play.error.slice(0, 200)}`, fix: 'store-health skill (Reporting API access)' });
|
||||
if (play && 'error' in play) {
|
||||
f.push(REPORTING_OFF.test(play.error)
|
||||
? { store: 'play', level: o.unreadable ?? 'warn', code: 'vitals', msg: 'vitals not readable: the Google Play Developer Reporting API is off in the service account\'s Google Cloud project',
|
||||
fix: 'Google Cloud console > APIs & Services > Library: enable "Google Play Developer Reporting API" in that project, wait a few minutes (store-health skill)' }
|
||||
: { store: 'play', level: o.unreadable ?? 'warn', code: 'vitals', msg: `vitals not readable: ${play.error.slice(0, 200)}`, fix: 'store-health skill (Reporting API access)' });
|
||||
}
|
||||
else if (play) {
|
||||
const crash = lastValue(play.crash, 'userPerceivedCrashRate28dUserWeighted') ?? weightedAverage(play.crash, 'userPerceivedCrashRate');
|
||||
const anr = lastValue(play.anr, 'userPerceivedAnrRate28dUserWeighted') ?? weightedAverage(play.anr, 'userPerceivedAnrRate');
|
||||
|
|
|
|||
|
|
@ -11,3 +11,15 @@ export async function checkUrl(url: string, o: { body?: boolean; timeoutMs?: num
|
|||
return { url, status: null, error: (e as Error).message };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An API error body for an Error message: JSON on one line (App Store Connect and Google pretty-print their errors,
|
||||
* which broke tables, `lastLine` in serve and matching on the error reason), an HTML page named as such, else the text
|
||||
* with its whitespace collapsed. At most `max` characters.
|
||||
*/
|
||||
export function errorBody(text: string, max = 1500): string {
|
||||
if (/^\s*</.test(text)) return '(HTML error page)';
|
||||
let s: string;
|
||||
try { s = JSON.stringify(JSON.parse(text)); } catch { s = text.replace(/\s+/g, ' ').trim(); }
|
||||
return s.length > max ? s.slice(0, max) + '…' : s;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,7 +10,9 @@ export function toMoney(currencyCode: string, value: number): Money {
|
|||
return { currencyCode, units: String(Math.floor(cents / 100)), nanos: (cents % 100) * 10_000_000 };
|
||||
}
|
||||
|
||||
export const fromMoney = (m: Money): number => Number(m.units) + (m.nanos ?? 0) / 1e9;
|
||||
/** Google Money -> number. Proto3 JSON leaves out zero fields: a 0.99 price comes back as { nanos: 990000000 } with no
|
||||
* units (and 1.00 with no nanos), so both default to 0. */
|
||||
export const fromMoney = (m: Omit<Money, 'units'> & { units?: string | number | null }): number => Number(m.units ?? 0) + (m.nanos ?? 0) / 1e9;
|
||||
|
||||
export interface RegionConfig { regionCode: string; availability: 'AVAILABLE'; price: Money }
|
||||
|
||||
|
|
|
|||
|
|
@ -41,18 +41,18 @@ export async function listAppleApps(get: Get, o: { icons?: boolean; bytes?: Byte
|
|||
raw.push(...(page.data ?? []));
|
||||
url = page.links?.next ?? null;
|
||||
}
|
||||
const apps: StoreApp[] = [];
|
||||
for (const a of raw) {
|
||||
const one = async (a: J): Promise<StoreApp> => {
|
||||
const app: StoreApp = {
|
||||
store: 'ios', id: String(a.id), bundleId: String(a.attributes?.bundleId ?? ''), name: String(a.attributes?.name ?? a.attributes?.bundleId ?? a.id),
|
||||
platforms: [], sku: a.attributes?.sku ?? null, primaryLocale: a.attributes?.primaryLocale ?? null, latest: null, icon: null,
|
||||
};
|
||||
try {
|
||||
const vs: J[] = (await get(`/v1/apps/${a.id}/appStoreVersions?limit=5&fields[appStoreVersions]=platform,versionString,appStoreState,appVersionState,createdDate`)).data ?? [];
|
||||
// App Store Connect groups this list by platform (not by date), so a short page can hide a platform and its
|
||||
// first item is not the newest version: read them all (small, fields only) and sort by createdDate.
|
||||
const vs: J[] = (await get(`/v1/apps/${a.id}/appStoreVersions?limit=200&fields[appStoreVersions]=platform,versionString,appStoreState,appVersionState,createdDate`)).data ?? [];
|
||||
app.platforms = [...new Set(vs.map(v => String(v.attributes?.platform ?? '')).filter(Boolean))];
|
||||
const v = vs[0];
|
||||
if (v) app.latest = { version: String(v.attributes?.versionString ?? ''), state: ASC_STATE(v), platform: v.attributes?.platform ?? null };
|
||||
} catch (e) { warnings.push(`${app.bundleId}: versions not read (${short(e)})`); }
|
||||
app.latest = latestVersion(vs);
|
||||
} catch (e) { warns.set(a, [...(warns.get(a) ?? []), `${app.bundleId}: versions not read (${short(e)})`]); }
|
||||
if (o.icons && o.bytes) {
|
||||
try {
|
||||
const b: J = (await get(`/v1/builds?filter[app]=${a.id}&sort=-uploadedDate&limit=1&fields[builds]=iconAssetToken,version`)).data?.[0];
|
||||
|
|
@ -61,13 +61,35 @@ export async function listAppleApps(get: Get, o: { icons?: boolean; bytes?: Byte
|
|||
const img = await o.bytes(iconUrl(tpl));
|
||||
if (img && img.data.length <= MAX_ICON_BYTES) app.icon = dataUrl(img.type, img.data);
|
||||
}
|
||||
} catch (e) { warnings.push(`${app.bundleId}: icon not read (${short(e)})`); }
|
||||
} catch (e) { warns.set(a, [...(warns.get(a) ?? []), `${app.bundleId}: icon not read (${short(e)})`]); }
|
||||
}
|
||||
apps.push(app);
|
||||
}
|
||||
return app;
|
||||
};
|
||||
const warns = new Map<J, string[]>();
|
||||
const apps = await pool(raw, APPLE_CONCURRENCY, one);
|
||||
for (const a of raw) warnings.push(...(warns.get(a) ?? []));
|
||||
return { apps: apps.sort((x, y) => x.name.localeCompare(y.name)), warnings };
|
||||
}
|
||||
|
||||
/** Per-app App Store Connect reads in flight at once (a 50-app team took a minute one by one). */
|
||||
export const APPLE_CONCURRENCY = 4;
|
||||
|
||||
/** fn over items, `n` at a time, results in input order. */
|
||||
export async function pool<T, R>(items: T[], n: number, fn: (x: T) => Promise<R>): Promise<R[]> {
|
||||
const out: R[] = new Array(items.length);
|
||||
let next = 0;
|
||||
await Promise.all(Array.from({ length: Math.min(n, items.length) }, async () => { while (next < items.length) { const i = next++; out[i] = await fn(items[i]!); } }));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Newest App Store version by createdDate; the iOS one when the app has iOS versions (the store-side twin of an
|
||||
* Android app), else the newest of any platform. */
|
||||
export function latestVersion(vs: J[]): StoreApp['latest'] {
|
||||
const sorted = [...vs].sort((x, y) => String(y.attributes?.createdDate ?? '').localeCompare(String(x.attributes?.createdDate ?? '')));
|
||||
const v = sorted.find(x => x.attributes?.platform === 'IOS') ?? sorted[0];
|
||||
return v ? { version: String(v.attributes?.versionString ?? ''), state: ASC_STATE(v), platform: v.attributes?.platform ?? null } : null;
|
||||
}
|
||||
|
||||
/** Every app a Play service account can see (all developer accounts that invited it), from the Reporting API. */
|
||||
export async function listPlayApps(get: Get, o: { icon?: (pkg: string) => Promise<string | null> } = {}): Promise<{ apps: StoreApp[]; warnings: string[] }> {
|
||||
const warnings: string[] = [];
|
||||
|
|
@ -92,7 +114,13 @@ export async function listPlayApps(get: Get, o: { icon?: (pkg: string) => Promis
|
|||
return { apps: apps.sort((x, y) => x.name.localeCompare(y.name)), warnings };
|
||||
}
|
||||
|
||||
const short = (e: unknown): string => String((e as Error)?.message ?? e).split('\n')[0]!.slice(0, 200);
|
||||
/** One readable line of an error: the API's own message (Google error.message, App Store Connect errors[].detail)
|
||||
* after the "GET ... -> 403" head when the body is JSON, else the first line. */
|
||||
const short = (e: unknown): string => {
|
||||
const m = String((e as Error)?.message ?? e);
|
||||
const api = /^(.*?-> \d{3}) .*?"(?:detail|message)":"((?:[^"\\]|\\.)*)"/.exec(m);
|
||||
return (api ? `${api[1]} ${api[2]!.replace(/\\(.)/g, '$1')}` : m.split('\n')[0]!).slice(0, 200);
|
||||
};
|
||||
const statusOf = (e: unknown): number | null => { const m = /-> (\d{3})\b/.exec(String((e as Error)?.message ?? e)); return m ? Number(m[1]) : null; };
|
||||
|
||||
export const ASC_KEYS_URL = 'https://appstoreconnect.apple.com/access/integrations/api';
|
||||
|
|
@ -127,16 +155,16 @@ export function playCheck(principal: string | null, outcome: { apps: number } |
|
|||
? { store: 'android', status: 'ok', principal, apps: outcome.apps, message: `The service account can see ${outcome.apps} app${outcome.apps === 1 ? '' : 's'}.`, fix: null, docs: null }
|
||||
: { store: 'android', status: 'permission', principal, apps: 0, message: 'The key works, but no developer account has invited this service account (it sees no apps).', fix: invite, docs: PLAY_USERS_URL };
|
||||
}
|
||||
const code = statusOf(outcome.error), msg = short(outcome.error);
|
||||
if (code === 403 && /SERVICE_DISABLED|has not been used|is disabled|accessNotConfigured/i.test(msg))
|
||||
const code = statusOf(outcome.error), msg = short(outcome.error), full = String((outcome.error as Error)?.message ?? outcome.error);
|
||||
if (code === 403 && /SERVICE_DISABLED|has not been used|is disabled|accessNotConfigured/i.test(full))
|
||||
return { store: 'android', status: 'api-disabled', principal, apps: null, message: 'The Google Play Developer Reporting API is off in this service account\'s Google Cloud project.',
|
||||
fix: 'Google Cloud console > APIs & Services > Library: enable "Google Play Developer Reporting API" (and "Google Play Android Developer API") in the service account\'s project, wait a few minutes, test again.', docs: REPORTING_API_URL };
|
||||
if (code === null && /invalid_grant|Invalid JWT|account not found|disabled/i.test(msg))
|
||||
if (code === null && /invalid_grant|Invalid JWT|account not found|disabled/i.test(full))
|
||||
return { store: 'android', status: 'revoked', principal, apps: null, message: `Google refused the key: ${msg}`,
|
||||
fix: 'The JSON key was deleted or the service account disabled. Google Cloud console > IAM & Admin > Service accounts > Keys: add a new JSON key, then add it here again.', docs: null };
|
||||
if (code === 403 || code === 401)
|
||||
return { store: 'android', status: 'permission', principal, apps: null, message: `The service account is missing a permission (${code}).`, fix: invite, docs: PLAY_USERS_URL };
|
||||
if (/not a Google service account|PLAY_SERVICE_ACCOUNT/i.test(msg))
|
||||
if (/not a Google service account|PLAY_SERVICE_ACCOUNT/i.test(full))
|
||||
return { store: 'android', status: 'error', principal, apps: null, message: msg, fix: 'Add the service account JSON key again (Google Cloud console > IAM & Admin > Service accounts > Keys > Add key > JSON).', docs: null };
|
||||
return { store: 'android', status: 'error', principal, apps: null, message: `Could not reach Google: ${msg}`, fix: 'Check the connection and try again.', docs: null };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@
|
|||
// https://developers.google.com/android-publisher/api-ref/rest/v3/monetization.subscriptions.basePlans.offers
|
||||
import type { IntroOffer, Language, OfferCodeDef, PriceOverride, Subscription, SubscriptionGroup, SubscriptionOfferDef, SubscriptionPeriod } from './config';
|
||||
import { playCodes } from './config';
|
||||
import { ALPHA3, type Money, toMoney } from './money';
|
||||
import { ALPHA3, fromMoney, type Money, toMoney } from './money';
|
||||
import type { PriceRow } from './prices';
|
||||
|
||||
// ---- mappings ----
|
||||
|
|
@ -428,7 +428,7 @@ export function playOfferBody(pkg: string, s: Subscription, regions: PlayRegionP
|
|||
};
|
||||
}
|
||||
|
||||
const moneyKey = (m?: Money): string => (m ? `${m.currencyCode} ${cents(Number(m.units) + (m.nanos ?? 0) / 1e9)}` : '-');
|
||||
const moneyKey = (m?: Money): string => (m ? `${m.currencyCode} ${cents(fromMoney(m))}` : '-');
|
||||
|
||||
export interface PlaySubDiff { create: boolean; listings: string[]; basePlan: 'new' | 'same' | 'changed'; priceChanges: { regionCode: string; from: string; to: string }[]; activate: boolean }
|
||||
|
||||
|
|
|
|||
|
|
@ -108,7 +108,15 @@ const EDITABLE = ['PREPARE_FOR_SUBMISSION', 'DEVELOPER_REJECTED', 'REJECTED', 'M
|
|||
const IN_FLIGHT = ['WAITING_FOR_REVIEW', 'IN_REVIEW', 'PENDING_DEVELOPER_RELEASE', 'PROCESSING_FOR_DISTRIBUTION', 'READY_FOR_DISTRIBUTION', 'READY_FOR_SALE', 'ACCEPTED'];
|
||||
const IAP_OK = ['READY_TO_SUBMIT', 'WAITING_FOR_REVIEW', 'IN_REVIEW', 'APPROVED'];
|
||||
/** Age rating questions whose null means "not answered" (kidsAgeBand null = not a kids app). */
|
||||
const AGE_OPTIONAL = new Set(['kidsAgeBand', 'ageRatingOverride', 'ageRatingOverrideV2', 'koreaAgeRatingOverride', 'developerAgeRatingInfoUrl']);
|
||||
// Left null on apps App Review accepted: gracRatingClassificationNumber (a Korean GRAC rating number, for apps GRAC
|
||||
// rated), socialMediaAgeRestricted (asked only when socialMedia is true). socialMedia itself is a newer question that
|
||||
// App Store Connect let submissions through without: a warning, not a blocker.
|
||||
const AGE_OPTIONAL = new Set(['kidsAgeBand', 'ageRatingOverride', 'ageRatingOverrideV2', 'koreaAgeRatingOverride', 'developerAgeRatingInfoUrl', 'gracRatingClassificationNumber']);
|
||||
const AGE_SOFT = new Set(['socialMedia']);
|
||||
const ageOpen = (r: Record<string, unknown>): { open: string[]; soft: string[] } => {
|
||||
const unset = Object.entries(r).filter(([k, v]) => v === null && !AGE_OPTIONAL.has(k) && !(k === 'socialMediaAgeRestricted' && r.socialMedia !== true)).map(([k]) => k);
|
||||
return { open: unset.filter(k => !AGE_SOFT.has(k)), soft: unset.filter(k => AGE_SOFT.has(k)) };
|
||||
};
|
||||
|
||||
const urlOk = (u: UrlCheck) => u.status !== null && u.status >= 200 && u.status < 300;
|
||||
const urlMsg = (u: UrlCheck) => (u.status === null ? `unreachable (${u.error ?? 'no answer'})` : `HTTP ${u.status}`);
|
||||
|
|
@ -154,9 +162,10 @@ export function appleRules(s: AppleSnapshot): Finding[] {
|
|||
|
||||
if (!s.ageRating) add('blocker', 'age-rating', 'age rating declaration not readable / missing', 'storebound apple appinfo');
|
||||
else {
|
||||
const open = Object.entries(s.ageRating).filter(([k, v]) => v === null && !AGE_OPTIONAL.has(k)).map(([k]) => k);
|
||||
const { open, soft } = ageOpen(s.ageRating);
|
||||
if (open.length) add('blocker', 'age-rating', `age rating unanswered: ${open.join(', ')}`, 'storebound apple appinfo');
|
||||
else add('ok', 'age-rating', 'age rating answered');
|
||||
if (soft.length) add('warn', 'age-rating', `age rating question not answered yet: ${soft.join(', ')} (App Store Connect > App Information > Age Rating)`);
|
||||
}
|
||||
add(s.priceSchedule ? 'ok' : 'blocker', 'price', s.priceSchedule ? 'app price set' : 'no app price schedule', 'storebound apple appinfo');
|
||||
add(s.availability ? 'ok' : 'blocker', 'availability', s.availability ? 'availability set' : 'no territory availability',
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
import { playServiceAccount } from '../lib/credentials';
|
||||
import { tokenSource } from '../lib/google-auth';
|
||||
import { log } from '../lib/log';
|
||||
import { errorBody } from '../lib/http';
|
||||
|
||||
export type PlayClient = Awaited<ReturnType<typeof playClient>>;
|
||||
|
||||
|
|
@ -24,7 +25,7 @@ export async function playClient(root: string, packageName: string) {
|
|||
if ((r.status === 429 || r.status >= 500) && attempt < 4) { await Bun.sleep(2000 * (attempt + 1)); continue; }
|
||||
const short = url.replace(API, '').replace(UPLOAD, '');
|
||||
// A wrong path casing answers with an HTML 404 page, not JSON: say so instead of dumping the HTML.
|
||||
const msg = /^\s*</.test(text) ? `(HTML ${r.status} page: wrong path or casing?)` : text.slice(0, 1500);
|
||||
const msg = /^\s*</.test(text) ? `(HTML ${r.status} page: wrong path or casing?)` : errorBody(text);
|
||||
throw new Error(`${method} ${short} -> ${r.status} ${msg}`);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
// Reporting API (vitals) and Cloud Storage (Play statistics exports). Read-only callers; retries 429 / 5xx.
|
||||
import { playServiceAccount } from '../lib/credentials';
|
||||
import { tokenSource } from '../lib/google-auth';
|
||||
import { errorBody } from '../lib/http';
|
||||
|
||||
export const REPORTING_API = 'https://playdeveloperreporting.googleapis.com/v1beta1';
|
||||
|
||||
|
|
@ -19,12 +20,12 @@ export function googleClient(root: string, scope: string) {
|
|||
async json<T = unknown>(method: string, url: string, body?: unknown): Promise<T> {
|
||||
const r = await send(method, url, body);
|
||||
const t = await r.text();
|
||||
if (!r.ok) throw new Error(`${method} ${url.replace(/^https:\/\/[^/]+/, '')} -> ${r.status} ${/^\s*</.test(t) ? '(HTML error page)' : t.slice(0, 800)}`);
|
||||
if (!r.ok) throw new Error(`${method} ${url.replace(/^https:\/\/[^/]+/, '')} -> ${r.status} ${errorBody(t, 800)}`);
|
||||
return (t ? JSON.parse(t) : {}) as T;
|
||||
},
|
||||
async bytes(url: string): Promise<Uint8Array> {
|
||||
const r = await send('GET', url);
|
||||
if (!r.ok) throw new Error(`GET ${url.replace(/^https:\/\/[^/]+/, '')} -> ${r.status} ${(await r.text()).slice(0, 300)}`);
|
||||
if (!r.ok) throw new Error(`GET ${url.replace(/^https:\/\/[^/]+/, '')} -> ${r.status} ${errorBody(await r.text(), 300)}`);
|
||||
return new Uint8Array(await r.arrayBuffer());
|
||||
},
|
||||
};
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue