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

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 };
}