From 3454a9aadb63fd3456c6b47b9ac1efce71bd59cd Mon Sep 17 00:00:00 2001 From: CRT Date: Sat, 10 Oct 2026 17:11:56 +0000 Subject: [PATCH] serve --stdio: desktop JSON-RPC profile on the MCP core, confirm tokens, --json results, sidecar builds - cli/serve.ts: session.hello with a per-session secret, typed methods per tool, project.inspect, portfolio.status over many project folders, progress notifications, cancellation - cli/lib/confirm-token.ts: single-use HMAC tokens bound to method + canonical params + expiry; writes are dry runs without one; no submit / release / publish method exists - cli/lib/runner.ts: shared child runner for mcp and serve, works from a compiled binary - --json on check, testflight / ppo status, next-build, next-version-code, analytics compare, prices import; inspect command; confirm() always answers no under serve - tools/build-sidecars.ts: bun build --compile for five targets, ad-hoc re-sign on macOS, path leak check - tests/serve.test.ts: methods, token binding / expiry / replay, shared vector, stdio and compiled smoke --- .gitignore | 7 + CHANGELOG.md | 13 ++ README.md | 14 ++ cli/analytics.ts | 3 +- cli/apple/next-build.ts | 2 + cli/apple/ppo.ts | 14 +- cli/apple/status.ts | 4 +- cli/apple/testflight.ts | 19 ++- cli/check.ts | 18 +- cli/health.ts | 4 +- cli/index.ts | 2 + cli/inspect.ts | 28 ++++ cli/lib/config.ts | 4 +- cli/lib/confirm-token.ts | 95 +++++++++++ cli/lib/ctx.ts | 7 +- cli/lib/desktop-protocol.ts | 99 +++++++++++ cli/lib/log.ts | 12 ++ cli/lib/runner.ts | 79 +++++++++ cli/mcp.ts | 17 +- cli/play/next-version-code.ts | 8 +- cli/play/status.ts | 3 +- cli/prices.ts | 6 +- cli/reviews.ts | 4 +- cli/serve.ts | 306 ++++++++++++++++++++++++++++++++++ cli/shots/check.ts | 4 +- cli/validate.ts | 4 +- tests/serve.test.ts | 243 +++++++++++++++++++++++++++ tools/build-sidecars.ts | 71 ++++++++ 28 files changed, 1048 insertions(+), 42 deletions(-) create mode 100644 cli/inspect.ts create mode 100644 cli/lib/confirm-token.ts create mode 100644 cli/lib/desktop-protocol.ts create mode 100644 cli/lib/runner.ts create mode 100644 cli/serve.ts create mode 100644 tests/serve.test.ts create mode 100644 tools/build-sidecars.ts diff --git a/.gitignore b/.gitignore index e5c7dc00..ed7d4a3d 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,10 @@ node_modules/ *.p12 .DS_Store media/teaser/out/ + +# desktop app (apps/desktop): build output, compiled sidecars, Tauri generated schemas +apps/desktop/dist/ +apps/desktop/src-tauri/target/ +apps/desktop/src-tauri/binaries/ +apps/desktop/src-tauri/gen/ +.scratch/ diff --git a/CHANGELOG.md b/CHANGELOG.md index f206e635..528072f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## Unreleased + +- **Desktop machine interface** (`serve --stdio`): JSON-RPC session for the coming desktop app, built on the MCP core. + Typed methods with argument schemas, structured results, progress notifications, cancellation, `project.inspect` + and `portfolio.status` (many projects; `live` adds App Store and Play status). Writes are dry runs unless the host + sends a single-use confirm token bound to the method, arguments and a short expiry (HMAC with a per-session secret + handed over on stdin). No submit / release / publish method exists. Under `serve`, terminal confirmations always + answer no. +- `--json` on `check` (and `check --aso`), `apple testflight status`, `apple ppo status`, `apple next-build`, + `play next-version-code`, `analytics compare` and `prices import` (read-only diff); new `inspect` command. +- `tools/build-sidecars.ts`: single-file executables for macOS (arm64, x64), Linux (x64, arm64) and Windows (x64), + re-signed ad hoc on macOS and checked for build-machine paths. The MCP server now also runs from such a binary. + ## 0.5.0 · 2026-10-11 Apps and games: storebound is for every mobile app, not only games, and the in-app catalog is complete on both stores. diff --git a/README.md b/README.md index 3e5b3549..6022cea3 100644 --- a/README.md +++ b/README.md @@ -174,6 +174,8 @@ run in the background with a log (`storebound shots render > .storebound/render. | `init [--profile app\|game\|subscription-app]` | local | copy the templates of a profile (default app), gitignore `.storebound/` | | `install --agent ` | local | skills + MCP entry for an AI tool | | `mcp` | local | stdio MCP server wrapping the commands | +| `serve --stdio` | local | JSON-RPC session for the storebound desktop app (see [Desktop machine interface](#desktop-machine-interface)) | +| `inspect [--json]` | local | offline summary of the config: name, store ids, languages, products | | `check` | local | config, copy limits, data safety, products, subscriptions, profile (delete-account URL, demo account, terms URL), files; warns on untranslated release notes | | `catalog diff [--store] [--threshold 10]` | API, read-only | one catalog vs both stores: missing / extra / mismatched products and subscriptions, US and override prices, locales, offers, per-region price differences between the stores; exit 1 on mismatches | | `check --aso` | local | keyword audit: App Store keyword field rules, Play stuffing / claims | @@ -376,6 +378,18 @@ per-request `_meta`, `resultType`, cacheable `tools/list`) and, on the same proc Manual config for a tool that `install` does not know: command `bunx` with args `["storebound", "mcp"]` (or the absolute path of `bin/storebound` plus `mcp`). +### Desktop machine interface + +`storebound serve --stdio` is what the desktop app (`apps/desktop`, in progress) runs as its sidecar: newline-delimited +JSON-RPC on the same core as the MCP server (tool list, validation, forbidden flags, child-process runner), with typed +methods (`check`, `validate`, `apple.status`, `play.listing`, ... plus `project.inspect` and `portfolio.status` over +many project folders), structured results (the commands' `--json` output), progress notifications and cancellation. +The first request is `session.hello` with a per-session secret only the host knows. Write methods are dry runs unless +the call carries a single-use confirm token (HMAC over method, arguments and expiry) that the host mints after the +owner confirmed a native dialog showing that dry run. There is no method that submits, releases or publishes; Play +testing releases and phased release changes stay out of the desktop profile too. Types: `cli/lib/desktop-protocol.ts`. +`bun tools/build-sidecars.ts` compiles the CLI for macOS, Linux and Windows (`bun build --compile`). + ## Safety model - **Credentials** live in env vars or the gitignored `.storebound/credentials.json`, never in the config or the repo. diff --git a/cli/analytics.ts b/cli/analytics.ts index 2df81f7d..9c581dc8 100644 --- a/cli/analytics.ts +++ b/cli/analytics.ts @@ -17,7 +17,7 @@ import { latestPerDate, mergeSeries, monthsBetween, parseGitLog, parseReport, pickReport, type PlayDay, playDaily, playObjects, playTotals, type Snapshot, } from './lib/analytics'; import { STORAGE_READ_SCOPE } from './lib/google-auth'; -import { done, log, warn } from './lib/log'; +import { done, log, printJson, warn } from './lib/log'; import { pct, textTable } from './lib/table'; import { googleClient } from './play/google'; @@ -145,6 +145,7 @@ export async function run(ctx: Ctx): Promise { const events = parseGitLog(g.stdout.toString()).reverse(); log(TAG, `${snaps.length} snapshot(s), ${series.apple.length} App Store day(s), ${series.play.length} Play day(s), ${events.length} store change(s) since ${first}`); const fx = compareAroundEvents(series, events, a.num('days', 7)); + if (a.has('json')) { printJson({ snapshots: snaps.length, since: first, series, effects: fx }); return; } console.log(a.has('md') ? effectMarkdown(fx) : effectTable(fx)); log(TAG, 'reading: a change needs several days on both sides and enough traffic; seasonality, featuring and ads move these numbers too'); return; diff --git a/cli/apple/next-build.ts b/cli/apple/next-build.ts index 0ee770cc..5c4a5601 100644 --- a/cli/apple/next-build.ts +++ b/cli/apple/next-build.ts @@ -5,6 +5,7 @@ // Then attach exactly that build: storebound apple listing --version x.y.z --build 42 (never "the latest"). import type { Ctx } from '../lib/ctx'; import { need } from '../lib/ctx'; +import { printJson } from '../lib/log'; import { nextBuildNumber } from '../lib/release'; import { ascClient } from './asc'; @@ -14,6 +15,7 @@ export async function run(ctx: Ctx): Promise { const appId = await c.app(); const builds = await c.all(`/v1/builds?filter[app]=${appId}&limit=200&fields[builds]=version`); const next = nextBuildNumber(builds.map(b => String(b.attributes.version))); + if (ctx.args.has('json')) { printJson({ next, builds: builds.length }); return; } console.error(`[apple] ${builds.length} builds on App Store Connect; next build number:`); console.log(next); } diff --git a/cli/apple/ppo.ts b/cli/apple/ppo.ts index de07de94..af8d2c71 100644 --- a/cli/apple/ppo.ts +++ b/cli/apple/ppo.ts @@ -1,5 +1,5 @@ // App Store Product Page Optimization through the App Store Connect API, wired to the `shots` variants. -// storebound apple ppo status +// storebound apple ppo status [--json] // storebound apple ppo create --variant b[,c] [--name "..."] [--traffic 30] [--dry] // storebound apple ppo upload --variant b [--experiment "..."] [--only en-US,tr] [--src store/renders] [--dry] // storebound apple ppo start | stop [--experiment "..."] [--dry] [--yes] @@ -13,7 +13,7 @@ import { existsSync } from 'node:fs'; import { join } from 'node:path'; import type { Ctx } from '../lib/ctx'; import { byAppleLocale, confirm, need } from '../lib/ctx'; -import { done, log, warn } from '../lib/log'; +import { done, log, printJson, warn } from '../lib/log'; import { checkCreate, createExperimentReq, defaultName, type Experiment, experimentFromApi, pickExperiment, planTreatmentLocales, planTreatments, startStopReq, } from '../lib/ppo'; @@ -44,6 +44,16 @@ export async function run(ctx: Ctx): Promise { const list = await experiments(c, appId); const locales = config.languages.map(l => l.apple).filter((x): x is string => !!x); + if (sub === 'status' && a.has('json')) { + const tests = []; + for (const x of list) { + const ts = []; + if (!['COMPLETED', 'STOPPED'].includes(x.state)) for (const t of await treatments(c, x.id)) ts.push({ id: t.id, name: t.attributes.name, locales: (await treatmentLocs(c, t.id)).length }); + tests.push({ ...x, treatments: ts }); + } + printJson({ tests }); + return; + } if (sub === 'status') { if (!list.length) { done(TAG, 'no Product Page Optimization tests (storebound apple ppo create --variant b)'); return; } console.log(textTable(['test', 'state', 'traffic', 'start', 'end'], list.map(x => [x.name, x.state, x.trafficProportion !== undefined ? `${x.trafficProportion}%` : '', (x.startDate ?? '').slice(0, 10), (x.endDate ?? '').slice(0, 10)]))); diff --git a/cli/apple/status.ts b/cli/apple/status.ts index 9cd5c249..31ef1253 100644 --- a/cli/apple/status.ts +++ b/cli/apple/status.ts @@ -7,7 +7,7 @@ // exit codes: 0 approved, 1 rejected, 7 timeout (2 = nothing in review) import type { Ctx } from '../lib/ctx'; import { confirm, need } from '../lib/ctx'; -import { log } from '../lib/log'; +import { log, printJson } from '../lib/log'; import { classifyReviewState, nextPollDelay, parseDuration, WAIT_EXIT } from '../lib/release'; import { type Asc, ascClient, type J } from './asc'; @@ -54,7 +54,7 @@ export async function run(ctx: Ctx): Promise { const builds = (await c.asc('GET', `/v1/builds?filter[app]=${appId}&sort=-uploadedDate&limit=5&include=preReleaseVersion`)); const iaps = await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`); const subs = await c.all(`/v1/reviewSubmissions?filter[app]=${appId}&limit=20`); - if (ctx.args.has('json')) { console.log(JSON.stringify({ app, versions, builds: builds.data, iaps, subs }, null, 2)); return; } + if (ctx.args.has('json')) { printJson({ app, versions, builds: builds.data, iaps, subs }); return; } console.log(`${app.attributes.name} · ${app.attributes.bundleId} · Apple ID ${appId}`); for (const v of versions) console.log(` version ${v.attributes.versionString.padEnd(8)} ${v.attributes.appVersionState ?? v.attributes.appStoreState}${v.relationships?.build?.data ? ' (build attached)' : ''}`); diff --git a/cli/apple/testflight.ts b/cli/apple/testflight.ts index 626b55fd..89db3ba5 100644 --- a/cli/apple/testflight.ts +++ b/cli/apple/testflight.ts @@ -1,5 +1,5 @@ // TestFlight through the App Store Connect API. -// storebound apple testflight status groups, testers per group, recent builds + beta states +// storebound apple testflight status [--json] groups, testers per group, recent builds + beta states // storebound apple testflight groups [--dry] create the groups of apple.testflight.groups that are missing // storebound apple testflight testers [--csv f] [--group a,b] [--remove] [--invite] [--dry] [--yes] // storebound apple testflight what-to-test --build N [--version x.y.z] [--locale en-US,tr] [--text "..."] [--dry] @@ -14,7 +14,7 @@ import { existsSync, readFileSync } from 'node:fs'; import type { Ctx } from '../lib/ctx'; import { confirm, need } from '../lib/ctx'; import { reviewContact } from '../lib/credentials'; -import { done, log, warn } from '../lib/log'; +import { done, log, printJson, warn } from '../lib/log'; import { textTable } from '../lib/table'; import { type ApiBuild, betaDescriptions, betaReadiness, betaReviewReq, buildsWithVersion, type Group, groupFromApi, inviteReq, maskEmail, @@ -52,21 +52,30 @@ export async function run(ctx: Ctx): Promise { if (sub === 'status') { const gs = await groups(c, appId); const rows: (string | number)[][] = []; + const jsonGroups: Record[] = []; for (const g of gs) { const testers = await c.all(`/v1/betaGroups/${g.id}/betaTesters?limit=200`); const builds = await c.all(`/v1/betaGroups/${g.id}/builds?limit=200`); + jsonGroups.push({ id: g.id, name: g.name, internal: g.internal, testers: testers.length, builds: g.internal && g.hasAccessToAllBuilds ? 'all' : builds.length, publicLink: !!g.publicLinkEnabled }); rows.push([g.name, g.internal ? 'internal' : 'external', testers.length, g.internal && g.hasAccessToAllBuilds ? 'all' : builds.length, g.publicLinkEnabled ? 'public link on' : '']); } - console.log(textTable(['group', 'kind', 'testers', 'builds', ''], rows)); const q = new URLSearchParams({ 'filter[app]': appId, include: 'preReleaseVersion,buildBetaDetail', sort: '-uploadedDate', limit: '8' }); const resp = await c.asc('GET', `/v1/builds?${q}`); const details = new Map((resp.included ?? []).filter((x: J) => x.type === 'buildBetaDetails').map((x: J) => [x.id, x.attributes] as const)); + const missingGroups = (tf?.groups ?? []).filter(w => !gs.some(g => g.name === w.name)).map(w => w.name); + if (a.has('json')) { + printJson({ groups: jsonGroups, builds: buildsWithVersion(resp).map(b => { + const d = details.get((b as J).relationships?.buildBetaDetail?.data?.id) as J; + return { version: b.marketing ?? null, build: b.attributes.version ?? null, processing: b.attributes.processingState ?? null, internal: d?.internalBuildState ?? null, external: d?.externalBuildState ?? null, uploaded: b.attributes.uploadedDate ?? null }; + }), missingGroups }); + return; + } + console.log(textTable(['group', 'kind', 'testers', 'builds', ''], rows)); console.log('\n' + textTable(['version', 'build', 'processing', 'internal', 'external', 'uploaded'], buildsWithVersion(resp).map(b => { const d = details.get((b as J).relationships?.buildBetaDetail?.data?.id) as J; return [b.marketing ?? '', b.attributes.version ?? '', b.attributes.processingState ?? '', d?.internalBuildState ?? '', d?.externalBuildState ?? '', (b.attributes.uploadedDate ?? '').slice(0, 10)]; }))); - const missing = (tf?.groups ?? []).filter(w => !gs.some(g => g.name === w.name)).map(w => w.name); - if (missing.length) warn(TAG, `configured but not on App Store Connect: ${missing.join(', ')} (storebound apple testflight groups)`); + if (missingGroups.length) warn(TAG, `configured but not on App Store Connect: ${missingGroups.join(', ')} (storebound apple testflight groups)`); return; } diff --git a/cli/check.ts b/cli/check.ts index 8c4309ff..e69099f3 100644 --- a/cli/check.ts +++ b/cli/check.ts @@ -3,6 +3,7 @@ // subscriptions + terms URL) and the files the config points at. No network; credentials are only checked for presence. // storebound check everything above // storebound check --aso keyword audit of both listing files (App Store keyword field, Play stuffing); exit 1 on errors +// --json structured result ({ ok, items, warnings, problems } or { findings, errors }), exit 1 on problems import { existsSync, readFileSync } from 'node:fs'; import { type AsoFinding, auditAso } from './lib/aso'; import { playCodes } from './lib/config'; @@ -10,7 +11,7 @@ import { APPLE_IAP_LIMITS, len, parseAppStoreListing, parsePlayListing } from '. import type { Ctx } from './lib/ctx'; import { dataSafetyRows } from './lib/data-safety'; import { reviewDemoAccount } from './lib/credentials'; -import { log, warn } from './lib/log'; +import { log, printJson, warn } from './lib/log'; import { profileIssues } from './lib/profile'; import { allSubscriptions } from './lib/subscriptions'; import { type CopyFile, validateCopy } from './shots/lib'; @@ -20,6 +21,7 @@ function aso(ctx: Ctx): void { const apple = config.apple ? parseAppStoreListing(readFileSync(resolve(config.apple.listing ?? 'store/appstore.md'), 'utf8')) : undefined; const play = config.play ? parsePlayListing(readFileSync(resolve(config.play.listing ?? 'store/listing.md'), 'utf8'), config.app.name) : undefined; const f: AsoFinding[] = auditAso({ apple, play, appName: config.app.name, storefront: ctx.args.get('storefront') ?? 'US' }); + if (ctx.args.has('json')) { const errors = f.filter(x => x.level === 'error').length; printJson({ findings: f, errors }); if (errors) process.exitCode = 1; return; } const tag = { error: 'ERROR', warn: 'warn ', info: 'info ' } as const; for (const x of f) console.log(`${tag[x.level]} [${x.where}] ${x.msg}`); const errors = f.filter(x => x.level === 'error').length; @@ -32,24 +34,29 @@ export async function run(ctx: Ctx): Promise { const { config, resolve, path } = ctx.loaded; log('check', `config ok: ${path}`); const problems: string[] = []; - const tryDo = (what: string, fn: () => string): void => { try { log('check', `${what}: ${fn()}`); } catch (e) { problems.push(`${what}: ${(e as Error).message}`); } }; + const items: { what: string; detail: string }[] = []; + const warnings: string[] = []; + const note = (msg: string): void => { warnings.push(msg); warn('check', msg); }; + const tryDo = (what: string, fn: () => string): void => { + try { const detail = fn(); items.push({ what, detail }); log('check', `${what}: ${detail}`); } catch (e) { problems.push(`${what}: ${(e as Error).message}`); } + }; if (config.play) tryDo('play listing', () => { const f = resolve(config.play!.listing ?? 'store/listing.md'); const copy = parsePlayListing(readFileSync(f, 'utf8'), config.app.name); const want = config.languages.flatMap(playCodes); const missing = want.filter(c => !copy.some(x => x.lang === c)); - if (missing.length) warn('check', `play listing has no section for ${missing.join(', ')}`); + if (missing.length) note(`play listing has no section for ${missing.join(', ')}`); const def = copy.find(x => x.lang === (config.play!.defaultLanguage ?? 'en-US')); const same = copy.filter(x => def && x !== def && x.whatsNew && x.whatsNew === def.whatsNew && x.lang.slice(0, 2) !== def.lang.slice(0, 2)); - if (same.length) warn('check', `what's new of ${same.map(x => x.lang).join(', ')} is the same text as ${def!.lang}: translate it`); + if (same.length) note(`what's new of ${same.map(x => x.lang).join(', ')} is the same text as ${def!.lang}: translate it`); return `${copy.length} languages`; }); if (config.apple) tryDo('appstore listing', () => { const f = resolve(config.apple!.listing ?? 'store/appstore.md'); const copy = parseAppStoreListing(readFileSync(f, 'utf8')); const missing = config.languages.filter(l => l.apple && !copy[l.apple]).map(l => l.apple); - if (missing.length) warn('check', `appstore listing has no section for ${missing.join(', ')}`); + if (missing.length) note(`appstore listing has no section for ${missing.join(', ')}`); return `${Object.keys(copy).length} locales`; }); if (config.dataSafety) tryDo('data safety', () => `${dataSafetyRows(config.dataSafety!).length - 1} CSV rows`); @@ -74,6 +81,7 @@ export async function run(ctx: Ctx): Promise { if (existsSync(resolve('.gitignore')) && !/^\/?\.storebound\/?$/m.test(readFileSync(resolve('.gitignore'), 'utf8'))) problems.push('.gitignore does not ignore .storebound/ (credentials live there)'); + if (ctx.args.has('json')) { printJson({ config: path, ok: !problems.length, items, warnings, problems }); if (problems.length) process.exitCode = 1; return; } if (problems.length) { for (const p of problems) console.error(` - ${p}`); throw new Error(`${problems.length} problems`); } log('check', 'all good'); } diff --git a/cli/health.ts b/cli/health.ts index fe56980e..a0b80d72 100644 --- a/cli/health.ts +++ b/cli/health.ts @@ -16,7 +16,7 @@ import { type AppleHealth, ANR_METRICS, betaCrashCounts, CRASH_METRICS, deviceBreakdown, healthFindings, healthMarkdown, type HealthSnapshot, healthTable, issuesQuery, latestDailyEnd, metricQuery, parseIssues, parseMetricRows, parsePerfPower, type PlayHealth, ymd, ymdString, } from './lib/health'; -import { done, log, warn } from './lib/log'; +import { done, log, printJson, warn } from './lib/log'; import { formatFindings } from './lib/validate-rules'; import { googleClient, REPORTING_API } from './play/google'; @@ -84,7 +84,7 @@ export async function run(ctx: Ctx): Promise { const days = a.num('days', 7); if (!(days >= 1 && days <= 90)) throw new Error('--days: 1-90'); const h = await collectHealth(ctx, { apple: both || a.has('apple'), play: both || a.has('play'), days }); - if (a.has('json')) { console.log(JSON.stringify(h, null, 2)); return; } + if (a.has('json')) { printJson(h); return; } console.log(healthTable(h)); console.log('\n' + formatFindings(healthFindings(h))); if (weekly) { diff --git a/cli/index.ts b/cli/index.ts index 52d73f33..58e85530 100755 --- a/cli/index.ts +++ b/cli/index.ts @@ -12,9 +12,11 @@ const PLAIN: Record Promise, string]> = { 'init': [() => import('./init'), 'copy the templates (config, listing, copy, declarations, privacy policy) into this project; --profile app|game|subscription-app (default app)'], '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)'], 'privacy-manifest': [() => import('./privacy-manifest'), 'iOS PrivacyInfo.xcprivacy + required-reason API + SDK manifest scan (--ios )'], }; const COMMANDS: Record Promise, string]> = { + 'inspect': [() => import('./inspect'), 'offline summary of the config (name, store ids, languages, products, subscriptions); --json'], 'check': [() => import('./check'), 'validate config, copy files, data safety answers, products, subscriptions and the app profile (offline); --aso keyword audit'], 'validate': [() => import('./validate'), 'read-only store readiness report with ordered blockers (--apple / --play), plus local renders checks (--no-local skips); exit 1 on blockers'], 'analytics': [() => import('./analytics'), 'setup (App Store report request) | snapshot (impressions, page views, installs, conversion -> .storebound/analytics) | compare (vs listing changes in git)'], diff --git a/cli/inspect.ts b/cli/inspect.ts new file mode 100644 index 00000000..dd93d148 --- /dev/null +++ b/cli/inspect.ts @@ -0,0 +1,28 @@ +// Offline summary of the project config: app name, store ids, languages, products, shots. No network, no credentials. +// storebound inspect [--json] +import type { Ctx } from './lib/ctx'; +import type { ProjectSummary } from './lib/desktop-protocol'; +import { log, printJson } from './lib/log'; + +export function summarize(ctx: Ctx): ProjectSummary { + const { config, root, path } = ctx.loaded; + return { + dir: root, + config: path, + name: config.app.name, + languages: config.languages.map(l => l.id), + play: config.play ? { packageName: config.play.packageName } : null, + apple: config.apple ? { bundleId: config.apple.bundleId, appId: config.apple.appId ?? null } : null, + products: config.products?.length ?? 0, + shots: !!config.shots, + testflightGroups: config.apple?.testflight?.groups?.length ?? 0, + }; +} + +export async function run(ctx: Ctx): Promise { + const s = summarize(ctx); + if (ctx.args.has('json')) { printJson(s); return; } + log('inspect', `${s.name} · ${s.languages.length} languages · ${s.products} products`); + log('inspect', `play ${s.play?.packageName ?? '-'} · apple ${s.apple?.bundleId ?? '-'}${s.apple?.appId ? ` (${s.apple.appId})` : ''}`); + log('inspect', `config ${s.config}`); +} diff --git a/cli/lib/config.ts b/cli/lib/config.ts index 93e5d978..b4ef28b0 100644 --- a/cli/lib/config.ts +++ b/cli/lib/config.ts @@ -617,14 +617,14 @@ export function validateConfig(c: unknown): string[] { export interface Loaded { config: ShipConfig; root: string; path: string; resolve(p: string): string } -const NAMES = ['storebound.config.ts', 'storebound.config.js', 'storebound.config.json']; +export const CONFIG_NAMES = ['storebound.config.ts', 'storebound.config.js', 'storebound.config.json']; /** Finds storebound.config.* from `start` upwards (or uses `explicit`), imports and validates it. */ export async function loadConfig(explicit?: string, start = process.cwd()): Promise { let path = explicit ? resolve(explicit) : ''; if (!path) { for (let d = resolve(start); ; d = dirname(d)) { - const hit = NAMES.map(n => join(d, n)).find(existsSync); + const hit = CONFIG_NAMES.map(n => join(d, n)).find(existsSync); if (hit) { path = hit; break; } if (dirname(d) === d) break; } diff --git a/cli/lib/confirm-token.ts b/cli/lib/confirm-token.ts new file mode 100644 index 00000000..e3344f94 --- /dev/null +++ b/cli/lib/confirm-token.ts @@ -0,0 +1,95 @@ +// Confirm tokens for `storebound serve --stdio` (the desktop app's sidecar protocol). +// +// A write method only runs for real (dryRun: false) with a token that the desktop host mints after the owner said yes +// in a native dialog showing the dry run. The token is an HMAC over the method, the canonical params and an expiry, +// keyed with a per-session secret the host generates and hands over in `session.hello` on stdin. Only the process that +// owns the sidecar's stdin (the Rust host) knows the secret; the webview never sees it, and child commands never get it +// (runner.ts strips STOREBOUND_SESSION* from their env, and the secret never is in the env to begin with). +// +// token = "sbt1." + expiryMs + "." + nonce + "." + base64url(HMAC-SHA256(secret, payload)) +// payload = "storebound-confirm-v1\n" + method + "\n" + canonical(params) + "\n" + expiryMs + "\n" + nonce +// +// Tokens are single use (nonce kept until expiry), live at most MAX_TTL_MS, and are bound to the exact method and +// params: another project, other arguments or another method do not verify. The Rust side (apps/desktop/src-tauri/ +// src/confirm.rs) implements the same scheme; both test the shared vector in tests/serve.test.ts and tests/confirm.rs. +import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto'; + +export const TOKEN_PREFIX = 'sbt1'; +export const DOMAIN = 'storebound-confirm-v1'; +/** A token may not be valid for longer than this (the host mints 60 s ones right after the dialog). */ +export const MAX_TTL_MS = 120_000; +export const MIN_SECRET_BYTES = 32; + +/** + * Canonical JSON: object keys sorted (by UTF-16 code units, like JS sort), no whitespace, strings escaped by + * JSON.stringify. Numbers must be safe integers so every language prints them the same way; undefined object + * members are dropped, like JSON.stringify does. + */ +export function canonical(v: unknown): string { + if (v === null) return 'null'; + if (typeof v === 'boolean') return v ? 'true' : 'false'; + if (typeof v === 'number') { + if (!Number.isSafeInteger(v)) throw new Error('canonical: only safe integers are allowed as numbers'); + return String(v); + } + if (typeof v === 'string') return JSON.stringify(v); + if (Array.isArray(v)) return `[${v.map(canonical).join(',')}]`; + if (typeof v === 'object') { + const o = v as Record; + const keys = Object.keys(o).filter(k => o[k] !== undefined).sort(); + return `{${keys.map(k => `${JSON.stringify(k)}:${canonical(o[k])}`).join(',')}}`; + } + throw new Error(`canonical: unsupported ${typeof v}`); +} + +const b64url = (b: Buffer): string => b.toString('base64url'); + +export function payload(method: string, params: unknown, expiry: number, nonce: string): string { + return `${DOMAIN}\n${method}\n${canonical(params)}\n${expiry}\n${nonce}`; +} + +export function mac(secret: Buffer, method: string, params: unknown, expiry: number, nonce: string): string { + return b64url(createHmac('sha256', secret).update(payload(method, params, expiry, nonce), 'utf8').digest()); +} + +/** Mints a token (the host does this in Rust; here for tests and tools). */ +export function mint(secret: Buffer, method: string, params: unknown, o: { now?: number; ttlMs?: number; nonce?: string } = {}): string { + const expiry = (o.now ?? Date.now()) + (o.ttlMs ?? 60_000); + const nonce = o.nonce ?? b64url(randomBytes(16)); + return `${TOKEN_PREFIX}.${expiry}.${nonce}.${mac(secret, method, params, expiry, nonce)}`; +} + +export function parseSecret(hex: unknown): Buffer { + if (typeof hex !== 'string' || !/^[0-9a-f]+$/i.test(hex) || hex.length % 2) throw new Error('secret: hex string expected'); + const b = Buffer.from(hex, 'hex'); + if (b.length < MIN_SECRET_BYTES) throw new Error(`secret: at least ${MIN_SECRET_BYTES} bytes`); + return b; +} + +export type VerifyError = 'malformed' | 'expired' | 'too-long' | 'replayed' | 'mismatch'; + +/** Verifies tokens of one session and remembers used nonces until they expire (replay protection). */ +export class TokenGuard { + private used = new Map(); + constructor(private readonly secret: Buffer, private readonly clock: () => number = Date.now) {} + + verify(token: unknown, method: string, params: unknown): { ok: true } | { ok: false; error: VerifyError } { + const now = this.clock(); + for (const [n, exp] of this.used) if (exp <= now) this.used.delete(n); + if (typeof token !== 'string') return { ok: false, error: 'malformed' }; + const parts = token.split('.'); + if (parts.length !== 4 || parts[0] !== TOKEN_PREFIX) return { ok: false, error: 'malformed' }; + const [, exp, nonce, sig] = parts as [string, string, string, string]; + if (!/^\d{1,16}$/.test(exp) || !/^[A-Za-z0-9_-]{16,64}$/.test(nonce) || !/^[A-Za-z0-9_-]{43}$/.test(sig)) return { ok: false, error: 'malformed' }; + const expiry = Number(exp); + let want: string; + try { want = mac(this.secret, method, params, expiry, nonce); } catch { return { ok: false, error: 'malformed' }; } + const a = Buffer.from(sig), b = Buffer.from(want); + if (a.length !== b.length || !timingSafeEqual(a, b)) return { ok: false, error: 'mismatch' }; + if (expiry <= now) return { ok: false, error: 'expired' }; + if (expiry - now > MAX_TTL_MS) return { ok: false, error: 'too-long' }; + if (this.used.has(nonce)) return { ok: false, error: 'replayed' }; + this.used.set(nonce, expiry); + return { ok: true }; + } +} diff --git a/cli/lib/ctx.ts b/cli/lib/ctx.ts index 79f97f5c..d85a96b1 100644 --- a/cli/lib/ctx.ts +++ b/cli/lib/ctx.ts @@ -21,8 +21,13 @@ export function byAppleLocale(langs: Language[]): Map { return new Map(langs.filter(l => l.apple).map(l => [l.apple!, l] as const)); } -/** Asks on the terminal unless --yes. Store actions that are public or irreversible go through this. */ +/** + * 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. + */ export async function confirm(ctx: Ctx, question: string): Promise { + if (process.env.STOREBOUND_SERVE === '1') { 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] `); diff --git a/cli/lib/desktop-protocol.ts b/cli/lib/desktop-protocol.ts new file mode 100644 index 00000000..bb2e2d04 --- /dev/null +++ b/cli/lib/desktop-protocol.ts @@ -0,0 +1,99 @@ +// Types of the `storebound serve --stdio` protocol (desktop profile). Type-only, no runtime code: the desktop app +// (apps/desktop) imports this file so both sides agree on shapes. Newline-delimited JSON-RPC 2.0 on stdio. +// +// Session: the first request must be `session.hello` with the per-session secret (hex, >= 32 bytes) the host +// generated. Every other method answers -32002 before that. One hello per process. +// Progress: notifications `progress` { requestId, line?, stream?, n?, total?, project? } while a request runs. +// Cancel: notification `$/cancelRequest` { id } (or MCP-style `notifications/cancelled` { requestId }); the request +// then answers -32800. +// Writes: every write method is a dry run unless `dryRun: false` comes with a `confirmToken` minted by the host for +// exactly (method, { project, args }) (cli/lib/confirm-token.ts). No method submits, releases or publishes anything. + +export const DESKTOP_PROTOCOL = 'storebound-desktop/1'; + +export const ERR = { + parse: -32700, + invalidRequest: -32600, + methodNotFound: -32601, + invalidParams: -32602, + internal: -32603, + notInitialized: -32002, + confirmRequired: -32010, + confirmInvalid: -32011, + cancelled: -32800, +} as const; + +export interface JsonSchemaLite { type: string; description?: string; enum?: (string | number)[]; default?: unknown; minimum?: number; maximum?: number; pattern?: string } + +export interface MethodDescriptor { + method: string; + title: string; + description: string; + kind: 'read' | 'write' | 'session' | 'system' | 'portfolio'; + /** Talks to a store API or the internet. */ + network: boolean; + /** Replaces existing data on a store (screenshots, whole forms). */ + destructive: boolean; + /** Result carries structured `data` (the command's --json output). */ + json: boolean; + /** Schema of `params.args` (tool methods), or of `params` (other methods). */ + args: { type: 'object'; properties: Record; required?: string[]; additionalProperties: false }; +} + +export interface HelloParams { secret: string; client?: { name: string; version: string } } +export interface HelloResult { protocol: typeof DESKTOP_PROTOCOL; server: { name: 'storebound'; version: string; compiled: boolean }; methods: MethodDescriptor[] } + +export interface Credentials { PLAY_SERVICE_ACCOUNT?: string; ASC_KEY_ID?: string; ASC_ISSUER_ID?: string; ASC_P8?: string } + +export interface ToolParams { + /** Absolute path of a folder that contains storebound.config.ts. */ + project: string; + args?: Record; + /** Write methods: false runs for real and needs confirmToken. Default true. */ + dryRun?: boolean; + confirmToken?: string; + /** Per-call credentials (kept in memory, passed to the command's env only). Not part of the token. */ + credentials?: Credentials; +} + +export interface ToolResult { + method: string; + ok: boolean; + exitCode: number; + dryRun: boolean; + /** The CLI line it ran, for logs ("storebound play listing --dry"). */ + command: string; + /** Text output (log lines), trimmed to the last 60 000 characters. */ + output: string; + /** Structured result of a --json capable command. */ + data?: unknown; +} + +export interface ProgressParams { requestId: string | number; line?: string; stream?: 'stdout' | 'stderr'; n?: number; total?: number; project?: string } + +export interface ProjectSummary { + dir: string; + config: string; + name: string; + languages: string[]; + play: { packageName: string } | null; + apple: { bundleId: string; appId: string | null } | null; + products: number; + shots: boolean; + testflightGroups: number; +} + +export interface PortfolioParams { projects: string[]; live?: boolean; credentials?: Credentials } + +export interface PortfolioEntry { + project: string; + ok: boolean; + summary: ProjectSummary | null; + check: { ok: boolean; problems: string[]; warnings: string[] } | null; + /** live only: `apple status --json` / `play status --json` data, or the error text. */ + apple?: { data?: unknown; error?: string }; + play?: { data?: unknown; error?: string }; + errors: string[]; +} + +export interface PortfolioResult { projects: PortfolioEntry[]; at: string } diff --git a/cli/lib/log.ts b/cli/lib/log.ts index 9d6c090a..ebe9e0ef 100644 --- a/cli/lib/log.ts +++ b/cli/lib/log.ts @@ -10,3 +10,15 @@ export const done = (tag: string, msg: string): void => console.log(`${stamp()} /** "3/14 de-DE" style counters. */ export const step = (i: number, n: number, what: string): string => `${String(i).padStart(String(n).length)}/${n} ${what}`; + +/** Prefix of the one machine-readable result line that `storebound serve --stdio` reads from a child command. */ +export const RESULT_MARK = '\u001estorebound-result '; + +/** + * Structured result of a `--json` run. In a terminal (or a pipe) it is pretty JSON on stdout as before; under + * `storebound serve` (STOREBOUND_MACHINE=1) it is one marked line, so log lines printed before it never break parsing. + */ +export function printJson(data: unknown): void { + if (process.env.STOREBOUND_MACHINE === '1') process.stdout.write(RESULT_MARK + JSON.stringify(data) + '\n'); + else console.log(JSON.stringify(data, null, 2)); +} diff --git a/cli/lib/runner.ts b/cli/lib/runner.ts new file mode 100644 index 00000000..1af8f758 --- /dev/null +++ b/cli/lib/runner.ts @@ -0,0 +1,79 @@ +// Runs one storebound command as a child process: the shared core of `storebound mcp` and `storebound serve --stdio`. +// Works from source (`bun cli/index.ts ...`) and from a `bun build --compile` binary (the desktop sidecar), where the +// binary re-executes itself. Output is streamed line by line (progress) and the `--json` result line is picked out. +import { join } from 'node:path'; +import { RESULT_MARK } from './log'; + +/** True inside a `bun build --compile` executable (the entry module lives in Bun's embedded file system). */ +export const compiled = (): boolean => /^(\/\$bunfs\/|[A-Z]:[\\/]~BUN[\\/])/.test(Bun.main); + +/** Command prefix that starts this storebound: the compiled binary itself, or bun + cli/index.ts. */ +export function selfCommand(): string[] { + return compiled() ? [process.execPath] : [process.execPath, join(import.meta.dir, '..', 'index.ts')]; +} + +export interface RunOptions { + cwd: string; + /** Extra environment for this call only (credentials from the desktop keychain, never written anywhere). */ + env?: Record; + /** Every output line as it arrives (stdout and stderr), without the machine result line. */ + onLine?: (line: string, stream: 'stdout' | 'stderr') => void; + /** Ask for the marked `--json` result line (STOREBOUND_MACHINE=1). */ + machine?: boolean; +} + +export interface RunResult { code: number; out: string; data?: unknown; cancelled: boolean } + +export interface Running { result: Promise; cancel(): void } + +/** Env names a caller may pass per call; anything else in `env` is ignored. */ +export const CALL_ENV = ['PLAY_SERVICE_ACCOUNT', 'ASC_KEY_ID', 'ASC_ISSUER_ID', 'ASC_P8'] as const; + +export function pickCallEnv(env: Record | undefined): Record { + const out: Record = {}; + for (const k of CALL_ENV) { const v = env?.[k]; if (typeof v === 'string' && v) out[k] = v; } + return out; +} + +/** Environment of a child: the parent's minus anything secret to the session, plus the per-call values. */ +export function childEnv(extra: Record = {}, machine = false): Record { + const base: Record = {}; + for (const [k, v] of Object.entries(process.env)) if (v !== undefined && !k.startsWith('STOREBOUND_SESSION')) base[k] = v; + return { ...base, ...extra, NO_COLOR: '1', ...(machine ? { STOREBOUND_MACHINE: '1', STOREBOUND_SERVE: '1' } : {}) }; +} + +async function pump(stream: ReadableStream, kind: 'stdout' | 'stderr', each: (line: string, kind: 'stdout' | 'stderr') => void): Promise { + const dec = new TextDecoder(); + let buf = ''; + const reader = stream.getReader(); + for (;;) { + const { value, done } = await reader.read(); + if (done) break; + buf += dec.decode(value, { stream: true }); + let nl: number; + while ((nl = buf.indexOf('\n')) >= 0) { each(buf.slice(0, nl).replace(/\r$/, ''), kind); buf = buf.slice(nl + 1); } + } + buf += dec.decode(); + if (buf) each(buf, kind); +} + +export function runCommand(argv: string[], o: RunOptions): Running { + const p = Bun.spawn([...selfCommand(), ...argv], { cwd: o.cwd, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', env: childEnv(o.env, o.machine) }); + let cancelled = false; + const lines: string[] = []; + let data: unknown; + const each = (line: string, kind: 'stdout' | 'stderr'): void => { + if (kind === 'stdout' && line.startsWith(RESULT_MARK)) { + try { data = JSON.parse(line.slice(RESULT_MARK.length)); } catch { lines.push(line); } + return; + } + lines.push(line); + o.onLine?.(line, kind); + }; + const result = (async (): Promise => { + await Promise.all([pump(p.stdout, 'stdout', each), pump(p.stderr, 'stderr', each)]); + const code = await p.exited; + return { code, out: lines.join('\n').trim(), ...(data === undefined ? {} : { data }), cancelled }; + })(); + return { result, cancel: () => { cancelled = true; p.kill(); } }; +} diff --git a/cli/mcp.ts b/cli/mcp.ts index 571042fb..04a552db 100644 --- a/cli/mcp.ts +++ b/cli/mcp.ts @@ -20,8 +20,8 @@ // Every tool runs the CLI as a child process in the project directory (STOREBOUND_PROJECT or the server's cwd) and // returns its output. stdout of this process carries protocol messages only; logs go to stderr. // Tool list and safety rules: mcp-tools.ts (write tools default to dry_run, nothing public or irreversible exposed). -import { join } from 'node:path'; import pkg from '../package.json' with { type: 'json' }; +import { runCommand, type Running } from './lib/runner'; import { listTools, TOOLS, toArgv, validateInput } from './mcp-tools'; /** Current (modern, stateless) revision. */ @@ -54,7 +54,6 @@ type Id = string | number; interface Msg { jsonrpc: '2.0'; id?: Id; method?: string; params?: Record } const MAX_OUTPUT = 60_000; -const CLI = join(import.meta.dir, 'index.ts'); const serverInfo = () => ({ name: 'storebound', title: 'storebound', version: pkg.version }); /** Era of one request: modern when its _meta names a modern (or unknown) protocol version, else legacy. */ @@ -117,17 +116,13 @@ export async function handle(m: Msg, run: (argv: string[], id: Id) => Promise<{ } } -const running = new Map>(); -function cancel(id: Id | undefined): void { if (id !== undefined) running.get(id)?.kill(); } +const running = new Map(); +function cancel(id: Id | undefined): void { if (id !== undefined) running.get(id)?.cancel(); } async function runCli(argv: string[], id: Id): Promise<{ code: number; out: string }> { - const cwd = process.env.STOREBOUND_PROJECT || process.cwd(); - const p = Bun.spawn([process.execPath, CLI, ...argv], { cwd, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', env: { ...process.env, NO_COLOR: '1' } }); - running.set(id, p); - try { - const [out, errText, code] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text(), p.exited]); - return { code, out: (out + (errText ? `\n${errText}` : '')).trim() }; - } finally { running.delete(id); } + const r = runCommand(argv, { cwd: process.env.STOREBOUND_PROJECT || process.cwd() }); + running.set(id, r); + try { const { code, out } = await r.result; return { code, out }; } finally { running.delete(id); } } export async function serve(): Promise { diff --git a/cli/play/next-version-code.ts b/cli/play/next-version-code.ts index d7a5b407..2d8bcb81 100644 --- a/cli/play/next-version-code.ts +++ b/cli/play/next-version-code.ts @@ -4,6 +4,7 @@ // ./gradlew bundleRelease -PversionCode=$(storebound play next-version-code) import type { Ctx } from '../lib/ctx'; import { need } from '../lib/ctx'; +import { printJson } from '../lib/log'; import { nextVersionCode } from '../lib/release'; import { playClient } from './client'; @@ -16,8 +17,11 @@ export async function run(ctx: Ctx): Promise { const apks = (await play.call<{ apks?: { versionCode: number }[] }>('GET', `${play.API}/edits/${e.id}/apks`).catch(() => ({ apks: [] }))).apks ?? []; const tracks = (await play.call<{ tracks?: { releases?: { versionCodes?: string[] }[] }[] }>('GET', `${play.API}/edits/${e.id}/tracks`)).tracks ?? []; const codes = [...bundles.map(b => b.versionCode), ...apks.map(a => a.versionCode), ...tracks.flatMap(t => (t.releases ?? []).flatMap(r => r.versionCodes ?? []))]; - console.error(`[play] ${codes.length} version codes seen; next versionCode:`); - console.log(nextVersionCode(codes)); + if (ctx.args.has('json')) printJson({ next: nextVersionCode(codes), seen: codes.length }); + else { + console.error(`[play] ${codes.length} version codes seen; next versionCode:`); + console.log(nextVersionCode(codes)); + } } finally { await play.call('DELETE', `${play.API}/edits/${e.id}`).catch(() => {}); } diff --git a/cli/play/status.ts b/cli/play/status.ts index 5525b25d..73668e3f 100644 --- a/cli/play/status.ts +++ b/cli/play/status.ts @@ -2,6 +2,7 @@ // storebound play status [--json] import type { Ctx } from '../lib/ctx'; import { need } from '../lib/ctx'; +import { printJson } from '../lib/log'; import { playClient } from './client'; import { listOneTimeProducts } from './products'; @@ -16,7 +17,7 @@ export async function run(ctx: Ctx): Promise { const listings = (await play.call<{ listings?: { language: string }[] }>('GET', `${play.API}/edits/${e.id}/listings`)).listings ?? []; const details = await play.call>('GET', `${play.API}/edits/${e.id}/details`); const products = await listOneTimeProducts(play); - if (ctx.args.has('json')) { console.log(JSON.stringify({ details, tracks, listings, products }, null, 2)); return; } + if (ctx.args.has('json')) { printJson({ details, tracks, listings, products }); return; } console.log(`${play.packageName}\n details: ${details.defaultLanguage} · ${details.contactEmail ?? '-'} · ${details.contactWebsite ?? '-'}`); console.log(` listings (${listings.length}): ${listings.map(l => l.language).join(', ') || '-'}`); for (const t of tracks) { diff --git a/cli/prices.ts b/cli/prices.ts index 555af5ff..220e8a56 100644 --- a/cli/prices.ts +++ b/cli/prices.ts @@ -13,7 +13,7 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs'; import { ascClient, type Asc, type J } from './apple/asc'; import type { Ctx } from './lib/ctx'; import { confirm, need } from './lib/ctx'; -import { done, log, step, warn } from './lib/log'; +import { done, log, printJson, step, warn } from './lib/log'; import { toMoney } from './lib/money'; import { appleSchedule, appleScheduleBody, applePriceRows, diffPrices, diffTable, parsePriceCsv, type PlayProduct, playPatchBody, playPriceRows, playRegions, @@ -96,10 +96,12 @@ export async function run(ctx: Ctx): Promise { const wantedAll = parsePriceCsv(readFileSync(csvPath, 'utf8'), { products: config.products!.map(p => p.id) }) .filter(r => products.some(p => p.id === r.product) && ((r.store === 'apple' && useApple) || (r.store === 'play' && usePlay))); const diff = diffPrices(current, wantedAll); - console.log(diffTable(diff, { all: a.has('all') })); const changed = new Set(diff.filter(d => d.change !== 'same').map(d => `${d.product}|${d.store}`)); const reconvert = a.has('reconvert'); if (reconvert && usePlay) for (const p of products) if (playProducts.has(p.id)) changed.add(`${p.id}|play`); + // --json is a read-only diff: it never writes, whatever the other flags say. + if (a.has('json')) { printJson({ csv: csvPath, diff: a.has('all') ? diff : diff.filter(d => d.change !== 'same'), changed: [...changed] }); return; } + console.log(diffTable(diff, { all: a.has('all') })); if (!changed.size) { done(TAG, 'prices up to date'); return; } log(TAG, `${changed.size} product / store pair(s) to update`); if (dry) { done(TAG, 'dry run: nothing written'); return; } diff --git a/cli/reviews.ts b/cli/reviews.ts index d9448e8e..0df436a6 100644 --- a/cli/reviews.ts +++ b/cli/reviews.ts @@ -13,7 +13,7 @@ import { join } from 'node:path'; import { ascClient, type J } from './apple/asc'; import type { Ctx } from './lib/ctx'; import { confirm } from './lib/ctx'; -import { done, log, warn } from './lib/log'; +import { done, log, printJson, warn } from './lib/log'; import { checkReply, type Draft, draftMarkdown, draftName, filterReviews, markSent, parseAppleReviews, parseDraft, parsePlayReviews, replyRequest, type Review, sendPlan, @@ -92,7 +92,7 @@ export async function run(ctx: Ctx): Promise { if (sub === 'list') { const rs = await collect(ctx, { since, unanswered: a.has('unanswered'), ratings }); - if (a.has('json')) { console.log(JSON.stringify(rs.map(({ author: _a, ...r }) => r), null, 2)); return; } + if (a.has('json')) { printJson(rs.map(({ author: _a, ...r }) => r)); return; } console.log(textTable(['store', 'date', 'stars', 'where', 'replied', 'review'], rs.map(r => [r.store, r.date.slice(0, 10), r.rating, r.where ?? '', r.reply ? 'yes' : '', snippet(r)]))); done(TAG, `${rs.length} review(s) in the last ${days} days, ${rs.filter(r => !r.reply).length} without a reply`); return; diff --git a/cli/serve.ts b/cli/serve.ts new file mode 100644 index 00000000..06985694 --- /dev/null +++ b/cli/serve.ts @@ -0,0 +1,306 @@ +// `storebound serve --stdio`: the machine interface the desktop app (apps/desktop) drives as a sidecar. +// Newline-delimited JSON-RPC 2.0 on stdin / stdout, logs on stderr. Protocol types: lib/desktop-protocol.ts. +// +// It reuses the MCP core: the same tool list (mcp-tools.ts: schemas, validation, argv building, the forbidden-flag +// rules) and the same child-process runner (lib/runner.ts). On top of that, the desktop profile adds: +// - a session handshake (`session.hello`) carrying the per-session secret of the host, +// - typed methods (one per tool, e.g. `play.listing`, plus project.inspect, portfolio.status, system.*), +// - structured results (`data`, the command's --json output), progress notifications and cancellation, +// - 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 { isAbsolute, join, resolve } from 'node:path'; +import pkg from '../package.json' with { type: 'json' }; +import { parseSecret, TokenGuard } from './lib/confirm-token'; +import { CONFIG_NAMES } from './lib/config'; +import { + DESKTOP_PROTOCOL, ERR, type MethodDescriptor, type PortfolioEntry, type PortfolioResult, type ProjectSummary, type ToolResult, +} from './lib/desktop-protocol'; +import { compiled, pickCallEnv, runCommand, type RunOptions, type Running } from './lib/runner'; +import { inputSchema, type ToolDef, TOOLS, toArgv, validateInput } from './mcp-tools'; + +type Id = string | number; +interface Msg { jsonrpc?: string; id?: Id | null; method?: string; params?: unknown } +type Json = Record; +export type Send = (msg: Json) => void; +export type Runner = (argv: string[], o: RunOptions) => Running; + +const MAX_OUTPUT = 60_000; + +/** MCP tools the desktop profile leaves out (sending builds to testers on Play, release state changes). */ +export const DESKTOP_EXCLUDED = new Set(['play_release_testing', 'apple_phased_release']); +/** Words no desktop method name may contain. */ +export const FORBIDDEN_METHOD_WORDS = /submit|release|publish|rollout|resume|complete|send|start|stop|cancel|delete|remove|invite/i; + +/** Read tools whose command prints a structured result with --json. */ +export const JSON_TOOLS = new Set(['check', 'check_aso', 'validate', 'health', 'reviews_list', 'prices_diff', 'analytics_compare', 'apple_status', + 'apple_next_build', 'play_status', 'play_next_version_code', 'shots_check', 'apple_testflight_status', 'apple_ppo_status']); + +/** `apple_testflight_status` -> `apple.testflight_status`: first underscore becomes the namespace dot. */ +export const methodName = (tool: string): string => tool.replace('_', '.'); + +export const DESKTOP_TOOLS: ToolDef[] = TOOLS.filter(t => !DESKTOP_EXCLUDED.has(t.name)); +const byMethod = new Map(DESKTOP_TOOLS.map(t => [methodName(t.name), t] as const)); + +function argsSchema(t: ToolDef): MethodDescriptor['args'] { + const s = inputSchema(t) as MethodDescriptor['args']; + const { dry_run: _d, ...properties } = s.properties; + return { ...s, properties }; +} + +const obj = (properties: MethodDescriptor['args']['properties'], required?: string[]): MethodDescriptor['args'] => + ({ type: 'object', properties, ...(required ? { required } : {}), additionalProperties: false }); + +const SYSTEM: MethodDescriptor[] = [ + { method: 'session.hello', title: 'Start the session', description: 'Hand over the per-session secret (hex, >= 32 bytes). Must be the first request.', kind: 'session', network: false, destructive: false, json: true, + args: obj({ secret: { type: 'string' }, client: { type: 'object' } }, ['secret']) }, + { method: 'system.version', title: 'Version', description: 'storebound version, platform and whether this is the compiled sidecar.', kind: 'system', network: false, destructive: false, json: true, args: obj({}) }, + { method: 'system.methods', title: 'Methods', description: 'Every method of this profile with its argument schema.', kind: 'system', network: false, destructive: false, json: true, args: obj({}) }, + { method: 'system.tools', title: 'Local tools', description: 'Which optional local tools are installed (git, ffmpeg, Google Chrome, Playwright); screenshot and video 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: 'portfolio.status', title: 'Portfolio status', description: 'Summary + offline check of many projects; with live, also 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']) }, +]; + +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, + network: t.network, destructive: !!t.destructive, json: !t.write && JSON_TOOLS.has(t.name), args: argsSchema(t), + }))]; +} + +class RpcError extends Error { + constructor(readonly code: number, message: string, readonly data?: unknown) { super(message); } +} + +/** Absolute folder with a storebound config in it, else an error. */ +export function checkProject(p: unknown): string { + if (typeof p !== 'string' || !p) throw new RpcError(ERR.invalidParams, 'project: absolute folder path required'); + if (!isAbsolute(p)) throw new RpcError(ERR.invalidParams, 'project: must be an absolute path'); + const dir = resolve(p); + let isDir = false; + try { isDir = statSync(dir).isDirectory(); } catch { /* missing */ } + if (!isDir) throw new RpcError(ERR.invalidParams, `project: not a folder: ${dir}`); + if (!CONFIG_NAMES.some(n => existsSync(join(dir, n)))) throw new RpcError(ERR.invalidParams, `project: no storebound.config.ts in ${dir}`); + return dir; +} + +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 { + if (v === undefined) return {}; + if (typeof v !== 'object' || v === null || Array.isArray(v)) throw new RpcError(ERR.invalidParams, 'credentials: object expected'); + return pickCallEnv(v as Record); +} + +/** One sidecar session: state is the secret (after hello), the token guard and the running requests. */ +export class Session { + private guard: TokenGuard | null = null; + private running = new Map>(); + private cancelled = new Set(); + + constructor(private readonly send: Send, private readonly run: Runner = runCommand, private readonly clock: () => number = Date.now) {} + + get ready(): boolean { return this.guard !== null; } + + /** Stops every running child (the host went away). */ + shutdown(): void { for (const set of this.running.values()) for (const r of set) r.cancel(); } + + /** Handles one incoming message; resolves with the response (or null for notifications). */ + async handle(m: Msg): Promise { + if (typeof m !== 'object' || m === null || Array.isArray(m)) return { jsonrpc: '2.0', id: null, error: { code: ERR.invalidRequest, message: 'Invalid request' } }; + if (m.id === undefined || m.id === null) { this.notification(m); return null; } + const id = m.id; + try { + const result = await this.dispatch(String(m.method ?? ''), (m.params ?? {}) as Json, id); + return { jsonrpc: '2.0', id, result }; + } catch (e) { + if (this.cancelled.has(id)) return { jsonrpc: '2.0', id, error: { code: ERR.cancelled, message: 'Request cancelled' } }; + const err = e instanceof RpcError ? e : new RpcError(ERR.internal, (e as Error).message); + return { jsonrpc: '2.0', id, error: { code: err.code, message: err.message, ...(err.data === undefined ? {} : { data: err.data }) } }; + } finally { + this.running.delete(id); + this.cancelled.delete(id); + } + } + + private notification(m: Msg): void { + const p = (m.params ?? {}) as Json; + if (m.method === '$/cancelRequest' || m.method === 'notifications/cancelled') { + const id = (p.id ?? p.requestId) as Id | undefined; + if (id === undefined) return; + this.cancelled.add(id); + for (const r of this.running.get(id) ?? []) r.cancel(); + } + } + + private track(id: Id, r: Running): Running { + if (this.cancelled.has(id)) r.cancel(); + let set = this.running.get(id); + if (!set) this.running.set(id, (set = new Set())); + set.add(r); + return r; + } + + private async dispatch(method: string, params: Json, id: Id): Promise { + if (typeof params !== 'object' || params === null || Array.isArray(params)) throw new RpcError(ERR.invalidParams, 'params must be an object'); + if (method === 'session.hello') { + if (this.guard) throw new RpcError(ERR.invalidRequest, 'session already started'); + let secret: Buffer; + try { secret = parseSecret(params.secret); } catch (e) { throw new RpcError(ERR.invalidParams, (e as Error).message); } + this.guard = new TokenGuard(secret, this.clock); + return { protocol: DESKTOP_PROTOCOL, server: { name: 'storebound', version: pkg.version, compiled: compiled() }, methods: describeMethods() }; + } + if (!this.guard) throw new RpcError(ERR.notInitialized, 'session.hello first'); + switch (method) { + case 'system.version': return { version: pkg.version, compiled: compiled(), platform: process.platform, arch: process.arch, bun: Bun.version }; + case 'system.methods': return { methods: describeMethods() }; + case 'system.tools': return localTools(); + case 'project.inspect': return this.inspect(checkProject(params.project), {}, id); + case 'portfolio.status': return this.portfolio(params, id); + } + const tool = byMethod.get(method); + if (!tool) throw new RpcError(ERR.methodNotFound, `Method not found: ${method}`); + return this.tool(method, tool, params, id); + } + + private async tool(method: string, t: ToolDef, params: Json, id: Id): Promise { + 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 = 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'); + const problems = validateInput(t, args); + if (problems.length) throw new RpcError(ERR.invalidParams, `Invalid arguments: ${problems.join('; ')}`, { problems }); + const env = credentialsOf(params.credentials); + let dryRun = true; + if (params.dryRun === false) { + if (!t.write) dryRun = false; + else { + if (params.confirmToken === undefined) throw new RpcError(ERR.confirmRequired, `${method} writes: dryRun false needs a confirmToken from the desktop host`); + const v = this.guard!.verify(params.confirmToken, method, { project, args }); + if (!v.ok) throw new RpcError(ERR.confirmInvalid, `confirm token rejected: ${v.error}`, { reason: v.error }); + dryRun = false; + } + } else if (params.dryRun !== undefined && params.dryRun !== true) throw new RpcError(ERR.invalidParams, 'dryRun must be a boolean'); + if (!t.write) dryRun = false; + 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; + 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'); + return { + method, ok: res.code === 0, exitCode: res.code, dryRun: t.write ? dryRun : false, command: `storebound ${argv.join(' ')}`, output: cut(res.out), + ...(res.data === undefined ? {} : { data: res.data }), + }; + } + + private progress(id: Id, p: Json): void { + this.send({ jsonrpc: '2.0', method: 'progress', params: { requestId: id, ...p } }); + } + + private async inspect(project: string, env: Record, id: Id): Promise { + const r = await this.track(id, this.run(['inspect', '--json'], { cwd: project, env, machine: true })).result; + if (r.cancelled) throw new RpcError(ERR.cancelled, 'Request cancelled'); + if (r.code !== 0 || !r.data) throw new RpcError(ERR.invalidParams, `project: ${lastLine(r.out) || 'config could not be loaded'}`); + return r.data as ProjectSummary; + } + + private async portfolio(params: Json, id: Id): Promise { + const list = params.projects; + if (!Array.isArray(list) || !list.length || list.length > 200) throw new RpcError(ERR.invalidParams, 'projects: 1-200 absolute folder paths'); + const live = params.live === true; + const env = credentialsOf(params.credentials); + const out: PortfolioEntry[] = new Array(list.length); + let done = 0; + const one = async (i: number): Promise => { + const raw = list[i]; + const e: PortfolioEntry = { project: String(raw), ok: false, summary: null, check: null, errors: [] }; + out[i] = e; + try { + const dir = checkProject(raw); + e.project = dir; + const summary = e.summary = await this.inspect(dir, env, id); + 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; + return r.code === 0 && r.data !== undefined ? { data: r.data } : { error: lastLine(r.out) || `exit ${r.code}` }; + }; + const [apple, play] = await Promise.all([summary.apple ? store(['apple', 'status', '--json']) : undefined, summary.play ? store(['play', 'status', '--json']) : undefined]); + if (apple) e.apple = apple; + if (play) e.play = play; + } + e.ok = e.check.ok && !e.apple?.error && !e.play?.error; + } catch (err) { + if (this.cancelled.has(id)) throw err; + e.errors.push((err as Error).message); + } + this.progress(id, { n: ++done, total: list.length, project: e.project }); + }; + // A few projects at a time: each one is a few child processes (and API calls when live). + let next = 0; + await Promise.all(Array.from({ length: Math.min(3, list.length) }, async () => { while (next < list.length) await one(next++); })); + if (this.cancelled.has(id)) throw new RpcError(ERR.cancelled, 'Request cancelled'); + return { projects: out, at: new Date(this.clock()).toISOString() }; + } +} + +const lastLine = (s: string): string => s.trim().split('\n').filter(Boolean).at(-1)?.replace(/^error:\s*/, '') ?? ''; + +export function localTools(): Json { + const which = (n: string): string | null => Bun.which(n); + const chrome = process.platform === 'darwin' ? existsSync('/Applications/Google Chrome.app') + : process.platform === 'win32' ? [process.env['PROGRAMFILES'], process.env['PROGRAMFILES(X86)'], process.env.LOCALAPPDATA].some(d => d && existsSync(join(d, 'Google/Chrome/Application/chrome.exe'))) + : !!(which('google-chrome') || which('google-chrome-stable') || which('chromium')); + const ffmpeg = which('ffmpeg'); + return { + git: !!which('git'), ffmpeg: !!ffmpeg, chrome, + notes: [ + ...(ffmpeg ? [] : ['ffmpeg not found: icons, screenshot renders and app preview videos need it (brew install ffmpeg / apt install ffmpeg / winget install ffmpeg)']), + ...(chrome ? [] : ['Google Chrome not found: screenshot renders and web captures need Chrome or Playwright\'s Chromium in the project']), + ], + }; +} + +export async function serveStdio(): Promise { + const send: Send = o => { process.stdout.write(JSON.stringify(o) + '\n'); }; + const session = new Session(send); + console.error(`[storebound serve] ${pkg.version} on stdio (${DESKTOP_PROTOCOL}), waiting for session.hello`); + let buf = ''; + const decoder = new TextDecoder(); + const reader = Bun.stdin.stream().getReader(); + for (;;) { + const { value, done } = await reader.read(); + if (done) break; + buf += decoder.decode(value, { stream: true }); + let nl: number; + while ((nl = buf.indexOf('\n')) >= 0) { + const line = buf.slice(0, nl).trim(); + buf = buf.slice(nl + 1); + if (!line) continue; + let msg: Msg; + try { msg = JSON.parse(line) as Msg; } catch { send({ jsonrpc: '2.0', id: null, error: { code: ERR.parse, message: 'Parse error' } }); continue; } + if (Array.isArray(msg)) { send({ jsonrpc: '2.0', id: null, error: { code: ERR.invalidRequest, message: 'Batches are not supported' } }); continue; } + // The handshake must finish before anything else is read, so a request right behind it sees the session. + if (!session.ready && msg.method === 'session.hello') { const r = await session.handle(msg); if (r) send(r); continue; } + session.handle(msg).then(r => { if (r) send(r); }, e => send({ jsonrpc: '2.0', id: msg.id ?? null, error: { code: ERR.internal, message: String((e as Error).message) } })); + } + } + // stdin closed: the host is gone; stop what still runs. + session.shutdown(); + process.exit(0); +} + +export async function run(args: { has(n: string): boolean }): Promise { + if (!args.has('stdio')) { + console.error('usage: storebound serve --stdio (JSON-RPC for the storebound desktop app; for AI tools use `storebound mcp`)'); + process.exit(2); + } + await serveStdio(); +} diff --git a/cli/shots/check.ts b/cli/shots/check.ts index bd2539e4..00a64dc9 100644 --- a/cli/shots/check.ts +++ b/cli/shots/check.ts @@ -11,7 +11,7 @@ import { existsSync, readdirSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; import type { ShipConfig } from '../lib/config'; import type { Ctx } from '../lib/ctx'; -import { log } from '../lib/log'; +import { log, printJson } from '../lib/log'; import { checkFrames, type FrameIssue } from './devices'; import { defaultSizes, frameDims, SIZES } from './lib'; import type { LocalIssue, RendersCheck } from '../lib/validate-rules'; @@ -64,7 +64,7 @@ export async function run(ctx: Ctx): Promise { const cap = config.shots?.capture; const frameIssues = cap?.source === 'folder' ? checkFrameFolder(config, resolve(cap.folder ?? config.shots!.frames), scan.langs) : []; if (ctx.args.has('json')) { - console.log(JSON.stringify({ images: scan.images.length, videos: scan.videos.length, issues, frames: frameIssues }, null, 2)); + printJson({ images: scan.images.length, videos: scan.videos.length, issues, frames: frameIssues }); } else { for (const { where, issue } of issues) console.log(`${issue.level === 'error' ? 'ERROR' : 'warn '} ${where}: ${issue.msg}`); for (const f of frameIssues) console.log(`ERROR frames/${f.file}: ${f.msg}`); diff --git a/cli/validate.ts b/cli/validate.ts index 81799224..0fb06c68 100644 --- a/cli/validate.ts +++ b/cli/validate.ts @@ -19,7 +19,7 @@ import type { Ctx } from './lib/ctx'; import { checkUrl } from './lib/http'; import { collectHealth } from './health'; import { healthFindings } from './lib/health'; -import { log, warn } from './lib/log'; +import { log, printJson, warn } from './lib/log'; import { type AppleSnapshot, appleRules, type Finding, formatFindings, PLAY_REQUIRED_IMAGES, type PlaySnapshot, playRules, type ProfileFacts, rendersFindings, sortFindings } from './lib/validate-rules'; import { rendersCheck } from './shots/check'; import { playClient } from './play/client'; @@ -177,7 +177,7 @@ export async function run(ctx: Ctx): Promise { findings.push(...sortFindings(healthFindings(h, { unreadable: 'ok' }))); } const blockers = findings.filter(f => f.level === 'blocker').length; - if (a.has('json')) console.log(JSON.stringify({ blockers, findings }, null, 2)); + if (a.has('json')) printJson({ blockers, findings }); else { console.log(formatFindings(findings)); log('validate', blockers ? `${blockers} blocker(s)` : 'no blockers (UI-only steps are not visible to the API: App Privacy, Play App content)'); diff --git a/tests/serve.test.ts b/tests/serve.test.ts new file mode 100644 index 00000000..63930ac1 --- /dev/null +++ b/tests/serve.test.ts @@ -0,0 +1,243 @@ +import { describe, expect, test } from 'bun:test'; +import { existsSync, mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { canonical, mac, MAX_TTL_MS, mint, parseSecret, TokenGuard } from '../cli/lib/confirm-token'; +import { ERR } from '../cli/lib/desktop-protocol'; +import { childEnv, pickCallEnv, type RunOptions, type Running } from '../cli/lib/runner'; +import { FORBIDDEN_ARGS, TOOLS } from '../cli/mcp-tools'; +import { describeMethods, DESKTOP_TOOLS, FORBIDDEN_METHOD_WORDS, JSON_TOOLS, methodName, Session } from '../cli/serve'; +import { buildOne, hostTarget, leaks } from '../tools/build-sidecars'; + +type J = Record; +const ROOT = join(import.meta.dir, '..'); +const DEMO = join(ROOT, 'examples/demo-game'); +const SECRET_HEX = Array.from({ length: 32 }, (_, i) => i.toString(16).padStart(2, '0')).join(''); +const SECRET = Buffer.from(SECRET_HEX, 'hex'); + +interface Call { argv: string[]; o: RunOptions } +function fakeRunner(reply: (argv: string[]) => { code?: number; out?: string; data?: unknown; lines?: string[]; wait?: Promise } = () => ({})) { + const calls: Call[] = []; + const run = (argv: string[], o: RunOptions): Running => { + calls.push({ argv, o }); + const r = reply(argv); + let cancelled = false; + let release: () => void = () => {}; + const gate = new Promise(res => { release = res; }); + const result = (async () => { + for (const l of r.lines ?? []) o.onLine?.(l, 'stdout'); + if (r.wait) await Promise.race([r.wait, gate]); + return { code: cancelled ? 143 : r.code ?? 0, out: r.out ?? '', ...(r.data === undefined ? {} : { data: r.data }), cancelled }; + })(); + return { result, cancel: () => { cancelled = true; release(); } }; + }; + return { calls, run }; +} + +async function session(reply?: Parameters[0], clock: () => number = Date.now) { + const sent: J[] = []; + const f = fakeRunner(reply); + const s = new Session(m => sent.push(m), f.run, clock); + let id = 0; + const call = async (method: string, params: unknown = {}) => (await s.handle({ jsonrpc: '2.0', id: ++id, method, params }))!; + const hello = await call('session.hello', { secret: SECRET_HEX, client: { name: 'test', version: '1' } }); + return { s, sent, calls: f.calls, call, hello, nextId: () => id + 1 }; +} +const errOf = (r: J) => r.error as { code: number; message: string; data?: J }; +const resOf = (r: J) => r.result as J; + +describe('confirm tokens', () => { + test('canonical JSON: sorted keys, no whitespace, safe integers only', () => { + expect(canonical({ b: 1, a: [true, null, 'x'], c: { z: '', y: undefined } })).toBe('{"a":[true,null,"x"],"b":1,"c":{"z":""}}'); + expect(() => canonical({ f: 0.5 })).toThrow(); + expect(() => canonical({ f: 2 ** 60 })).toThrow(); + }); + test('shared vector (the Rust host tests the same one in src-tauri/tests/confirm.rs)', () => { + const p = { project: '/tmp/game', args: { only: 'en-US,tr', b: [1, true, null, 'ü"\n'] } }; + expect(canonical(p)).toBe('{"args":{"b":[1,true,null,"ü\\"\\n"],"only":"en-US,tr"},"project":"/tmp/game"}'); + expect(mac(SECRET, 'play.listing', p, 1700000060000, 'AAAAAAAAAAAAAAAAAAAAAA')).toBe('JhSxUL2ej4cm4yrmlcA23rTCPq3YMKJthbB7n6aixxw'); + }); + test('binding, expiry, max lifetime, replay', () => { + let now = 1_000_000; + const g = new TokenGuard(SECRET, () => now); + const p = { project: '/p', args: { only: 'en-US' } }; + const t = mint(SECRET, 'play.listing', p, { now }); + expect(g.verify(t, 'play.listing', { project: '/p', args: { only: 'tr' } })).toEqual({ ok: false, error: 'mismatch' }); + expect(g.verify(t, 'play.listing', { project: '/q', args: { only: 'en-US' } })).toEqual({ ok: false, error: 'mismatch' }); + expect(g.verify(t, 'play.images', p)).toEqual({ ok: false, error: 'mismatch' }); + expect(g.verify(mint(Buffer.alloc(32, 7), 'play.listing', p, { now }), 'play.listing', p)).toEqual({ ok: false, error: 'mismatch' }); + expect(g.verify(t, 'play.listing', p)).toEqual({ ok: true }); + expect(g.verify(t, 'play.listing', p)).toEqual({ ok: false, error: 'replayed' }); + const old = mint(SECRET, 'play.listing', p, { now, ttlMs: 1000 }); + now += 1000; + expect(g.verify(old, 'play.listing', p)).toEqual({ ok: false, error: 'expired' }); + expect(g.verify(mint(SECRET, 'play.listing', p, { now, ttlMs: MAX_TTL_MS + 1 }), 'play.listing', p)).toEqual({ ok: false, error: 'too-long' }); + for (const bad of [undefined, '', 'sbt1', 'sbt2.1.AAAAAAAAAAAAAAAAAAAAAA.x', `sbt1.${now + 5000}.short.${'A'.repeat(43)}`, t + 'x']) + expect(g.verify(bad, 'play.listing', p).ok).toBe(false); + }); + test('secrets: hex, at least 32 bytes', () => { + expect(parseSecret(SECRET_HEX).length).toBe(32); + expect(() => parseSecret('abcd')).toThrow(); + expect(() => parseSecret('zz'.repeat(32))).toThrow(); + expect(() => parseSecret(42)).toThrow(); + }); +}); + +describe('serve --stdio: methods', () => { + test('nothing submits, releases or publishes', () => { + const names = describeMethods().map(m => m.method); + for (const n of names) expect(n).not.toMatch(FORBIDDEN_METHOD_WORDS); + for (const n of ['apple.submit', 'apple.release', 'play.release', 'play.release_testing', 'apple.phased_release', 'play.rollout', 'reviews.send', 'apple.ppo_start', 'prices.import']) + expect(names).not.toContain(n); + // every desktop tool still goes through the MCP rules: no forbidden flag can come out of any of them + for (const t of DESKTOP_TOOLS) expect(t.command.some(c => FORBIDDEN_ARGS.includes(c))).toBe(false); + expect(new Set(names).size).toBe(names.length); + }); + test('typed descriptors for every tool; json flags only on read tools', () => { + const ms = describeMethods(); + expect(ms.filter(m => m.kind === 'read' || m.kind === 'write').length).toBe(DESKTOP_TOOLS.length + 1); // + project.inspect + for (const m of ms) { expect(m.args.type).toBe('object'); expect(m.args.additionalProperties).toBe(false); expect(m.args.properties.dry_run).toBeUndefined(); } + for (const t of JSON_TOOLS) expect(TOOLS.find(x => x.name === t)?.write).toBe(false); + expect(ms.map(m => m.method)).toEqual(expect.arrayContaining(['portfolio.status', 'project.inspect', 'check', 'validate', 'apple.status', 'play.status', 'reviews.list', 'apple.testflight_status'])); + expect(methodName('apple_testflight_status')).toBe('apple.testflight_status'); + }); +}); + +describe('serve --stdio: session', () => { + test('hello first, once, with a real secret', async () => { + const s = new Session(() => {}, fakeRunner().run); + expect(errOf((await s.handle({ jsonrpc: '2.0', id: 1, method: 'system.version' }))!).code).toBe(ERR.notInitialized); + expect(errOf((await s.handle({ jsonrpc: '2.0', id: 2, method: 'session.hello', params: { secret: 'ab' } }))!).code).toBe(ERR.invalidParams); + const ok = resOf((await s.handle({ jsonrpc: '2.0', id: 3, method: 'session.hello', params: { secret: SECRET_HEX } }))!); + expect(ok.protocol).toBe('storebound-desktop/1'); + expect((ok.methods as unknown[]).length).toBe(describeMethods().length); + expect(errOf((await s.handle({ jsonrpc: '2.0', id: 4, method: 'session.hello', params: { secret: SECRET_HEX } }))!).code).toBe(ERR.invalidRequest); + expect(resOf((await s.handle({ jsonrpc: '2.0', id: 5, method: 'system.version' }))!).version).toBeString(); + expect(errOf((await s.handle({ jsonrpc: '2.0', id: 6, method: 'apple.submit', params: { project: DEMO } }))!).code).toBe(ERR.methodNotFound); + }); + test('read method: --json appended, data and progress passed through, credentials only as per-call env', async () => { + const { call, calls, sent } = await session(() => ({ data: { blockers: 0, findings: [] }, out: 'log line', lines: ['12:00:00 [validate] apple'] })); + const r = resOf(await call('validate', { project: DEMO, args: { store: 'apple' }, credentials: { ASC_KEY_ID: 'K', HOME: '/evil', ASC_P8: '' } })); + expect(calls[0]!.argv).toEqual(['validate', '--apple', '--json']); + expect(calls[0]!.o).toMatchObject({ cwd: DEMO, machine: true, env: { ASC_KEY_ID: 'K' } }); + expect(Object.keys(calls[0]!.o.env!)).toEqual(['ASC_KEY_ID']); + expect(r).toMatchObject({ ok: true, exitCode: 0, dryRun: false, data: { blockers: 0 }, command: 'storebound validate --apple --json' }); + expect(sent).toContainEqual({ jsonrpc: '2.0', method: 'progress', params: { requestId: 2, line: '12:00:00 [validate] apple', stream: 'stdout' } }); + }); + test('bad params: relative or config-less project, unknown args, dry_run inside args', async () => { + const { call } = await session(); + expect(errOf(await call('check', { project: 'examples/demo-game' })).code).toBe(ERR.invalidParams); + expect(errOf(await call('check', { project: tmpdir() })).message).toContain('no storebound.config.ts'); + expect(errOf(await call('check', { project: DEMO, args: { nope: 1 } })).code).toBe(ERR.invalidParams); + expect(errOf(await call('play.listing', { project: DEMO, args: { dry_run: false } })).code).toBe(ERR.invalidParams); + expect(errOf(await call('check', { project: DEMO, extra: true })).code).toBe(ERR.invalidParams); + expect(errOf(await call('play.listing', { project: DEMO, args: { only: '--yes' } })).code).toBe(ERR.invalidParams); + }); + test('writes: dry run by default; real run only with a matching, fresh, unused host token', async () => { + let now = 5_000_000; + const { call, calls } = await session(undefined, () => now); + const p = { project: DEMO, args: { only: 'en-US' } }; + expect(resOf(await call('play.listing', p))).toMatchObject({ dryRun: true }); + expect(calls[0]!.argv).toEqual(['play', 'listing', '--only', 'en-US', '--dry']); + expect(errOf(await call('play.listing', { ...p, dryRun: false })).code).toBe(ERR.confirmRequired); + const token = mint(SECRET, 'play.listing', p, { now }); + expect(errOf(await call('play.listing', { ...p, args: { only: 'tr-TR' }, dryRun: false, confirmToken: token })).code).toBe(ERR.confirmInvalid); + expect(errOf(await call('play.images', { ...p, dryRun: false, confirmToken: token })).code).toBe(ERR.confirmInvalid); + const real = resOf(await call('play.listing', { ...p, dryRun: false, confirmToken: token, credentials: { PLAY_SERVICE_ACCOUNT: '{}' } })); + expect(real).toMatchObject({ dryRun: false }); + expect(calls.at(-1)!.argv).toEqual(['play', 'listing', '--only', 'en-US']); + const replay = errOf(await call('play.listing', { ...p, dryRun: false, confirmToken: token })); + expect(replay).toMatchObject({ code: ERR.confirmInvalid, data: { reason: 'replayed' } }); + const soon = mint(SECRET, 'play.listing', p, { now, ttlMs: 10 }); + now += 11; + expect(errOf(await call('play.listing', { ...p, dryRun: false, confirmToken: soon })).data).toEqual({ reason: 'expired' }); + // a read method never needs a token, and dryRun false on it is just a normal run + expect(resOf(await call('check', { project: DEMO, dryRun: false })).dryRun).toBe(false); + }); + test('cancellation answers -32800 and kills the child', async () => { + const { s, call, nextId } = await session(() => ({ wait: new Promise(() => {}) })); + const id = nextId(); + const pending = call('validate', { project: DEMO }); + await Bun.sleep(5); + await s.handle({ jsonrpc: '2.0', method: '$/cancelRequest', params: { id } }); + expect(errOf(await pending).code).toBe(ERR.cancelled); + }); + test('portfolio.status: many projects, per-project errors, progress n/total', async () => { + const { call, sent } = await session(argv => argv[0] === 'inspect' ? { data: { name: 'Demo', apple: { bundleId: 'a.b' }, play: null } } + : argv[0] === 'check' ? { data: { ok: true, problems: [], warnings: ['w'] } } + : argv[0] === 'apple' ? { code: 1, out: 'error: ASC_KEY_ID and ASC_ISSUER_ID are not set' } : {}); + const r = resOf(await call('portfolio.status', { projects: [DEMO, '/nope/game'], live: true })) as { projects: J[] }; + expect(r.projects[0]).toMatchObject({ project: DEMO, summary: { name: 'Demo' }, check: { ok: true, warnings: ['w'] }, apple: { error: 'ASC_KEY_ID and ASC_ISSUER_ID are not set' }, ok: false }); + expect(r.projects[0]!.play).toBeUndefined(); + expect(r.projects[1]).toMatchObject({ ok: false, summary: null }); + expect((r.projects[1]!.errors as string[])[0]).toContain('not a folder'); + const prog = sent.filter(m => m.method === 'progress').map(m => (m.params as J).n); + expect(prog.sort()).toEqual([1, 2]); + expect(errOf(await call('portfolio.status', { projects: [] })).code).toBe(ERR.invalidParams); + }); + test('children never inherit session secrets; only credential names pass', () => { + process.env.STOREBOUND_SESSION_SECRET = 'x'; + try { expect(childEnv({}, true).STOREBOUND_SESSION_SECRET).toBeUndefined(); } finally { delete process.env.STOREBOUND_SESSION_SECRET; } + expect(childEnv({}, true)).toMatchObject({ STOREBOUND_MACHINE: '1', STOREBOUND_SERVE: '1', NO_COLOR: '1' }); + expect(pickCallEnv({ PATH: '/x', ASC_ISSUER_ID: 'i', ASC_P8: 3 })).toEqual({ ASC_ISSUER_ID: 'i' }); + }); +}); + +/** Talks to a real `storebound serve --stdio` process (source or compiled). */ +async function stdioRoundTrip(cmd: string[]): Promise { + const p = Bun.spawn([...cmd, 'serve', '--stdio'], { cwd: ROOT, stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' }); + const lines = [ + { jsonrpc: '2.0', id: 1, method: 'system.version' }, + { jsonrpc: '2.0', id: 2, method: 'session.hello', params: { secret: SECRET_HEX } }, + { jsonrpc: '2.0', id: 3, method: 'project.inspect', params: { project: DEMO } }, + { jsonrpc: '2.0', id: 4, method: 'shots.check', params: { project: DEMO } }, + { jsonrpc: '2.0', id: 5, method: 'play.listing', params: { project: DEMO, dryRun: false, confirmToken: 'sbt1.1.AAAAAAAAAAAAAAAAAAAAAA.' + 'A'.repeat(43) } }, + ]; + // hello must be answered before the next request is read: send the version probe, then the rest + p.stdin.write(lines.map(l => JSON.stringify(l)).join('\n') + '\n'); + await p.stdin.flush(); + const out: J[] = []; + const reader = p.stdout.getReader(); + const dec = new TextDecoder(); + let buf = ''; + const deadline = Date.now() + 25_000; + while (out.filter(m => m.id !== undefined).length < lines.length && Date.now() < deadline) { + const { value, done } = await reader.read(); + if (done) break; + buf += dec.decode(value, { stream: true }); + let nl: number; + while ((nl = buf.indexOf('\n')) >= 0) { out.push(JSON.parse(buf.slice(0, nl)) as J); buf = buf.slice(nl + 1); } + } + p.stdin.end(); + await p.exited; + return out; +} + +function checkRoundTrip(out: J[]): void { + const byId = (id: number) => out.find(m => m.id === id)!; + expect(errOf(byId(1)).code).toBe(ERR.notInitialized); + expect(resOf(byId(2)).protocol).toBe('storebound-desktop/1'); + expect(resOf(byId(3))).toMatchObject({ name: 'Prism Puddle', play: { packageName: 'com.example.prismpuddle' } }); + const shots = resOf(byId(4)); + expect(shots.command).toBe('storebound shots check --json'); + expect((shots.data as J).issues).toBeArray(); + expect(errOf(byId(5)).code).toBe(ERR.confirmInvalid); + expect(out.some(m => m.method === 'progress')).toBe(true); +} + +describe('serve --stdio over a real pipe', () => { + test('from source', async () => { checkRoundTrip(await stdioRoundTrip([process.execPath, join(ROOT, 'cli/index.ts')])); }, 30_000); + + test('compiled sidecar for this machine: version + handshake, no private paths inside', async () => { + const dir = mkdtempSync(join(tmpdir(), 'sb-sidecar-')); + try { + const bin = await buildOne(hostTarget(), dir); + expect(existsSync(bin)).toBe(true); + const v = Bun.spawnSync([bin, 'version'], { cwd: ROOT, stdout: 'pipe' }); + expect(v.exitCode).toBe(0); + expect(v.stdout.toString().trim()).toMatch(/^\d+\.\d+\.\d+/); + expect(leaks(bin)).toEqual([]); + checkRoundTrip(await stdioRoundTrip([bin])); + } finally { rmSync(dir, { recursive: true, force: true }); } + }, 60_000); +}); diff --git a/tools/build-sidecars.ts b/tools/build-sidecars.ts new file mode 100644 index 00000000..5539f195 --- /dev/null +++ b/tools/build-sidecars.ts @@ -0,0 +1,71 @@ +#!/usr/bin/env bun +// Compiles the storebound CLI into single-file executables for the desktop app's sidecar (Tauri `externalBin`). +// bun tools/build-sidecars.ts every target +// bun tools/build-sidecars.ts --host only this machine's target (what `tauri dev` needs) +// bun tools/build-sidecars.ts --target bun-linux-x64[,bun-windows-x64] +// Output: apps/desktop/src-tauri/binaries/storebound-[.exe] (Tauri's sidecar naming; gitignored). +// macOS outputs are re-signed ad hoc: the signature `bun build --compile` leaves is invalid once the payload is +// appended, and the kernel kills such a binary on start (exit 137). Release builds re-sign with Developer ID (D5). +// Every output is scanned for the build machine's home and checkout paths: nothing private may ship. +import { mkdirSync, readFileSync, rmSync, statSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { join } from 'node:path'; + +export const TARGETS: Record = { + 'bun-darwin-arm64': 'aarch64-apple-darwin', + 'bun-darwin-x64': 'x86_64-apple-darwin', + 'bun-linux-x64': 'x86_64-unknown-linux-gnu', + 'bun-linux-arm64': 'aarch64-unknown-linux-gnu', + 'bun-windows-x64': 'x86_64-pc-windows-msvc', +}; + +export const ROOT = join(import.meta.dir, '..'); +export const OUT_DIR = join(ROOT, 'apps/desktop/src-tauri/binaries'); + +export function hostTarget(): string { + const os = process.platform === 'darwin' ? 'darwin' : process.platform === 'win32' ? 'windows' : 'linux'; + const arch = process.arch === 'arm64' ? 'arm64' : 'x64'; + return `bun-${os}-${arch}`; +} + +export const outName = (target: string): string => `storebound-${TARGETS[target]}${target.includes('windows') ? '.exe' : ''}`; + +/** Paths of this machine that must not appear in a shipped binary. */ +export function privateStrings(): string[] { + return [...new Set([homedir(), ROOT].filter(s => s.length > 4))]; +} + +export function leaks(file: string, needles = privateStrings()): string[] { + const buf = readFileSync(file); + return needles.filter(n => buf.includes(Buffer.from(n))); +} + +export async function buildOne(target: string, outDir = OUT_DIR): Promise { + if (!TARGETS[target]) throw new Error(`unknown target ${target} (${Object.keys(TARGETS).join(', ')})`); + mkdirSync(outDir, { recursive: true }); + const out = join(outDir, outName(target)); + rmSync(out, { force: true }); + const t = Date.now(); + const p = Bun.spawnSync(['bun', 'build', '--compile', `--target=${target}`, '--minify-syntax', '--minify-whitespace', 'cli/index.ts', '--outfile', out], + { cwd: ROOT, stdout: 'pipe', stderr: 'pipe' }); + if (p.exitCode !== 0) throw new Error(`${target}: bun build failed\n${p.stderr.toString()}${p.stdout.toString()}`); + if (target.startsWith('bun-darwin') && process.platform === 'darwin') { + const s = Bun.spawnSync(['codesign', '--force', '--sign', '-', out], { stdout: 'pipe', stderr: 'pipe' }); + if (s.exitCode !== 0) throw new Error(`${target}: ad-hoc codesign failed: ${s.stderr.toString()}`); + } + const hits = leaks(out); + if (hits.length) throw new Error(`${target}: ${out} contains private paths (${hits.length}); refusing to keep it`); + console.log(`sidecar ${target} -> ${out} (${(statSync(out).size / 1e6).toFixed(1)} MB, ${((Date.now() - t) / 1000).toFixed(1)}s)`); + return out; +} + +if (import.meta.main) { + const argv = process.argv.slice(2); + const i = argv.indexOf('--target'); + const targets = argv.includes('--host') ? [hostTarget()] : i >= 0 ? (argv[i + 1] ?? '').split(',').filter(Boolean) : Object.keys(TARGETS); + let failed = 0; + for (const t of targets) { + try { await buildOne(t); } catch (e) { failed++; console.error(`sidecar ${t}: ${(e as Error).message}`); } + } + if (failed) process.exit(1); +}