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
This commit is contained in:
CRTkafa 2026-10-10 17:11:56 +00:00
parent c6360812b8
commit 3454a9aadb
28 changed files with 1048 additions and 42 deletions

View file

@ -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<Loaded> {
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;
}

95
cli/lib/confirm-token.ts Normal file
View file

@ -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<string, unknown>;
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<string, number>();
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 };
}
}

View file

@ -21,8 +21,13 @@ export function byAppleLocale(langs: Language[]): Map<string, Language> {
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<boolean> {
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] `);

View file

@ -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<string, JsonSchemaLite>; 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<string, unknown>;
/** 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 }

View file

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

79
cli/lib/runner.ts Normal file
View file

@ -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<string, string>;
/** 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<RunResult>; 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<string, unknown> | undefined): Record<string, string> {
const out: Record<string, string> = {};
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<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;
return { ...base, ...extra, NO_COLOR: '1', ...(machine ? { STOREBOUND_MACHINE: '1', STOREBOUND_SERVE: '1' } : {}) };
}
async function pump(stream: ReadableStream<Uint8Array>, kind: 'stdout' | 'stderr', each: (line: string, kind: 'stdout' | 'stderr') => void): Promise<void> {
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<RunResult> => {
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(); } };
}