Merge desktop-d3: studios and accounts, store import, pairing, ignore list, settings, confirm-gated writes

This commit is contained in:
CRTkafa 2026-10-10 20:33:03 +00:00
commit fa6215ebbe
66 changed files with 5103 additions and 424 deletions

145
cli/apps.ts Normal file
View 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);
}

View file

@ -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'],
'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)'],
'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'],
'privacy-manifest': [() => import('./privacy-manifest'), 'iOS PrivacyInfo.xcprivacy + required-reason API + SDK manifest scan (--ios <path>)'],
};

View file

@ -23,11 +23,16 @@ export function byAppleLocale(langs: Language[]): Map<string, Language> {
/**
* Asks on the terminal unless --yes. Store actions that are public or irreversible go through this.
* Under `storebound serve` (the desktop sidecar) nothing can answer and nothing may skip the question, not even --yes:
* those actions stay terminal-only, so the answer is always no.
* Under `storebound serve` (the desktop sidecar) nothing can answer and nothing may skip the question, not even --yes,
* so the answer is no. The one exception: a desktop owner action (serve.ts OWNER_TOOLS: rollout changes, the phased
* release, sending one approved reply) whose confirm token the sidecar verified after the owner pressed the button of
* a native dialog showing the dry run; serve sets STOREBOUND_OWNER_CONFIRMED for that one child only.
*/
export async function confirm(ctx: Ctx, question: string): Promise<boolean> {
if (process.env.STOREBOUND_SERVE === '1') { console.error(`confirm-required: ${question}\n terminal only: run it in a terminal`); return false; }
if (process.env.STOREBOUND_SERVE === '1') {
if (process.env.STOREBOUND_OWNER_CONFIRMED === '1') { console.error(`confirmed by the owner in the desktop dialog: ${question}`); return true; }
console.error(`confirm-required: ${question}\n terminal only: run it in a terminal`); return false;
}
if (ctx.args.has('yes')) return true;
if (!process.stdin.isTTY) { console.log(`${question}\n not a terminal: re-run with --yes to confirm`); return false; }
process.stdout.write(`${question} [y/N] `);

View file

@ -29,7 +29,9 @@ export interface MethodDescriptor {
method: string;
title: string;
description: string;
kind: 'read' | 'write' | 'session' | 'system' | 'portfolio';
/** owner: a desktop-only write the owner decides (rollout, phased release, sending one reply); always a dry run
* unless the host's confirm token comes with it, and then the command's own confirmation is answered by that token. */
kind: 'read' | 'write' | 'session' | 'system' | 'portfolio' | 'account' | 'owner';
/** Talks to a store API or the internet. */
network: boolean;
/** Replaces existing data on a store (screenshots, whole forms). */
@ -154,6 +156,8 @@ export interface AppStatus {
/** 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[] };
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"). */
storeErrors: { ios?: string; android?: string };
errors: string[];
@ -204,3 +208,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. */
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 }

View file

@ -172,6 +172,18 @@ export function readReplyDrafts(dir: string): DraftsResult {
return out;
}
/** The "## Reply" section of a draft set to `reply` (everything after the heading is replaced); `approved` goes back
* to false, since an edited reply needs a fresh approval. Sent drafts are not edited. */
export function setReplyText(text: string, reply: string): string {
const { data, body } = parseFrontMatter(text);
if (data.store !== 'apple' && data.store !== 'play') throw new Error('not a review reply draft (front matter "store" missing)');
if (typeof data.sent === 'string' && data.sent) throw new Error('this reply was sent already: edit it in the store console');
const clean = reply.replace(/\r\n?/g, '\n').replace(/<!--[\s\S]*?-->/g, '').trim();
const at = body.search(/^## Reply\s*$/m);
const head = at < 0 ? `${body.trimEnd()}\n\n` : body.slice(0, at);
return stringifyFrontMatter({ ...data, approved: false }, `${head}## Reply\n\n${clean}\n`);
}
/** Front matter `approved: <bool>` set in a draft file text; the body unchanged. */
export function setApproved(text: string, approved: boolean): string {
const { data, body } = parseFrontMatter(text);

View file

@ -39,7 +39,8 @@ export function pickCallEnv(env: Record<string, unknown> | undefined): Record<st
/** Environment of a child: the parent's minus anything secret to the session, plus the per-call values. */
export function childEnv(extra: Record<string, string> = {}, machine = false): Record<string, string> {
const base: Record<string, string> = {};
for (const [k, v] of Object.entries(process.env)) if (v !== undefined && !k.startsWith('STOREBOUND_SESSION')) base[k] = v;
// never inherited: the session secret, and the owner's confirmation (serve passes it per call, after a verified token)
for (const [k, v] of Object.entries(process.env)) if (v !== undefined && !k.startsWith('STOREBOUND_SESSION') && k !== 'STOREBOUND_OWNER_CONFIRMED') base[k] = v;
// app-managed tools (desktop data folder) come first on PATH
if (base.STOREBOUND_TOOL_PATH) base.PATH = toolPath(base);
return { ...base, ...extra, NO_COLOR: '1', ...(machine ? { STOREBOUND_MACHINE: '1', STOREBOUND_SERVE: '1' } : {}) };

142
cli/lib/store-apps.ts Normal file
View 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 };
}

View file

@ -4,6 +4,8 @@
// storebound reviews send [--dir .storebound/replies] [--dry] [--yes]
// storebound reviews drafts [--json] the local drafts with the checks `send` applies (offline)
// storebound reviews approve <draft file> [--undo] [--dry] sets approved: true (false) in one draft (local file)
// storebound reviews reply <draft file> --text "..." [--dry] writes the reply of one draft (local file; approval reset)
// storebound reviews send --file <draft file> ... sends that one approved draft only
// `draft` writes one Markdown file per unanswered review into .storebound/replies/ (gitignored): front matter
// (store, review_id, rating, approved: false), the review, and an empty "## Reply" section. Existing files are never
// overwritten (your edits stay). The owner or an agent with the review-replies skill writes the reply; the owner sets
@ -21,7 +23,7 @@ import {
type Review, sendPlan,
} from './lib/reviews';
import { textTable } from './lib/table';
import { readReplyDrafts, setApproved } from './lib/project-files';
import { readReplyDrafts, setApproved, setReplyText } from './lib/project-files';
import { playClient } from './play/client';
const TAG = 'reviews';
@ -117,7 +119,11 @@ export async function run(ctx: Ctx): Promise<void> {
}
if (sub === 'send') {
const { drafts, texts } = readDrafts(dir);
const { drafts: all, texts } = readDrafts(dir);
const only = a.get('file');
if (only !== undefined && !/^(apple|play)-[A-Za-z0-9._-]{1,120}\.md$/.test(only)) throw new Error('--file: a draft file name in .storebound/replies');
const drafts = only === undefined ? all : all.filter(d => d.file.split(/[\\/]/).pop() === only);
if (only !== undefined && !drafts.length) throw new Error(`no draft ${only} in ${dir}`);
const plan = sendPlan(drafts);
for (const s of plan.skip) log(TAG, `skip ${s.file.split('/').pop()}: ${s.why}`);
for (const d of plan.send) for (const i of checkReply(d.reply, d.store)) warn(TAG, `${d.file.split('/').pop()}: ${i.msg}`);
@ -171,5 +177,20 @@ export async function run(ctx: Ctx): Promise<void> {
done(TAG, `${approved ? 'approved' : 'approval removed'}: ${p} (send with storebound reviews send)`);
return;
}
throw new Error('usage: storebound reviews list | draft | drafts | approve | send');
if (sub === 'reply') {
// writes the reply text of one draft (local file only); an edited reply needs a fresh approval
const file = a.get('file') ?? a._[1];
const text = a.get('text');
if (!file || text === undefined) throw new Error('usage: storebound reviews reply <draft file> --text "..." [--dry]');
const p = resolve(dir, file);
if (relative(dir, p).startsWith('..') || !p.endsWith('.md') || !existsSync(p)) throw new Error(`no draft ${file} in ${dir}`);
const d = parseDraft(p, readFileSync(p, 'utf8'));
const next = setReplyText(readFileSync(p, 'utf8'), text);
for (const i of checkReply(parseDraft(p, next).reply, d.store)) (i.level === 'error' ? warn : log)(TAG, `${file}: ${i.msg}`);
if (a.has('dry')) { done(TAG, `would write the reply (${[...text.trim()].length} characters) into ${p}${d.approved ? ' and reset its approval' : ''} (dry run)`); return; }
writeFileSync(p, next);
done(TAG, `reply saved in ${p}${d.approved ? ' (approval reset: approve it again)' : ''}`);
return;
}
throw new Error('usage: storebound reviews list | draft | drafts | approve | reply | send');
}

View file

@ -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
// 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).
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 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 {
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';
import { appIdentity, appleProductIds, appleReleases, catalogParity, playProductIds, playReleases, releaseTrains } from './lib/portfolio';
import { detectTools } from './lib/tools';
@ -56,10 +58,46 @@ export const DESKTOP_ONLY: ToolDef[] = [
description: 'Sets approved: true (or false with undo) in one local reply draft after its checks pass. Nothing is sent: replies go out with `storebound reviews send` in a terminal.',
props: { file: { type: 'string', pattern: '^(apple|play)-[A-Za-z0-9._-]{1,120}\\.md$', description: 'Draft file name in .storebound/replies' }, undo: { type: 'boolean', default: false } },
required: ['file'], args: i => [String(i.file), ...(i.undo === true ? ['--undo'] : [])] },
{ name: 'reviews_reply', title: 'Write a reply draft', command: ['reviews', 'reply'], write: true, network: false, idempotent: true,
description: 'Writes the reply text of one local reply draft (.storebound/replies); an edited reply loses its approval. Nothing is sent.',
props: { file: { type: 'string', pattern: '^(apple|play)-[A-Za-z0-9._-]{1,120}\\.md$', description: 'Draft file name in .storebound/replies' },
text: { type: 'string', pattern: '^[\\s\\S]{1,6000}$', description: 'The reply (plain text, the reviewer\'s language)' } },
required: ['file', 'text'], args: i => [String(i.file), '--text', String(i.text)] },
{ name: 'project_init', title: 'Start an app folder', command: ['init'], write: true, network: false, idempotent: true,
description: 'Copies the storebound templates (config, listing, screenshot copy, declarations, privacy policy) for a profile into an empty app folder; existing files are kept.',
props: { profile: { type: 'string', enum: ['app', 'game', 'subscription-app'], default: 'app' } }, args: i => ['--profile', String(i.profile ?? 'app')] },
];
/**
* Owner actions (desktop only, kind "owner"): changes the owner decides because users see them at once. Each is a dry
* run unless the host's confirm token comes with it, minted after the owner pressed the button of a native dialog that
* showed that dry run; only then the command's own confirmation is answered (STOREBOUND_OWNER_CONFIRMED for that one
* child). Never: submitting for review, releasing an approved version (--manual-release), cancelling a submission,
* external TestFlight or Beta App Review, removing testers. Those stay in the consoles or the terminal.
*/
export const OWNER_TOOLS: ToolDef[] = [
{ name: 'owner_play_rollout', title: 'Change the Play staged rollout', command: ['play', 'rollout'], write: true, network: true,
description: 'Google Play staged rollout of a track: set the user share (percent), halt it (not a rollback), resume it, or complete it (100 %).',
props: { action: { type: 'string', enum: ['percent', 'halt', 'resume', 'complete'] }, percent: { type: 'integer', minimum: 1, maximum: 99, description: 'User share in percent (action percent, or resume at a new share)' },
track: { type: 'string', enum: ['production', 'beta', 'alpha', 'internal'], default: 'production' } },
required: ['action'],
args: i => [...(i.action === 'halt' ? ['--halt'] : i.action === 'resume' ? ['--resume'] : i.action === 'complete' ? ['--complete'] : []),
...(i.percent !== undefined && (i.action === 'percent' || i.action === 'resume') ? ['--fraction', String(Number(i.percent) / 100)] : []), '--track', String(i.track ?? 'production')] },
{ name: 'owner_ios_phased', title: 'Change the App Store phased release', command: ['apple', 'release'], write: true, network: true,
description: 'The 7-day phased release of an App Store version: turn it on, pause it (not a rollback), resume it, or release to everyone now (complete).',
props: { action: { type: 'string', enum: ['on', 'pause', 'resume', 'complete'] }, version: { type: 'string', pattern: '^\\d+(\\.\\d+){0,2}$' } },
required: ['action'], args: i => ['--phased', String(i.action), ...(i.version ? ['--version', String(i.version)] : [])] },
{ name: 'owner_reply_send', title: 'Send one approved reply', command: ['reviews', 'send'], write: true, network: true,
description: 'Sends one approved, unsent reply draft (.storebound/replies) to its store: public, the reviewer is notified. The draft checks (length, no incentives) apply.',
props: { file: { type: 'string', pattern: '^(apple|play)-[A-Za-z0-9._-]{1,120}\\.md$', description: 'Draft file name in .storebound/replies' } },
required: ['file'], args: i => ['--file', String(i.file)] },
{ name: 'owner_testflight_testers', title: 'Add TestFlight testers', command: ['apple', 'testflight', 'testers'], write: true, network: true,
description: 'Adds the testers of the project\'s testers CSV (.storebound/testers.csv, gitignored) to their TestFlight groups; Apple emails them an invitation once the group has a build. Emails stay masked in every line. Removing testers stays a terminal command.',
props: { groups: { type: 'string', pattern: '^[^,;]{1,60}(,[^,;]{1,60}){0,19}$', description: 'Comma-separated group names (default: every group in the CSV)' } },
args: i => (i.groups ? ['--group', String(i.groups)] : []) },
];
/** Flags no owner action may ever produce. */
export const OWNER_FORBIDDEN_ARGS = ['--yes', '--manual-release', '--cancel-submission', '--submit-review', '--remove', '--invite', '--production', '--csv', 'submit', 'publish', 'distribute'];
/** Desktop-only methods whose `project` is a folder without a config yet. */
const NEW_PROJECT = new Set(['project_init']);
@ -67,7 +105,8 @@ const NEW_PROJECT = new Set(['project_init']);
export const methodName = (tool: string): string => tool.replace('_', '.');
export const DESKTOP_TOOLS: ToolDef[] = [...TOOLS.filter(t => !DESKTOP_EXCLUDED.has(t.name)), ...DESKTOP_ONLY];
const byMethod = new Map(DESKTOP_TOOLS.map(t => [methodName(t.name), t] as const));
const OWNER = new Set(OWNER_TOOLS.map(t => t.name));
const byMethod = new Map([...DESKTOP_TOOLS, ...OWNER_TOOLS].map(t => [methodName(t.name), t] as const));
function argsSchema(t: ToolDef): MethodDescriptor['args'] {
const s = inputSchema(t) as MethodDescriptor['args'];
@ -86,13 +125,23 @@ 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: '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']) },
{ 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,
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[] {
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,
return [...SYSTEM, ...[...DESKTOP_TOOLS, ...OWNER_TOOLS].map(t => ({
method: methodName(t.name), title: t.title, description: t.description, kind: OWNER.has(t.name) ? 'owner' as const : t.write ? 'write' as const : 'read' as const,
network: t.network, destructive: !!t.destructive, json: !t.write && JSON_TOOLS.has(t.name), args: argsSchema(t),
}))];
}
@ -113,6 +162,55 @@ export function checkProject(p: unknown): string {
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);
function credentialsOf(v: unknown): Record<string, string> {
@ -197,6 +295,8 @@ export class Session {
case 'system.tools': return localTools();
case 'project.inspect': return this.inspect(checkProject(params.project), {}, 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);
if (!tool) throw new RpcError(ERR.methodNotFound, `Method not found: ${method}`);
@ -204,8 +304,13 @@ export class Session {
}
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}`);
const project = NEW_PROJECT.has(t.name) ? checkNewProject(params.project) : checkProject(params.project);
for (const k of Object.keys(params)) if (!['project', 'args', 'dryRun', 'confirmToken', 'credentials', 'virtual'].includes(k)) throw new RpcError(ERR.invalidParams, `unknown param: ${k}`);
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;
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');
@ -227,6 +332,11 @@ export class Session {
const built = toArgv(t, { ...args, ...(t.write ? { dry_run: dryRun } : {}) });
const json = !t.write && JSON_TOOLS.has(t.name);
const argv = json ? [...built.argv, '--json'] : built.argv;
if (OWNER.has(t.name)) {
if (argv.some(a => OWNER_FORBIDDEN_ARGS.includes(a))) throw new RpcError(ERR.invalidParams, `${method}: not an owner action from here`);
// the verified token is the owner's answer to the command's own question; nothing else can set it
if (!dryRun) env.STOREBOUND_OWNER_CONFIRMED = '1';
}
const r = this.track(id, this.run(argv, { cwd: project, env, machine: true, onLine: (line, stream) => this.progress(id, { line, stream }) }));
const res = await r.result;
if (res.cancelled || this.cancelled.has(id)) throw new RpcError(ERR.cancelled, 'Request cancelled');
@ -236,6 +346,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 {
this.send({ jsonrpc: '2.0', method: 'progress', params: { requestId: id, ...p } });
}
@ -255,18 +382,27 @@ export class Session {
const out: AppStatus[] = new Array(list.length);
let done = 0;
const one = async (i: number): Promise<void> => {
const raw = list[i];
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: [] };
const raw = list[i] as unknown;
// 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;
try {
const dir = checkProject(raw);
e.project = dir;
let dir: string;
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);
e.app = appIdentity(summary);
e.catalog = catalogParity(summary);
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;
e.check = cd ? { ok: !!cd.ok, problems: cd.problems ?? [], warnings: cd.warnings ?? [] } : { ok: false, problems: [lastLine(c.out) || `check exit ${c.code}`], warnings: [] };
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 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: [] };
}
if (live) {
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;
@ -294,6 +430,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*/, '') ?? '';
/** Optional local tools with versions; app-managed copies (STOREBOUND_TOOL_PATH / STOREBOUND_CHROME) included. */