CLI: storebound apps list | check (apps on a store account, account health with fixes); serve apps.list, account.check and store-only apps through a generated config
This commit is contained in:
parent
0ce0c51ff6
commit
53f9e6dd75
6 changed files with 697 additions and 13 deletions
145
cli/apps.ts
Normal file
145
cli/apps.ts
Normal file
|
|
@ -0,0 +1,145 @@
|
||||||
|
// The apps on a store account, and whether the account's key works. No storebound.config.ts needed: credentials come
|
||||||
|
// from the environment or .storebound/credentials.json of the current folder (the desktop app passes one account's
|
||||||
|
// key per call). Read-only.
|
||||||
|
// storebound apps list [--store apple|play] [--icons] [--json] every app the key can see (App Store Connect team /
|
||||||
|
// every Play developer account that invited the
|
||||||
|
// service account)
|
||||||
|
// storebound apps check [--store apple|play] [--json] auth OK / permission missing / key revoked, with the fix
|
||||||
|
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 { 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';
|
||||||
|
import { ascClient } from './apple/asc';
|
||||||
|
import { REPORTING_API } from './play/google';
|
||||||
|
|
||||||
|
type Store = 'apple' | 'play';
|
||||||
|
|
||||||
|
function stores(args: Args, root: string): Store[] {
|
||||||
|
const s = args.get('store');
|
||||||
|
if (s === 'apple' || s === 'play') return [s];
|
||||||
|
if (s !== undefined) throw new Error('--store: apple or play');
|
||||||
|
// every store whose credentials are set (env, or .storebound/credentials.json in this folder)
|
||||||
|
const out: Store[] = [];
|
||||||
|
try { ascKey(root); out.push('apple'); } catch { /* not set */ }
|
||||||
|
try { playServiceAccount(root); out.push('play'); } catch { /* not set */ }
|
||||||
|
if (!out.length) throw new Error('no store credentials: set ASC_KEY_ID + ASC_ISSUER_ID + ASC_P8 and / or PLAY_SERVICE_ACCOUNT (env or .storebound/credentials.json)');
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
const bytes: Bytes = async url => {
|
||||||
|
const r = await fetch(url);
|
||||||
|
if (!r.ok) return null;
|
||||||
|
const len = Number(r.headers.get('content-length') ?? 0);
|
||||||
|
if (len > MAX_ICON_BYTES) { await r.body?.cancel(); return null; }
|
||||||
|
return { type: (r.headers.get('content-type') ?? 'image/png').split(';')[0]!, data: new Uint8Array(await r.arrayBuffer()) };
|
||||||
|
};
|
||||||
|
|
||||||
|
async function appleGet(root: string): Promise<Get> {
|
||||||
|
const c = await ascClient(root, '');
|
||||||
|
return path => c.asc('GET', path);
|
||||||
|
}
|
||||||
|
|
||||||
|
function googleGet(token: () => Promise<string>, base: string): Get {
|
||||||
|
return async path => {
|
||||||
|
for (let attempt = 0; ; attempt++) {
|
||||||
|
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)}`);
|
||||||
|
return t ? JSON.parse(t) : {};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Play icon of one package: an edit is opened, the default language's icon listed, and the edit deleted (never committed). */
|
||||||
|
function playIcon(root: string): (pkg: string) => Promise<string | null> {
|
||||||
|
const token = tokenSource(playServiceAccount(root), PLAY_SCOPE);
|
||||||
|
const API = 'https://androidpublisher.googleapis.com/androidpublisher/v3/applications/';
|
||||||
|
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)}`);
|
||||||
|
return t ? JSON.parse(t) : {};
|
||||||
|
};
|
||||||
|
return async pkg => {
|
||||||
|
const base = API + encodeURIComponent(pkg);
|
||||||
|
const edit = await call('POST', `${base}/edits`);
|
||||||
|
try {
|
||||||
|
const details = await call('GET', `${base}/edits/${edit.id}/details`);
|
||||||
|
const lang = details.defaultLanguage ?? 'en-US';
|
||||||
|
const imgs = await call('GET', `${base}/edits/${edit.id}/listings/${encodeURIComponent(lang)}/icon`);
|
||||||
|
const url = imgs.images?.[0]?.url;
|
||||||
|
if (typeof url !== 'string' || !/^https:\/\/[^/]+\.googleusercontent\.com\//.test(url)) return null;
|
||||||
|
const img = await bytes(`${url}=s128`);
|
||||||
|
return img && img.data.length <= MAX_ICON_BYTES ? dataUrl(img.type, img.data) : null;
|
||||||
|
} finally {
|
||||||
|
await call('DELETE', `${base}/edits/${edit.id}`).catch(() => {});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listApps(store: Store, root: string, icons: boolean): Promise<AppsListResult> {
|
||||||
|
const at = new Date().toISOString();
|
||||||
|
if (store === 'apple') {
|
||||||
|
const r = await listAppleApps(await appleGet(root), { icons, bytes });
|
||||||
|
return { store: 'ios', ...r, at };
|
||||||
|
}
|
||||||
|
const sa = playServiceAccount(root);
|
||||||
|
const r = await listPlayApps(googleGet(tokenSource(sa, REPORTING_SCOPE), REPORTING_API), icons ? { icon: playIcon(root) } : {});
|
||||||
|
return { store: 'android', ...r, at };
|
||||||
|
}
|
||||||
|
|
||||||
|
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 });
|
||||||
|
} catch (e) { return appleCheck({ error: e }); }
|
||||||
|
}
|
||||||
|
let principal: string | null = null;
|
||||||
|
try {
|
||||||
|
const sa = playServiceAccount(root);
|
||||||
|
principal = sa.client_email;
|
||||||
|
const page = await googleGet(tokenSource(sa, REPORTING_SCOPE), REPORTING_API)('/apps:search?pageSize=1000');
|
||||||
|
return playCheck(principal, { apps: (page.apps ?? []).length });
|
||||||
|
} catch (e) { return playCheck(principal, { error: e }); }
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function run(args: Args): Promise<void> {
|
||||||
|
const sub = args._[0];
|
||||||
|
const root = process.cwd();
|
||||||
|
const json = args.has('json');
|
||||||
|
if (sub === 'list') {
|
||||||
|
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]}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (json) { printJson(args.get('store') ? out[0] : out); return; }
|
||||||
|
for (const r of out) {
|
||||||
|
log('apps', `${r.store === 'ios' ? 'App Store Connect' : 'Google Play'}: ${r.apps.length} apps`);
|
||||||
|
console.log(textTable(['name', 'id', 'bundle / package', 'platforms', 'newest'], r.apps.map(a => [a.name, a.id, a.bundleId, a.platforms.join(' '), a.latest ? `${a.latest.version} ${a.latest.state}` : ''])));
|
||||||
|
for (const w of r.warnings) warn('apps', w);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (sub === 'check') {
|
||||||
|
const out: AccountCheck[] = [];
|
||||||
|
for (const s of stores(args, root)) out.push(await checkAccount(s, root));
|
||||||
|
if (json) { printJson(args.get('store') ? out[0] : out); return; }
|
||||||
|
for (const c of out) {
|
||||||
|
log('apps', `${c.store === 'ios' ? 'App Store Connect' : 'Google Play'}: ${c.status} · ${c.message}`);
|
||||||
|
if (c.fix) console.log(` fix: ${c.fix}`);
|
||||||
|
if (c.docs) console.log(` ${c.docs}`);
|
||||||
|
}
|
||||||
|
if (out.some(c => c.status !== 'ok')) process.exitCode = 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.error('usage: storebound apps list [--store apple|play] [--icons] [--json] | apps check [--store apple|play] [--json]');
|
||||||
|
process.exit(2);
|
||||||
|
}
|
||||||
|
|
@ -13,6 +13,7 @@ const PLAIN: Record<string, [() => Promise<Plain>, string]> = {
|
||||||
'install': [() => import('./install'), 'skills + MCP server for --agent claude|codex|cursor|copilot|windsurf|gemini|opencode'],
|
'install': [() => import('./install'), 'skills + MCP server for --agent claude|codex|cursor|copilot|windsurf|gemini|opencode'],
|
||||||
'mcp': [async () => ({ run: async () => (await import('./mcp')).serve() }), 'stdio MCP server wrapping these commands (for any MCP-capable AI tool)'],
|
'mcp': [async () => ({ run: async () => (await import('./mcp')).serve() }), 'stdio MCP server wrapping these commands (for any MCP-capable AI tool)'],
|
||||||
'serve': [() => import('./serve'), '--stdio: JSON-RPC session for the storebound desktop app (dry runs; writes need a host confirm token)'],
|
'serve': [() => import('./serve'), '--stdio: JSON-RPC session for the storebound desktop app (dry runs; writes need a host confirm token)'],
|
||||||
|
'apps': [() => import('./apps'), 'list (every app the store keys can see: App Store Connect team, Play developer accounts; --icons) | check (key works / permission missing / revoked, with the fix); --store apple|play, --json; read-only'],
|
||||||
'doctor': [() => import('./doctor'), 'local tools for screenshots, previews, icons and captures (ffmpeg, Chrome, playwright, Xcode, adb, git) and how to install what is missing; --json'],
|
'doctor': [() => import('./doctor'), 'local tools for screenshots, previews, icons and captures (ffmpeg, Chrome, playwright, Xcode, adb, git) and how to install what is missing; --json'],
|
||||||
'privacy-manifest': [() => import('./privacy-manifest'), 'iOS PrivacyInfo.xcprivacy + required-reason API + SDK manifest scan (--ios <path>)'],
|
'privacy-manifest': [() => import('./privacy-manifest'), 'iOS PrivacyInfo.xcprivacy + required-reason API + SDK manifest scan (--ios <path>)'],
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -29,7 +29,7 @@ export interface MethodDescriptor {
|
||||||
method: string;
|
method: string;
|
||||||
title: string;
|
title: string;
|
||||||
description: string;
|
description: string;
|
||||||
kind: 'read' | 'write' | 'session' | 'system' | 'portfolio';
|
kind: 'read' | 'write' | 'session' | 'system' | 'portfolio' | 'account';
|
||||||
/** Talks to a store API or the internet. */
|
/** Talks to a store API or the internet. */
|
||||||
network: boolean;
|
network: boolean;
|
||||||
/** Replaces existing data on a store (screenshots, whole forms). */
|
/** Replaces existing data on a store (screenshots, whole forms). */
|
||||||
|
|
@ -154,6 +154,8 @@ export interface AppStatus {
|
||||||
/** Release trains; `source: none` offline (no store data read). `all`: every store release read (live only). */
|
/** Release trains; `source: none` offline (no store data read). `all`: every store release read (live only). */
|
||||||
release: { source: 'none' | 'live'; current: ReleaseTrain | null; next: ReleaseTrain | null; all?: StoreRelease[] };
|
release: { source: 'none' | 'live'; current: ReleaseTrain | null; next: ReleaseTrain | null; all?: StoreRelease[] };
|
||||||
catalog: CatalogParity | null;
|
catalog: CatalogParity | null;
|
||||||
|
/** A store-only app read through a generated config (no app folder). */
|
||||||
|
virtual?: boolean;
|
||||||
/** live only: per-platform read errors ("unknown, never false"). */
|
/** live only: per-platform read errors ("unknown, never false"). */
|
||||||
storeErrors: { ios?: string; android?: string };
|
storeErrors: { ios?: string; android?: string };
|
||||||
errors: string[];
|
errors: string[];
|
||||||
|
|
@ -204,3 +206,44 @@ export interface DraftsResult { dir: string; drafts: ReplyDraft[]; problems: str
|
||||||
|
|
||||||
/** project.icon: the icon as a data: URL (PNG / JPEG / WebP / SVG, at most 1.5 MB), or null. */
|
/** project.icon: the icon as a data: URL (PNG / JPEG / WebP / SVG, at most 1.5 MB), or null. */
|
||||||
export interface IconResult { path: string | null; dataUrl: string | null }
|
export interface IconResult { path: string | null; dataUrl: string | null }
|
||||||
|
|
||||||
|
// ---- Store accounts and the apps on them (D3: many studios, many accounts) ----
|
||||||
|
|
||||||
|
/** One app record on a store, as `storebound apps list` reads it. */
|
||||||
|
export interface StoreApp {
|
||||||
|
store: 'ios' | 'android';
|
||||||
|
/** App Store Connect app id (numeric) / Play package name. */
|
||||||
|
id: string;
|
||||||
|
/** iOS bundle id / Android package name. */
|
||||||
|
bundleId: string;
|
||||||
|
name: string;
|
||||||
|
/** App Store version platforms (IOS, MAC_OS, TV_OS, VISION_OS); ["ANDROID"] on Play. */
|
||||||
|
platforms: string[];
|
||||||
|
sku?: string | null;
|
||||||
|
primaryLocale?: string | null;
|
||||||
|
/** Newest App Store version and its state (App Store only). */
|
||||||
|
latest?: { version: string; state: string; platform?: string | null } | null;
|
||||||
|
/** 128 px icon as a data: URL (with --icons), else null. */
|
||||||
|
icon?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AppsListResult { store: 'ios' | 'android'; apps: StoreApp[]; warnings: string[]; at: string }
|
||||||
|
|
||||||
|
/** Health of one store account: does the key work, and can it see apps. */
|
||||||
|
export interface AccountCheck {
|
||||||
|
store: 'ios' | 'android';
|
||||||
|
status: 'ok' | 'no-apps' | 'permission' | 'revoked' | 'api-disabled' | 'error';
|
||||||
|
/** Play: the service account email (to invite in Play Console). Never a secret. */
|
||||||
|
principal: string | null;
|
||||||
|
apps: number | null;
|
||||||
|
message: string;
|
||||||
|
/** What to do, in words. */
|
||||||
|
fix: string | null;
|
||||||
|
docs: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A store-only app (no app folder yet): the sidecar reads it through a generated minimal config (store ids only) in
|
||||||
|
* its temp folder. Read methods only.
|
||||||
|
*/
|
||||||
|
export interface VirtualProject { name: string; apple?: { bundleId: string; appId?: string | null } | null; play?: { packageName: string } | null }
|
||||||
|
|
|
||||||
142
cli/lib/store-apps.ts
Normal file
142
cli/lib/store-apps.ts
Normal file
|
|
@ -0,0 +1,142 @@
|
||||||
|
// Store-side app lists and account health, for `storebound apps list | check` and the desktop's "import from the
|
||||||
|
// stores". Pure over an injected HTTP getter, so tests run on recorded responses. Read-only: GET requests only, plus
|
||||||
|
// (Play icons, opt-in) an edit that is opened and deleted without a commit.
|
||||||
|
//
|
||||||
|
// App Store Connect: GET /v1/apps (paged), the newest appStoreVersions per app (platform, version, state) and, with
|
||||||
|
// icons, the newest build's iconAssetToken (an image template on Apple's CDN, fetched here and returned as a data URL:
|
||||||
|
// the desktop window loads no remote content).
|
||||||
|
// https://developer.apple.com/documentation/appstoreconnectapi/list_apps
|
||||||
|
// https://developer.apple.com/documentation/appstoreconnectapi/build (attribute iconAssetToken)
|
||||||
|
// Google Play: the Play Developer Reporting API `apps:search` lists every app the service account can see, across all
|
||||||
|
// developer accounts it was invited to.
|
||||||
|
// https://developers.google.com/play/developer/reporting/reference/rest/v1beta1/apps/search
|
||||||
|
import type { AccountCheck, StoreApp } from './desktop-protocol';
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
type J = any;
|
||||||
|
|
||||||
|
/** GET a JSON path (ASC: relative to the API root, or a full `links.next` URL). Throws Error("... -> <status> <body>"). */
|
||||||
|
export type Get = (path: string) => Promise<J>;
|
||||||
|
/** Bytes of an image URL (icons). */
|
||||||
|
export type Bytes = (url: string) => Promise<{ type: string; data: Uint8Array } | null>;
|
||||||
|
|
||||||
|
/** Largest icon kept as a data URL; bigger ones are dropped (the window shows a monogram instead). */
|
||||||
|
export const MAX_ICON_BYTES = 200_000;
|
||||||
|
|
||||||
|
export const dataUrl = (type: string, data: Uint8Array): string => `data:${type};base64,${Buffer.from(data).toString('base64')}`;
|
||||||
|
|
||||||
|
/** ASC iconAssetToken.templateUrl -> a 128 px PNG URL. */
|
||||||
|
export const iconUrl = (templateUrl: string, px = 128): string =>
|
||||||
|
templateUrl.replace('{w}', String(px)).replace('{h}', String(px)).replace('{c}', 'bb').replace('{f}', 'png');
|
||||||
|
|
||||||
|
const ASC_STATE = (v: J): string => v?.attributes?.appVersionState ?? v?.attributes?.appStoreState ?? '';
|
||||||
|
|
||||||
|
/** Every App Store Connect app the key's team can see, with platforms, newest version and (opt-in) icon. */
|
||||||
|
export async function listAppleApps(get: Get, o: { icons?: boolean; bytes?: Bytes; limit?: number } = {}): Promise<{ apps: StoreApp[]; warnings: string[] }> {
|
||||||
|
const warnings: string[] = [];
|
||||||
|
const raw: J[] = [];
|
||||||
|
let url: string | null = '/v1/apps?fields[apps]=name,bundleId,sku,primaryLocale&limit=200';
|
||||||
|
while (url && raw.length < (o.limit ?? 1000)) {
|
||||||
|
const page: J = await get(url);
|
||||||
|
raw.push(...(page.data ?? []));
|
||||||
|
url = page.links?.next ?? null;
|
||||||
|
}
|
||||||
|
const apps: StoreApp[] = [];
|
||||||
|
for (const a of raw) {
|
||||||
|
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.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)})`); }
|
||||||
|
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];
|
||||||
|
const tpl = b?.attributes?.iconAssetToken?.templateUrl;
|
||||||
|
if (typeof tpl === 'string' && /^https:\/\/[^/]+\.mzstatic\.com\//.test(tpl)) {
|
||||||
|
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)})`); }
|
||||||
|
}
|
||||||
|
apps.push(app);
|
||||||
|
}
|
||||||
|
return { apps: apps.sort((x, y) => x.name.localeCompare(y.name)), warnings };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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[] = [];
|
||||||
|
const raw: J[] = [];
|
||||||
|
let token = '';
|
||||||
|
for (let i = 0; i < 50; i++) {
|
||||||
|
const page: J = await get(`/apps:search?pageSize=1000${token ? `&pageToken=${encodeURIComponent(token)}` : ''}`);
|
||||||
|
raw.push(...(page.apps ?? []));
|
||||||
|
token = page.nextPageToken ?? '';
|
||||||
|
if (!token) break;
|
||||||
|
}
|
||||||
|
const apps: StoreApp[] = [];
|
||||||
|
for (const a of raw) {
|
||||||
|
const pkg = String(a.packageName ?? String(a.name ?? '').replace(/^apps\//, ''));
|
||||||
|
if (!pkg) continue;
|
||||||
|
const app: StoreApp = { store: 'android', id: pkg, bundleId: pkg, name: String(a.displayName || pkg), platforms: ['ANDROID'], sku: null, primaryLocale: null, latest: null, icon: null };
|
||||||
|
if (o.icon) {
|
||||||
|
try { app.icon = await o.icon(pkg); } catch (e) { warnings.push(`${pkg}: icon not read (${short(e)})`); }
|
||||||
|
}
|
||||||
|
apps.push(app);
|
||||||
|
}
|
||||||
|
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);
|
||||||
|
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';
|
||||||
|
export const PLAY_USERS_URL = 'https://play.google.com/console/developers/users-and-permissions';
|
||||||
|
export const REPORTING_API_URL = 'https://console.cloud.google.com/apis/library/playdeveloperreporting.googleapis.com';
|
||||||
|
|
||||||
|
/** App Store Connect key health from a GET /v1/apps?limit=1 outcome. */
|
||||||
|
export function appleCheck(outcome: { apps: number } | { error: unknown }): AccountCheck {
|
||||||
|
if ('apps' in outcome) {
|
||||||
|
return outcome.apps > 0
|
||||||
|
? { store: 'ios', status: 'ok', principal: null, apps: outcome.apps, message: 'The key works and can read the team\'s apps.', fix: null, docs: null }
|
||||||
|
: { store: 'ios', status: 'no-apps', principal: null, apps: 0, message: 'The key works, but the team has no apps it can see.', fix: 'Create the app record in App Store Connect (Apps > + > New App), or check that this is the team you meant.', docs: null };
|
||||||
|
}
|
||||||
|
const code = statusOf(outcome.error), msg = short(outcome.error);
|
||||||
|
if (/not set|not found|PRIVATE KEY|asn1|decoder|key/i.test(msg) && code === null)
|
||||||
|
return { store: 'ios', status: 'error', principal: null, apps: null, message: `The key could not be used: ${msg}`, fix: 'Add the key again: key id, issuer id and the AuthKey_<id>.p8 file from App Store Connect.', docs: ASC_KEYS_URL };
|
||||||
|
if (code === 401)
|
||||||
|
return { store: 'ios', status: 'revoked', principal: null, apps: null, message: 'App Store Connect refused the key (401): it was revoked, or the key id / issuer id do not belong to this .p8.',
|
||||||
|
fix: 'Users and Access > Integrations > App Store Connect API: check the key is still active, or generate a new one (role App Manager or Admin) and add it here again.', docs: ASC_KEYS_URL };
|
||||||
|
if (code === 403)
|
||||||
|
return { store: 'ios', status: 'permission', principal: null, apps: null, message: 'The key works but its role may not read apps (403).',
|
||||||
|
fix: 'Use a team key with the App Manager or Admin role (Users and Access > Integrations > App Store Connect API), or ask the Account Holder for one.', docs: ASC_KEYS_URL };
|
||||||
|
return { store: 'ios', status: 'error', principal: null, apps: null, message: `Could not reach App Store Connect: ${msg}`, fix: 'Check the connection and try again.', docs: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Play service account health from the token exchange and an `apps:search` outcome. */
|
||||||
|
export function playCheck(principal: string | null, outcome: { apps: number } | { error: unknown }): AccountCheck {
|
||||||
|
const who = principal ?? 'the service account';
|
||||||
|
const invite = `Play Console > Users and permissions > Invite new users: add ${who}. Account permissions: "View app information and download bulk reports (read-only)"; per app, as needed: "Manage store presence", "Manage testing tracks", "Release to production, exclude devices and use Play App Signing" (rollouts), "Reply to reviews", "Manage orders and subscriptions". One service account can be invited to several developer accounts.`;
|
||||||
|
if ('apps' in outcome) {
|
||||||
|
return outcome.apps > 0
|
||||||
|
? { 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))
|
||||||
|
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))
|
||||||
|
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))
|
||||||
|
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 };
|
||||||
|
}
|
||||||
115
cli/serve.ts
115
cli/serve.ts
|
|
@ -9,13 +9,15 @@
|
||||||
// - writes that are dry runs unless the host sends a confirm token (lib/confirm-token.ts) it minted after the owner
|
// - writes that are dry runs unless the host sends a confirm token (lib/confirm-token.ts) it minted after the owner
|
||||||
// confirmed a native dialog showing that dry run.
|
// confirmed a native dialog showing that dry run.
|
||||||
// Nothing here submits for review, releases or publishes: those methods do not exist (tests/serve.test.ts).
|
// Nothing here submits for review, releases or publishes: those methods do not exist (tests/serve.test.ts).
|
||||||
import { existsSync, statSync } from 'node:fs';
|
import { createHash } from 'node:crypto';
|
||||||
|
import { existsSync, mkdirSync, mkdtempSync, statSync, writeFileSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
import { isAbsolute, join, resolve } from 'node:path';
|
import { isAbsolute, join, resolve } from 'node:path';
|
||||||
import pkg from '../package.json' with { type: 'json' };
|
import pkg from '../package.json' with { type: 'json' };
|
||||||
import { parseSecret, TokenGuard } from './lib/confirm-token';
|
import { canonical, parseSecret, TokenGuard } from './lib/confirm-token';
|
||||||
import { CONFIG_NAMES } from './lib/config';
|
import { CONFIG_NAMES } from './lib/config';
|
||||||
import {
|
import {
|
||||||
DESKTOP_PROTOCOL, ERR, type AppStatus, type MethodDescriptor, type PortfolioResult, type ProjectSummary, type ToolResult,
|
DESKTOP_PROTOCOL, ERR, type AppStatus, type MethodDescriptor, type PortfolioResult, type ProjectSummary, type ToolResult, type VirtualProject,
|
||||||
} from './lib/desktop-protocol';
|
} from './lib/desktop-protocol';
|
||||||
import { appIdentity, appleProductIds, appleReleases, catalogParity, playProductIds, playReleases, releaseTrains } from './lib/portfolio';
|
import { appIdentity, appleProductIds, appleReleases, catalogParity, playProductIds, playReleases, releaseTrains } from './lib/portfolio';
|
||||||
import { detectTools } from './lib/tools';
|
import { detectTools } from './lib/tools';
|
||||||
|
|
@ -86,10 +88,20 @@ const SYSTEM: MethodDescriptor[] = [
|
||||||
{ method: 'system.tools', title: 'Local tools', description: 'Optional local tools with versions and where they come from (ffmpeg, ffprobe, Chrome, Xcode / simctl, adb, git); screenshot, video and capture features need them.', kind: 'system', network: false, destructive: false, json: true, args: obj({}) },
|
{ method: 'system.tools', title: 'Local tools', description: 'Optional local tools with versions and where they come from (ffmpeg, ffprobe, Chrome, Xcode / simctl, adb, git); screenshot, video and capture features need them.', kind: 'system', network: false, destructive: false, json: true, args: obj({}) },
|
||||||
{ method: 'project.inspect', title: 'Inspect a project', description: 'Offline summary of a folder\'s storebound.config.ts (name, store ids, languages, products).', kind: 'read', network: false, destructive: false, json: true,
|
{ method: 'project.inspect', title: 'Inspect a project', description: 'Offline summary of a folder\'s storebound.config.ts (name, store ids, languages, products).', kind: 'read', network: false, destructive: false, json: true,
|
||||||
args: obj({ project: { type: 'string', description: 'Absolute folder path' } }, ['project']) },
|
args: obj({ project: { type: 'string', description: 'Absolute folder path' } }, ['project']) },
|
||||||
|
{ method: 'apps.list', title: 'Apps on a store account', description: 'Every app one store account can see (App Store Connect team: GET /v1/apps with platforms and the newest version; Google Play: Reporting API apps:search over every developer account that invited the service account), optional 128 px icons. Credentials of exactly one account in params.credentials. Read-only.', kind: 'account', network: true, destructive: false, json: true,
|
||||||
|
args: obj({ credentials: { type: 'object' }, args: { type: 'object' } }, ['credentials']) },
|
||||||
|
{ method: 'account.check', title: 'Check a store account', description: 'Does the key work, and can it see apps: ok, no-apps, permission (with the Play Console / App Store Connect fix), revoked, api-disabled. Read-only.', kind: 'account', network: true, destructive: false, json: true,
|
||||||
|
args: obj({ credentials: { type: 'object' } }, ['credentials']) },
|
||||||
{ method: 'portfolio.status', title: 'Portfolio status', description: 'Apps (one per project folder) across iOS and Android: identity, offline config check, catalog parity; with live, release trains (current / next version on both stores) and live catalog parity from App Store and Google Play status (read-only).', kind: 'portfolio', network: true, destructive: false, json: true,
|
{ method: 'portfolio.status', title: 'Portfolio status', description: 'Apps (one per project folder) across iOS and Android: identity, offline config check, catalog parity; with live, release trains (current / next version on both stores) and live catalog parity from App Store and Google Play status (read-only).', kind: 'portfolio', network: true, destructive: false, json: true,
|
||||||
args: obj({ projects: { type: 'array' }, live: { type: 'boolean', default: false } }, ['projects']) },
|
args: obj({ projects: { type: 'array' }, live: { type: 'boolean', default: false } }, ['projects']) },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/** Read methods a store-only app (params.virtual, no app folder) may use: store reads that need only the store ids. */
|
||||||
|
export const VIRTUAL_READS = new Set(['apple_status', 'play_status', 'health', 'reviews_list', 'apple_testflight_status', 'apple_ppo_status']);
|
||||||
|
|
||||||
|
const PKG_RE = /^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)+$/;
|
||||||
|
const BUNDLE_RE = /^[A-Za-z0-9][A-Za-z0-9.-]{0,154}$/;
|
||||||
|
|
||||||
export function describeMethods(): MethodDescriptor[] {
|
export function describeMethods(): MethodDescriptor[] {
|
||||||
return [...SYSTEM, ...DESKTOP_TOOLS.map(t => ({
|
return [...SYSTEM, ...DESKTOP_TOOLS.map(t => ({
|
||||||
method: methodName(t.name), title: t.title, description: t.description, kind: t.write ? 'write' as const : 'read' as const,
|
method: methodName(t.name), title: t.title, description: t.description, kind: t.write ? 'write' as const : 'read' as const,
|
||||||
|
|
@ -113,6 +125,55 @@ export function checkProject(p: unknown): string {
|
||||||
return dir;
|
return dir;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Checks a params.virtual object (store ids only). */
|
||||||
|
export function checkVirtual(v: unknown): VirtualProject {
|
||||||
|
if (typeof v !== 'object' || v === null || Array.isArray(v)) throw new RpcError(ERR.invalidParams, 'virtual: object expected');
|
||||||
|
const o = v as Record<string, unknown>;
|
||||||
|
for (const k of Object.keys(o)) if (!['name', 'apple', 'play'].includes(k)) throw new RpcError(ERR.invalidParams, `virtual.${k}: unknown`);
|
||||||
|
const name = typeof o.name === 'string' && o.name.trim() && o.name.length <= 120 ? o.name.trim() : null;
|
||||||
|
if (!name) throw new RpcError(ERR.invalidParams, 'virtual.name: 1-120 characters');
|
||||||
|
const a = o.apple as Record<string, unknown> | null | undefined, p = o.play as Record<string, unknown> | null | undefined;
|
||||||
|
if (!a && !p) throw new RpcError(ERR.invalidParams, 'virtual: apple and / or play');
|
||||||
|
const out: VirtualProject = { name };
|
||||||
|
if (a) {
|
||||||
|
if (typeof a.bundleId !== 'string' || !BUNDLE_RE.test(a.bundleId) || !a.bundleId.includes('.')) throw new RpcError(ERR.invalidParams, 'virtual.apple.bundleId: a bundle id');
|
||||||
|
if (a.appId !== undefined && a.appId !== null && (typeof a.appId !== 'string' || !/^\d{1,20}$/.test(a.appId))) throw new RpcError(ERR.invalidParams, 'virtual.apple.appId: digits');
|
||||||
|
out.apple = { bundleId: a.bundleId, appId: (a.appId as string | null | undefined) ?? null };
|
||||||
|
}
|
||||||
|
if (p) {
|
||||||
|
if (typeof p.packageName !== 'string' || !PKG_RE.test(p.packageName)) throw new RpcError(ERR.invalidParams, 'virtual.play.packageName: a package name');
|
||||||
|
out.play = { packageName: p.packageName };
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The minimal config of a store-only app (store ids, placeholder links), as storebound.config.json. */
|
||||||
|
export function virtualConfig(v: VirtualProject): Record<string, unknown> {
|
||||||
|
return {
|
||||||
|
app: { name: v.name, privacyPolicyUrl: 'https://example.com/privacy', supportUrl: 'https://example.com/support', website: 'https://example.com/',
|
||||||
|
contactEmail: 'store-only@example.com', platforms: [...(v.apple ? ['ios'] : []), ...(v.play ? ['android'] : [])] },
|
||||||
|
languages: [{ id: 'en', play: 'en-US', apple: 'en-US' }],
|
||||||
|
...(v.apple ? { apple: { bundleId: v.apple.bundleId, ...(v.apple.appId ? { appId: v.apple.appId } : {}) } } : {}),
|
||||||
|
...(v.play ? { play: { packageName: v.play.packageName } } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let virtualRoot: string | null = null;
|
||||||
|
/** A folder (in this session's temp folder) holding the generated config of a store-only app. */
|
||||||
|
export function virtualDir(v: VirtualProject): string {
|
||||||
|
virtualRoot ??= mkdtempSync(join(tmpdir(), 'storebound-virtual-'));
|
||||||
|
const dir = join(virtualRoot, createHash('sha256').update(canonical(v as unknown as Record<string, unknown>)).digest('hex').slice(0, 20));
|
||||||
|
if (!existsSync(join(dir, 'storebound.config.json'))) {
|
||||||
|
mkdirSync(dir, { recursive: true });
|
||||||
|
writeFileSync(join(dir, 'storebound.config.json'), JSON.stringify(virtualConfig(v), null, 2) + '\n');
|
||||||
|
}
|
||||||
|
return dir;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An empty folder for commands that need no project (apps list / check): no stray .storebound/credentials.json. */
|
||||||
|
let neutral: string | null = null;
|
||||||
|
const neutralDir = (): string => (neutral ??= mkdtempSync(join(tmpdir(), 'storebound-account-')));
|
||||||
|
|
||||||
const cut = (s: string): string => (s.length > MAX_OUTPUT ? `[... first ${s.length - MAX_OUTPUT} characters cut ...]\n` + s.slice(-MAX_OUTPUT) : s);
|
const cut = (s: string): string => (s.length > MAX_OUTPUT ? `[... first ${s.length - MAX_OUTPUT} characters cut ...]\n` + s.slice(-MAX_OUTPUT) : s);
|
||||||
|
|
||||||
function credentialsOf(v: unknown): Record<string, string> {
|
function credentialsOf(v: unknown): Record<string, string> {
|
||||||
|
|
@ -197,6 +258,8 @@ export class Session {
|
||||||
case 'system.tools': return localTools();
|
case 'system.tools': return localTools();
|
||||||
case 'project.inspect': return this.inspect(checkProject(params.project), {}, id);
|
case 'project.inspect': return this.inspect(checkProject(params.project), {}, id);
|
||||||
case 'portfolio.status': return this.portfolio(params, id);
|
case 'portfolio.status': return this.portfolio(params, id);
|
||||||
|
case 'apps.list': return this.account(['apps', 'list'], params, id, true);
|
||||||
|
case 'account.check': return this.account(['apps', 'check'], params, id, false);
|
||||||
}
|
}
|
||||||
const tool = byMethod.get(method);
|
const tool = byMethod.get(method);
|
||||||
if (!tool) throw new RpcError(ERR.methodNotFound, `Method not found: ${method}`);
|
if (!tool) throw new RpcError(ERR.methodNotFound, `Method not found: ${method}`);
|
||||||
|
|
@ -204,8 +267,13 @@ export class Session {
|
||||||
}
|
}
|
||||||
|
|
||||||
private async tool(method: string, t: ToolDef, params: Json, id: Id): Promise<ToolResult> {
|
private async tool(method: string, t: ToolDef, params: Json, id: Id): Promise<ToolResult> {
|
||||||
for (const k of Object.keys(params)) if (!['project', 'args', 'dryRun', 'confirmToken', 'credentials'].includes(k)) throw new RpcError(ERR.invalidParams, `unknown param: ${k}`);
|
for (const k of Object.keys(params)) if (!['project', 'args', 'dryRun', 'confirmToken', 'credentials', 'virtual'].includes(k)) throw new RpcError(ERR.invalidParams, `unknown param: ${k}`);
|
||||||
const project = NEW_PROJECT.has(t.name) ? checkNewProject(params.project) : checkProject(params.project);
|
let project: string;
|
||||||
|
if (params.virtual !== undefined) {
|
||||||
|
if (params.project !== undefined) throw new RpcError(ERR.invalidParams, 'project or virtual, not both');
|
||||||
|
if (t.write || !VIRTUAL_READS.has(t.name)) throw new RpcError(ERR.invalidParams, `${method}: needs an app folder (store-only apps have store reads only)`);
|
||||||
|
project = virtualDir(checkVirtual(params.virtual));
|
||||||
|
} else project = NEW_PROJECT.has(t.name) ? checkNewProject(params.project) : checkProject(params.project);
|
||||||
const args = (params.args ?? {}) as Json;
|
const args = (params.args ?? {}) as Json;
|
||||||
if (typeof args !== 'object' || args === null || Array.isArray(args)) throw new RpcError(ERR.invalidParams, 'args must be an object');
|
if (typeof args !== 'object' || args === null || Array.isArray(args)) throw new RpcError(ERR.invalidParams, 'args must be an object');
|
||||||
if ('dry_run' in args) throw new RpcError(ERR.invalidParams, 'args.dry_run: use params.dryRun');
|
if ('dry_run' in args) throw new RpcError(ERR.invalidParams, 'args.dry_run: use params.dryRun');
|
||||||
|
|
@ -236,6 +304,23 @@ export class Session {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** apps.list / account.check: one account's credentials, no project folder. */
|
||||||
|
private async account(cmd: string[], params: Json, id: Id, list: boolean): Promise<unknown> {
|
||||||
|
for (const k of Object.keys(params)) if (!['credentials', 'args'].includes(k)) throw new RpcError(ERR.invalidParams, `unknown param: ${k}`);
|
||||||
|
const env = credentialsOf(params.credentials);
|
||||||
|
const play = !!env.PLAY_SERVICE_ACCOUNT, apple = !!(env.ASC_KEY_ID || env.ASC_ISSUER_ID || env.ASC_P8);
|
||||||
|
if (play === apple) throw new RpcError(ERR.invalidParams, 'credentials: exactly one store account (a Play service account, or an App Store Connect key)');
|
||||||
|
const args = (params.args ?? {}) as Json;
|
||||||
|
if (typeof args !== 'object' || args === null || Array.isArray(args)) throw new RpcError(ERR.invalidParams, 'args must be an object');
|
||||||
|
for (const k of Object.keys(args)) if (!(list && k === 'icons')) throw new RpcError(ERR.invalidParams, `args.${k}: unknown`);
|
||||||
|
if (args.icons !== undefined && typeof args.icons !== 'boolean') throw new RpcError(ERR.invalidParams, 'args.icons: boolean');
|
||||||
|
const argv = [...cmd, '--store', play ? 'play' : 'apple', ...(args.icons === true ? ['--icons'] : []), '--json'];
|
||||||
|
const r = await this.track(id, this.run(argv, { cwd: neutralDir(), env, machine: true, onLine: (line, stream) => this.progress(id, { line, stream }) })).result;
|
||||||
|
if (r.cancelled || this.cancelled.has(id)) throw new RpcError(ERR.cancelled, 'Request cancelled');
|
||||||
|
if (r.data === undefined) throw new RpcError(ERR.internal, lastLine(r.out) || `exit ${r.code}`);
|
||||||
|
return r.data;
|
||||||
|
}
|
||||||
|
|
||||||
private progress(id: Id, p: Json): void {
|
private progress(id: Id, p: Json): void {
|
||||||
this.send({ jsonrpc: '2.0', method: 'progress', params: { requestId: id, ...p } });
|
this.send({ jsonrpc: '2.0', method: 'progress', params: { requestId: id, ...p } });
|
||||||
}
|
}
|
||||||
|
|
@ -255,18 +340,27 @@ export class Session {
|
||||||
const out: AppStatus[] = new Array(list.length);
|
const out: AppStatus[] = new Array(list.length);
|
||||||
let done = 0;
|
let done = 0;
|
||||||
const one = async (i: number): Promise<void> => {
|
const one = async (i: number): Promise<void> => {
|
||||||
const raw = list[i];
|
const raw = list[i] as unknown;
|
||||||
const e: AppStatus = { project: String(raw), ok: false, app: null, summary: null, check: null, release: { source: 'none', current: null, next: null }, catalog: null, storeErrors: {}, errors: [] };
|
// a store-only app: { key: "store:...", virtual: { name, apple?, play? } }
|
||||||
|
const virt = typeof raw === 'object' && raw !== null && !Array.isArray(raw) ? raw as { key?: unknown; virtual?: unknown } : null;
|
||||||
|
const e: AppStatus = { project: virt ? String(virt.key ?? '') : String(raw), ok: false, app: null, summary: null, check: null, release: { source: 'none', current: null, next: null }, catalog: null, storeErrors: {}, errors: [] };
|
||||||
out[i] = e;
|
out[i] = e;
|
||||||
try {
|
try {
|
||||||
const dir = checkProject(raw);
|
let dir: string;
|
||||||
e.project = dir;
|
if (virt) {
|
||||||
|
if (typeof virt.key !== 'string' || !STORE_KEY_RE.test(virt.key)) throw new RpcError(ERR.invalidParams, 'projects[].key: a store target key');
|
||||||
|
dir = virtualDir(checkVirtual(virt.virtual));
|
||||||
|
e.virtual = true;
|
||||||
|
} else { dir = checkProject(raw); e.project = dir; }
|
||||||
const summary = e.summary = await this.inspect(dir, env, id);
|
const summary = e.summary = await this.inspect(dir, env, id);
|
||||||
e.app = appIdentity(summary);
|
e.app = appIdentity(summary);
|
||||||
e.catalog = catalogParity(summary);
|
e.catalog = catalogParity(summary);
|
||||||
|
if (virt) e.check = { ok: true, problems: [], warnings: [] };
|
||||||
|
else {
|
||||||
const c = await this.track(id, this.run(['check', '--json'], { cwd: dir, env, machine: true })).result;
|
const c = await this.track(id, this.run(['check', '--json'], { cwd: dir, env, machine: true })).result;
|
||||||
const cd = c.data as { ok?: boolean; problems?: string[]; warnings?: string[] } | undefined;
|
const cd = c.data as { ok?: boolean; problems?: string[]; warnings?: string[] } | undefined;
|
||||||
e.check = cd ? { ok: !!cd.ok, problems: cd.problems ?? [], warnings: cd.warnings ?? [] } : { ok: false, problems: [lastLine(c.out) || `check exit ${c.code}`], warnings: [] };
|
e.check = cd ? { ok: !!cd.ok, problems: cd.problems ?? [], warnings: cd.warnings ?? [] } : { ok: false, problems: [lastLine(c.out) || `check exit ${c.code}`], warnings: [] };
|
||||||
|
}
|
||||||
if (live) {
|
if (live) {
|
||||||
const store = async (argv: string[]): Promise<{ data?: unknown; error?: string }> => {
|
const store = async (argv: string[]): Promise<{ data?: unknown; error?: string }> => {
|
||||||
const r = await this.track(id, this.run(argv, { cwd: dir, env, machine: true })).result;
|
const r = await this.track(id, this.run(argv, { cwd: dir, env, machine: true })).result;
|
||||||
|
|
@ -294,6 +388,9 @@ export class Session {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Store target keys of store-only apps ("store:ios:<account>:<app id>:<bundle id>;android:<account>:<package>"). */
|
||||||
|
export const STORE_KEY_RE = /^store:[A-Za-z0-9:;._-]{1,400}$/;
|
||||||
|
|
||||||
const lastLine = (s: string): string => s.trim().split('\n').filter(Boolean).at(-1)?.replace(/^error:\s*/, '') ?? '';
|
const lastLine = (s: string): string => s.trim().split('\n').filter(Boolean).at(-1)?.replace(/^error:\s*/, '') ?? '';
|
||||||
|
|
||||||
/** Optional local tools with versions; app-managed copies (STOREBOUND_TOOL_PATH / STOREBOUND_CHROME) included. */
|
/** Optional local tools with versions; app-managed copies (STOREBOUND_TOOL_PATH / STOREBOUND_CHROME) included. */
|
||||||
|
|
|
||||||
256
tests/store-apps.test.ts
Normal file
256
tests/store-apps.test.ts
Normal file
|
|
@ -0,0 +1,256 @@
|
||||||
|
// storebound apps list / check (D3: many studios, many store accounts): parsing of recorded App Store Connect and
|
||||||
|
// Play Reporting API responses, account health classification, the CLI over a mocked fetch, and the serve methods
|
||||||
|
// (apps.list, account.check, store-only apps through a generated config).
|
||||||
|
import { afterEach, describe, expect, test } from 'bun:test';
|
||||||
|
import { generateKeyPairSync } from 'node:crypto';
|
||||||
|
import { existsSync, mkdtempSync, readFileSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { checkAccount, listApps } from '../cli/apps';
|
||||||
|
import { ERR } from '../cli/lib/desktop-protocol';
|
||||||
|
import type { RunOptions, Running } from '../cli/lib/runner';
|
||||||
|
import { appleCheck, iconUrl, listAppleApps, listPlayApps, playCheck } from '../cli/lib/store-apps';
|
||||||
|
import { checkVirtual, describeMethods, Session, STORE_KEY_RE, VIRTUAL_READS, virtualConfig, virtualDir } from '../cli/serve';
|
||||||
|
import { validateConfig } from '../cli/lib/config';
|
||||||
|
|
||||||
|
type J = Record<string, unknown>;
|
||||||
|
|
||||||
|
// ---- recorded responses (shapes as the APIs return them; ids and names are placeholders) ----
|
||||||
|
const ASC_APPS_1 = {
|
||||||
|
data: [
|
||||||
|
{ type: 'apps', id: '6400000101', attributes: { name: 'Example Puzzle', bundleId: 'com.example.puzzle', sku: 'PUZZLE1', primaryLocale: 'en-US' } },
|
||||||
|
{ type: 'apps', id: '6400000102', attributes: { name: 'Example Notes', bundleId: 'com.example.notes', sku: 'NOTES1', primaryLocale: 'en-GB' } },
|
||||||
|
],
|
||||||
|
links: { self: 'https://api.appstoreconnect.apple.com/v1/apps?limit=200', next: 'https://api.appstoreconnect.apple.com/v1/apps?cursor=Mg&limit=200' },
|
||||||
|
meta: { paging: { total: 3, limit: 200 } },
|
||||||
|
};
|
||||||
|
const ASC_APPS_2 = { data: [{ type: 'apps', id: '6400000103', attributes: { name: 'A Mac Tool', bundleId: 'com.example.mactool', sku: 'MAC1', primaryLocale: 'en-US' } }], links: { self: '' } };
|
||||||
|
const ASC_VERSIONS: Record<string, J> = {
|
||||||
|
'6400000101': { data: [
|
||||||
|
{ type: 'appStoreVersions', id: 'v1', attributes: { platform: 'IOS', versionString: '2.4.0', appStoreState: 'WAITING_FOR_REVIEW', appVersionState: 'WAITING_FOR_REVIEW' } },
|
||||||
|
{ type: 'appStoreVersions', id: 'v0', attributes: { platform: 'IOS', versionString: '2.3.0', appStoreState: 'READY_FOR_SALE', appVersionState: 'READY_FOR_DISTRIBUTION' } },
|
||||||
|
] },
|
||||||
|
'6400000102': { data: [] },
|
||||||
|
'6400000103': { data: [{ type: 'appStoreVersions', id: 'v9', attributes: { platform: 'MAC_OS', versionString: '1.0', appStoreState: 'PREPARE_FOR_SUBMISSION' } }] },
|
||||||
|
};
|
||||||
|
const ASC_BUILD = { data: [{ type: 'builds', id: 'b1', attributes: { version: '52', iconAssetToken: { templateUrl: 'https://is1-ssl.mzstatic.com/image/thumb/Purple/v4/ab/cd/AppIcon.png/{w}x{h}bb.{f}', width: 1024, height: 1024 } } }] };
|
||||||
|
const PLAY_SEARCH_1 = { apps: [{ name: 'apps/com.example.puzzle', packageName: 'com.example.puzzle', displayName: 'Example Puzzle' }, { name: 'apps/com.example.runner', packageName: 'com.example.runner', displayName: 'Runner' }], nextPageToken: 'tok2' };
|
||||||
|
const PLAY_SEARCH_2 = { apps: [{ name: 'apps/com.example.ledger', packageName: 'com.example.ledger', displayName: '' }] };
|
||||||
|
|
||||||
|
function ascGet(calls: string[]) {
|
||||||
|
return async (path: string): Promise<J> => {
|
||||||
|
calls.push(path);
|
||||||
|
if (path.startsWith('/v1/apps?fields')) return ASC_APPS_1;
|
||||||
|
if (path.includes('cursor=Mg')) return ASC_APPS_2;
|
||||||
|
const v = /^\/v1\/apps\/(\d+)\/appStoreVersions/.exec(path);
|
||||||
|
if (v) return ASC_VERSIONS[v[1]!]!;
|
||||||
|
if (path.startsWith('/v1/builds?filter[app]=6400000101')) return ASC_BUILD;
|
||||||
|
if (path.startsWith('/v1/builds')) return { data: [] };
|
||||||
|
throw new Error(`GET ${path} -> 404 not recorded`);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('apps list: App Store Connect', () => {
|
||||||
|
test('pages through /v1/apps, platforms and newest version per app, icon as a data URL', async () => {
|
||||||
|
const calls: string[] = [];
|
||||||
|
const icons: string[] = [];
|
||||||
|
const r = await listAppleApps(ascGet(calls), { icons: true, bytes: async url => { icons.push(url); return { type: 'image/png', data: new Uint8Array([137, 80, 78, 71]) }; } });
|
||||||
|
expect(r.apps.map(a => a.name)).toEqual(['A Mac Tool', 'Example Notes', 'Example Puzzle']);
|
||||||
|
const p = r.apps.find(a => a.bundleId === 'com.example.puzzle')!;
|
||||||
|
expect(p).toMatchObject({ store: 'ios', id: '6400000101', platforms: ['IOS'], latest: { version: '2.4.0', state: 'WAITING_FOR_REVIEW', platform: 'IOS' }, sku: 'PUZZLE1' });
|
||||||
|
expect(p.icon).toBe('data:image/png;base64,iVBORw==');
|
||||||
|
expect(icons).toEqual(['https://is1-ssl.mzstatic.com/image/thumb/Purple/v4/ab/cd/AppIcon.png/128x128bb.png']);
|
||||||
|
expect(r.apps.find(a => a.id === '6400000103')!.platforms).toEqual(['MAC_OS']);
|
||||||
|
expect(r.apps.find(a => a.id === '6400000102')!).toMatchObject({ platforms: [], latest: null, icon: null });
|
||||||
|
expect(calls.filter(c => c.startsWith('/v1/builds')).length).toBe(3);
|
||||||
|
expect(r.warnings).toEqual([]);
|
||||||
|
});
|
||||||
|
test('no icons unless asked; a failing version read is a warning, not a failure', async () => {
|
||||||
|
const calls: string[] = [];
|
||||||
|
const get = ascGet(calls);
|
||||||
|
const r = await listAppleApps(async p => { if (p.includes('6400000102/appStoreVersions')) throw new Error(`GET ${p} -> 500 boom`); return get(p); });
|
||||||
|
expect(calls.some(c => c.startsWith('/v1/builds'))).toBe(false);
|
||||||
|
expect(r.apps.every(a => a.icon === null)).toBe(true);
|
||||||
|
expect(r.warnings).toEqual([expect.stringContaining('com.example.notes: versions not read')]);
|
||||||
|
});
|
||||||
|
test('icon templates only from Apple\'s CDN', async () => {
|
||||||
|
const r = await listAppleApps(async p => {
|
||||||
|
if (p.startsWith('/v1/apps?fields')) return { data: [ASC_APPS_1.data[0]] };
|
||||||
|
if (p.includes('appStoreVersions')) return { data: [] };
|
||||||
|
return { data: [{ attributes: { iconAssetToken: { templateUrl: 'https://evil.example.com/{w}x{h}bb.{f}' } } }] };
|
||||||
|
}, { icons: true, bytes: async () => { throw new Error('must not fetch'); } });
|
||||||
|
expect(r.apps[0]!.icon).toBeNull();
|
||||||
|
expect(iconUrl('https://a.mzstatic.com/x/{w}x{h}{c}.{f}', 64)).toBe('https://a.mzstatic.com/x/64x64bb.png');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('apps list: Google Play', () => {
|
||||||
|
test('apps:search pages, display name falls back to the package', async () => {
|
||||||
|
const calls: string[] = [];
|
||||||
|
const r = await listPlayApps(async p => { calls.push(p); return p.includes('pageToken=tok2') ? PLAY_SEARCH_2 : PLAY_SEARCH_1; });
|
||||||
|
expect(calls).toEqual(['/apps:search?pageSize=1000', '/apps:search?pageSize=1000&pageToken=tok2']);
|
||||||
|
expect(r.apps.map(a => [a.name, a.id, a.store])).toEqual([['com.example.ledger', 'com.example.ledger', 'android'], ['Example Puzzle', 'com.example.puzzle', 'android'], ['Runner', 'com.example.runner', 'android']]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('account health', () => {
|
||||||
|
test('App Store Connect: ok, no apps, revoked (401), permission (403), unreachable', () => {
|
||||||
|
expect(appleCheck({ apps: 3 })).toMatchObject({ status: 'ok', apps: 3, fix: null });
|
||||||
|
expect(appleCheck({ apps: 0 }).status).toBe('no-apps');
|
||||||
|
const revoked = appleCheck({ error: new Error('GET /v1/apps -> 401 {"errors":[{"status":"401","code":"NOT_AUTHORIZED"}]}') });
|
||||||
|
expect(revoked.status).toBe('revoked');
|
||||||
|
expect(revoked.fix).toContain('Integrations');
|
||||||
|
expect(appleCheck({ error: new Error('GET /v1/apps -> 403 {"errors":[{"code":"FORBIDDEN_ERROR"}]}') }).status).toBe('permission');
|
||||||
|
expect(appleCheck({ error: new Error('fetch failed') }).status).toBe('error');
|
||||||
|
});
|
||||||
|
test('Play: ok, not invited (0 apps), API off, revoked key, missing permission; the hint names the service account', () => {
|
||||||
|
const who = 'storebound@example-project.iam.gserviceaccount.com';
|
||||||
|
expect(playCheck(who, { apps: 2 })).toMatchObject({ status: 'ok', apps: 2, principal: who });
|
||||||
|
const none = playCheck(who, { apps: 0 });
|
||||||
|
expect(none.status).toBe('permission');
|
||||||
|
expect(none.fix).toContain(`Invite new users: add ${who}`);
|
||||||
|
expect(none.fix).toContain('several developer accounts');
|
||||||
|
expect(playCheck(who, { error: new Error('GET /v1beta1/apps:search -> 403 {"error":{"code":403,"status":"PERMISSION_DENIED","details":[{"reason":"SERVICE_DISABLED"}],"message":"Google Play Developer Reporting API has not been used in project 123 before or it is disabled."}}') }).status).toBe('api-disabled');
|
||||||
|
expect(playCheck(who, { error: new Error('Google token: Invalid JWT Signature.') }).status).toBe('revoked');
|
||||||
|
expect(playCheck(who, { error: new Error('Google token: invalid_grant') }).status).toBe('revoked');
|
||||||
|
expect(playCheck(who, { error: new Error('GET /apps:search -> 403 {"error":{"status":"PERMISSION_DENIED","message":"The caller does not have permission"}}') }).status).toBe('permission');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- the CLI over a mocked fetch (real JWT signing with throwaway keys) ----
|
||||||
|
const realFetch = globalThis.fetch;
|
||||||
|
const saved = { ...process.env };
|
||||||
|
afterEach(() => { globalThis.fetch = realFetch; for (const k of ['ASC_KEY_ID', 'ASC_ISSUER_ID', 'ASC_P8', 'PLAY_SERVICE_ACCOUNT']) { if (saved[k] === undefined) delete process.env[k]; else process.env[k] = saved[k]; } });
|
||||||
|
|
||||||
|
function mockFetch(routes: (url: string, init?: RequestInit) => Response | null): string[] {
|
||||||
|
const seen: string[] = [];
|
||||||
|
globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
|
||||||
|
const url = String(input instanceof Request ? input.url : input);
|
||||||
|
seen.push(`${init?.method ?? 'GET'} ${url}`);
|
||||||
|
const r = routes(url, init);
|
||||||
|
if (!r) return new Response('{"error":"not recorded"}', { status: 404 });
|
||||||
|
return r;
|
||||||
|
}) as typeof fetch;
|
||||||
|
return seen;
|
||||||
|
}
|
||||||
|
const json = (o: unknown, status = 200) => new Response(JSON.stringify(o), { status, headers: { 'content-type': 'application/json' } });
|
||||||
|
|
||||||
|
describe('storebound apps (CLI functions, mocked HTTP)', () => {
|
||||||
|
const root = mkdtempSync(join(tmpdir(), 'sb-apps-'));
|
||||||
|
test('apple: list with icons, check', async () => {
|
||||||
|
const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });
|
||||||
|
process.env.ASC_KEY_ID = 'ABCDE12345';
|
||||||
|
process.env.ASC_ISSUER_ID = '00000000-0000-4000-8000-000000000000';
|
||||||
|
process.env.ASC_P8 = privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();
|
||||||
|
const get = ascGet([]);
|
||||||
|
const seen = mockFetch(url => {
|
||||||
|
if (url.startsWith('https://is1-ssl.mzstatic.com/')) return new Response(new Uint8Array([1, 2, 3]), { headers: { 'content-type': 'image/png' } });
|
||||||
|
if (url.startsWith('https://api.appstoreconnect.apple.com')) return null;
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
// route ASC through the recorded getter
|
||||||
|
globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
|
||||||
|
const url = String(input);
|
||||||
|
seen.push(url);
|
||||||
|
const auth = new Headers(init?.headers).get('Authorization') ?? '';
|
||||||
|
if (url.startsWith('https://api.appstoreconnect')) expect(auth).toMatch(/^Bearer [\w-]+\.[\w-]+\.[\w-]+$/);
|
||||||
|
if (url.startsWith('https://is1-ssl.mzstatic.com/')) return new Response(new Uint8Array([1, 2, 3]), { headers: { 'content-type': 'image/png' } });
|
||||||
|
try { return json(await get(url.replace('https://api.appstoreconnect.apple.com', ''))); } catch { return json({ errors: [{ status: '404' }] }, 404); }
|
||||||
|
}) as typeof fetch;
|
||||||
|
const r = await listApps('apple', root, true);
|
||||||
|
expect(r.store).toBe('ios');
|
||||||
|
expect(r.apps.length).toBe(3);
|
||||||
|
expect(r.apps.find(a => a.id === '6400000101')!.icon).toBe('data:image/png;base64,AQID');
|
||||||
|
expect(await checkAccount('apple', root)).toMatchObject({ status: 'ok', apps: 2 });
|
||||||
|
globalThis.fetch = (async () => json({ errors: [{ status: '401', code: 'NOT_AUTHORIZED' }] }, 401)) as unknown as typeof fetch;
|
||||||
|
expect((await checkAccount('apple', root)).status).toBe('revoked');
|
||||||
|
});
|
||||||
|
test('play: token exchange, apps:search, check; no apps = not invited', async () => {
|
||||||
|
const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
|
||||||
|
process.env.PLAY_SERVICE_ACCOUNT = JSON.stringify({ client_email: 'sb@example-project.iam.gserviceaccount.com', private_key: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(), token_uri: 'https://oauth2.googleapis.com/token' });
|
||||||
|
let apps: unknown[] = PLAY_SEARCH_2.apps;
|
||||||
|
const seen = mockFetch(url => {
|
||||||
|
if (url === 'https://oauth2.googleapis.com/token') return json({ access_token: 'ya29.test', expires_in: 3600 });
|
||||||
|
if (url.startsWith('https://playdeveloperreporting.googleapis.com/v1beta1/apps:search')) return json({ apps });
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
const r = await listApps('play', root, false);
|
||||||
|
expect(r.apps.map(a => a.id)).toEqual(['com.example.ledger']);
|
||||||
|
expect(seen.some(s => s.startsWith('POST https://oauth2.googleapis.com/token'))).toBe(true);
|
||||||
|
expect(await checkAccount('play', root)).toMatchObject({ status: 'ok', principal: 'sb@example-project.iam.gserviceaccount.com' });
|
||||||
|
apps = [];
|
||||||
|
expect((await checkAccount('play', root)).status).toBe('permission');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- serve: apps.list, account.check, store-only apps ----
|
||||||
|
const SECRET_HEX = Array.from({ length: 32 }, (_, i) => i.toString(16).padStart(2, '0')).join('');
|
||||||
|
async function session(reply: (argv: string[], o: RunOptions) => { code?: number; out?: string; data?: unknown } = () => ({})) {
|
||||||
|
const calls: { argv: string[]; o: RunOptions }[] = [];
|
||||||
|
const run = (argv: string[], o: RunOptions): Running => { calls.push({ argv, o }); const r = reply(argv, o); return { result: Promise.resolve({ code: r.code ?? 0, out: r.out ?? '', ...(r.data === undefined ? {} : { data: r.data }), cancelled: false }), cancel: () => {} }; };
|
||||||
|
const s = new Session(() => {}, run);
|
||||||
|
let id = 0;
|
||||||
|
const call = async (method: string, params: unknown = {}) => (await s.handle({ jsonrpc: '2.0', id: ++id, method, params }))! as J;
|
||||||
|
await call('session.hello', { secret: SECRET_HEX });
|
||||||
|
return { calls, call };
|
||||||
|
}
|
||||||
|
const PLAY = { PLAY_SERVICE_ACCOUNT: '{"client_email":"x@example.com","private_key":"-----BEGIN PRIVATE KEY-----"}' };
|
||||||
|
const APPLE = { ASC_KEY_ID: 'ABCDE12345', ASC_ISSUER_ID: '00000000-0000-4000-8000-000000000000', ASC_P8: '-----BEGIN PRIVATE KEY-----\nx\n-----END PRIVATE KEY-----' };
|
||||||
|
|
||||||
|
describe('serve: account methods', () => {
|
||||||
|
test('described as kind "account", network reads', () => {
|
||||||
|
const m = describeMethods().filter(x => x.kind === 'account').map(x => x.method).sort();
|
||||||
|
expect(m).toEqual(['account.check', 'apps.list']);
|
||||||
|
});
|
||||||
|
test('apps.list: one account, its store from the credentials, icons on request, in an empty folder', async () => {
|
||||||
|
const s = await session(() => ({ data: { store: 'android', apps: [], warnings: [], at: 'x' } }));
|
||||||
|
const r = await s.call('apps.list', { credentials: PLAY, args: { icons: true } });
|
||||||
|
expect(r.result).toEqual({ store: 'android', apps: [], warnings: [], at: 'x' });
|
||||||
|
expect(s.calls[0]!.argv).toEqual(['apps', 'list', '--store', 'play', '--icons', '--json']);
|
||||||
|
expect(s.calls[0]!.o.env).toEqual(PLAY);
|
||||||
|
expect(existsSync(join(s.calls[0]!.o.cwd, '.storebound'))).toBe(false);
|
||||||
|
await s.call('account.check', { credentials: APPLE });
|
||||||
|
expect(s.calls[1]!.argv).toEqual(['apps', 'check', '--store', 'apple', '--json']);
|
||||||
|
});
|
||||||
|
test('apps.list: refuses no account, two accounts, unknown args', async () => {
|
||||||
|
const s = await session();
|
||||||
|
for (const p of [{ credentials: {} }, { credentials: { ...PLAY, ...APPLE } }, { credentials: PLAY, args: { only: 'x' } }, { credentials: PLAY, project: '/tmp' }, { credentials: APPLE, args: { icons: 'yes' } }])
|
||||||
|
expect((await s.call('apps.list', p)).error).toMatchObject({ code: ERR.invalidParams });
|
||||||
|
expect((await s.call('account.check', { credentials: PLAY, args: { icons: true } })).error).toMatchObject({ code: ERR.invalidParams });
|
||||||
|
expect(s.calls.length).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('serve: store-only apps (virtual)', () => {
|
||||||
|
const V = { name: 'Example Puzzle', apple: { bundleId: 'com.example.puzzle', appId: '6400000101' }, play: { packageName: 'com.example.puzzle' } };
|
||||||
|
test('generated config validates and only carries store ids and placeholders', () => {
|
||||||
|
expect(validateConfig(virtualConfig(V))).toEqual([]);
|
||||||
|
expect(validateConfig(virtualConfig({ name: 'Only Play', play: { packageName: 'com.example.runner' } }))).toEqual([]);
|
||||||
|
const dir = virtualDir(V);
|
||||||
|
expect(JSON.parse(readFileSync(join(dir, 'storebound.config.json'), 'utf8')).apple).toEqual({ bundleId: 'com.example.puzzle', appId: '6400000101' });
|
||||||
|
expect(virtualDir(V)).toBe(dir);
|
||||||
|
for (const bad of [{}, { name: '' }, { name: 'x' }, { name: 'x', apple: { bundleId: '../etc' } }, { name: 'x', play: { packageName: 'nope' } }, { name: 'x', apple: { bundleId: 'com.a.b', appId: '12a' } }, { name: 'x', play: { packageName: 'com.a.b' }, path: '/etc' }])
|
||||||
|
expect(() => checkVirtual(bad)).toThrow();
|
||||||
|
});
|
||||||
|
test('store reads run in the generated folder; writes and offline project reads are refused', async () => {
|
||||||
|
const s = await session(() => ({ data: { ok: true } }));
|
||||||
|
const r = await s.call('reviews.list', { virtual: V, args: { days: 30 }, credentials: APPLE });
|
||||||
|
expect(r.error).toBeUndefined();
|
||||||
|
expect(existsSync(join(s.calls[0]!.o.cwd, 'storebound.config.json'))).toBe(true);
|
||||||
|
expect([...VIRTUAL_READS].sort()).toEqual(['apple_ppo_status', 'apple_status', 'apple_testflight_status', 'health', 'play_status', 'reviews_list']);
|
||||||
|
for (const m of ['play.listing', 'catalog.diff', 'project.listings', 'check', 'reviews.approve'])
|
||||||
|
expect((await s.call(m, { virtual: V, args: m === 'reviews.approve' ? { file: 'apple-1.md' } : {} })).error).toMatchObject({ code: ERR.invalidParams });
|
||||||
|
expect((await s.call('health', { virtual: V, project: '/tmp' })).error).toMatchObject({ code: ERR.invalidParams });
|
||||||
|
});
|
||||||
|
test('portfolio.status takes store-only entries by key: inspected, no config check, keyed back', async () => {
|
||||||
|
const s = await session(argv => (argv[0] === 'inspect' ? { data: { dir: '/x', config: '/x/c', name: 'Example Puzzle', languages: ['en'], play: { packageName: 'com.example.puzzle' }, apple: { bundleId: 'com.example.puzzle', appId: '6400000101' }, platforms: ['ios', 'android'], products: 0, productIds: [], subscriptions: 0, subscriptionIds: [], catalog: { ios: [], android: [] }, shots: false, testflightGroups: 0 } } : { data: {} }));
|
||||||
|
const key = 'store:ios:a1b2:6400000101:com.example.puzzle;android:c3d4:com.example.puzzle';
|
||||||
|
expect(STORE_KEY_RE.test(key)).toBe(true);
|
||||||
|
const r = await s.call('portfolio.status', { projects: [{ key, virtual: V }] });
|
||||||
|
const app = (r.result as { apps: J[] }).apps[0]!;
|
||||||
|
expect(app).toMatchObject({ project: key, virtual: true, check: { ok: true, problems: [], warnings: [] } });
|
||||||
|
expect(s.calls.map(c => c.argv[0])).toEqual(['inspect']);
|
||||||
|
const bad = await s.call('portfolio.status', { projects: [{ key: 'store:../x y', virtual: V }] });
|
||||||
|
expect(((bad.result as { apps: J[] }).apps[0]!.errors as string[])[0]).toContain('store target key');
|
||||||
|
});
|
||||||
|
});
|
||||||
Loading…
Add table
Add a link
Reference in a new issue