D3 writes: owner actions (Play rollout share / halt / resume / complete, iOS phased release, send one approved reply) answer the command's confirmation only with a verified host token; reviews reply edits a draft; native dialog names owner actions; token binding tests for every write the window offers

This commit is contained in:
CRTkafa 2026-10-11 04:19:47 +08:00
parent 7b2cc8da0a
commit f47c00bed0
11 changed files with 359 additions and 24 deletions

View file

@ -138,7 +138,7 @@ pub async fn sidecar_call(window: WebviewWindow, app: AppHandle, state: State<'_
let mut p = policy::sanitize_js_call(&method, kind, &params.unwrap_or(Value::Null)).map_err(Fail::host)?; let mut p = policy::sanitize_js_call(&method, kind, &params.unwrap_or(Value::Null)).map_err(Fail::host)?;
let args = p.get("args").cloned().unwrap_or_else(|| json!({})); let args = p.get("args").cloned().unwrap_or_else(|| json!({}));
let mut cache_project = None; let mut cache_project = None;
if matches!(kind, Some(Kind::Read | Kind::Write)) { if matches!(kind, Some(Kind::Read | Kind::Write | Kind::Owner)) {
let id = project_id.ok_or_else(|| Fail::host(format!("{method} needs a project")))?; let id = project_id.ok_or_else(|| Fail::host(format!("{method} needs a project")))?;
if id.starts_with("store:") { if id.starts_with("store:") {
// a store-only app: store reads only, through the sidecar's generated config // a store-only app: store reads only, through the sidecar's generated config
@ -242,8 +242,26 @@ pub fn dialog_summary(title: &str, description: &str, project: &str, network: bo
s s
} }
/// Summary of an owner action: users see it right away, so the dialog says so in plain words.
pub fn owner_summary(title: &str, description: &str, project: &str) -> String {
format!("{title} · {project}\n\n{description}\n\nThis is your decision: it changes what users get on the store right away. storebound does it only because you press the button below.")
}
/// Dialog title and the confirm button of a write: owner actions name the action on the button.
pub fn dialog_labels(kind: Kind, title: &str) -> (String, String) {
if kind == Kind::Owner {
(format!("Owner action: {title}"), format!("Yes: {title}"))
} else {
(format!("Apply: {title}"), "Apply".to_string())
}
}
/// Native Apply / Cancel dialog; true on Apply. /// Native Apply / Cancel dialog; true on Apply.
async fn confirm_dialog(window: &WebviewWindow, title: String, text: String) -> Res<bool> { async fn confirm_dialog(window: &WebviewWindow, title: String, text: String) -> Res<bool> {
confirm_dialog_with(window, title, text, "Apply".into()).await
}
async fn confirm_dialog_with(window: &WebviewWindow, title: String, text: String, ok: String) -> Res<bool> {
let w = window.clone(); let w = window.clone();
tauri::async_runtime::spawn_blocking(move || { tauri::async_runtime::spawn_blocking(move || {
w.app_handle() w.app_handle()
@ -251,7 +269,7 @@ async fn confirm_dialog(window: &WebviewWindow, title: String, text: String) ->
.message(text) .message(text)
.title(title) .title(title)
.kind(MessageDialogKind::Warning) .kind(MessageDialogKind::Warning)
.buttons(MessageDialogButtons::OkCancelCustom("Apply".into(), "Cancel".into())) .buttons(MessageDialogButtons::OkCancelCustom(ok, "Cancel".into()))
.parent(&w) .parent(&w)
.blocking_show() .blocking_show()
}) })
@ -266,9 +284,11 @@ pub async fn write_with_confirm(window: WebviewWindow, app: AppHandle, state: St
guard(&window)?; guard(&window)?;
let job = job_of(job)?; let job = job_of(job)?;
let r = state.sidecar.get(&app).await?; let r = state.sidecar.get(&app).await?;
if r.kind(&method) != Some(Kind::Write) || method == "project.init" { let kind = r.kind(&method);
if !matches!(kind, Some(Kind::Write | Kind::Owner)) || method == "project.init" {
return Err(Fail::host(format!("{method} is not a write method of an app folder"))); return Err(Fail::host(format!("{method} is not a write method of an app folder")));
} }
let kind = kind.unwrap_or(Kind::Write);
let d = r.descriptor(&method).cloned().ok_or_else(|| Fail::host("unknown method"))?; let d = r.descriptor(&method).cloned().ok_or_else(|| Fail::host("unknown method"))?;
let args = match args.unwrap_or(json!({})) { let args = match args.unwrap_or(json!({})) {
Value::Object(o) => Value::Object(o), Value::Object(o) => Value::Object(o),
@ -283,14 +303,11 @@ pub async fn write_with_confirm(window: WebviewWindow, app: AppHandle, state: St
if dry["ok"] != Value::Bool(true) { if dry["ok"] != Value::Bool(true) {
return Ok(json!({ "confirmed": false, "stage": "dry-run", "dryRun": dry })); return Ok(json!({ "confirmed": false, "stage": "dry-run", "dryRun": dry }));
} }
let text = format!( let summary = if kind == Kind::Owner { owner_summary(&d.title, &d.description, &proj.name) } else { dialog_summary(&d.title, &d.description, &proj.name, d.network, d.destructive) };
"{}\n\nDry run ({}):\n{}", let text = format!("{summary}\n\nDry run ({}):\n{}", dry["command"].as_str().unwrap_or_default(), dialog_excerpt(dry["output"].as_str().unwrap_or_default()));
dialog_summary(&d.title, &d.description, &proj.name, d.network, d.destructive),
dry["command"].as_str().unwrap_or_default(),
dialog_excerpt(dry["output"].as_str().unwrap_or_default())
);
let home = app.path().home_dir().ok().map(|h| h.to_string_lossy().to_string()); let home = app.path().home_dir().ok().map(|h| h.to_string_lossy().to_string());
if !confirm_dialog(&window, format!("Apply: {}", d.title), tilde(&text, home.as_deref())).await? { let (title, ok) = dialog_labels(kind, &d.title);
if !confirm_dialog_with(&window, title, tilde(&text, home.as_deref()), ok).await? {
return Ok(json!({ "confirmed": false, "stage": "dialog", "dryRun": dry })); return Ok(json!({ "confirmed": false, "stage": "dialog", "dryRun": dry }));
} }
let bound = json!({ "project": proj.path, "args": args }); let bound = json!({ "project": proj.path, "args": args });

View file

@ -53,6 +53,9 @@ pub enum Kind {
Session, Session,
/// Account-scoped store reads (apps.list, account.check): the host runs them with one account's key. /// Account-scoped store reads (apps.list, account.check): the host runs them with one account's key.
Account, Account,
/// Owner actions (rollout share, phased release, sending one approved reply): like writes, a dry run from the
/// window; the real run only through `write_with_confirm`, whose dialog says that users see it at once.
Owner,
} }
impl Kind { impl Kind {
@ -64,6 +67,7 @@ impl Kind {
"portfolio" => Kind::Portfolio, "portfolio" => Kind::Portfolio,
"session" => Kind::Session, "session" => Kind::Session,
"account" => Kind::Account, "account" => Kind::Account,
"owner" => Kind::Owner,
_ => return None, _ => return None,
}) })
} }
@ -96,7 +100,7 @@ pub fn sanitize_js_call(method: &str, kind: Option<Kind>, params: &Value) -> Res
} }
} }
let mut out = obj.clone(); let mut out = obj.clone();
if kind == Kind::Write { if matches!(kind, Kind::Write | Kind::Owner) {
out.insert("dryRun".into(), Value::Bool(true)); out.insert("dryRun".into(), Value::Bool(true));
} }
Ok(Value::Object(out)) Ok(Value::Object(out))

View file

@ -0,0 +1,60 @@
//! Desktop D3 writes: owner actions are dry runs from the window like every write; only `write_with_confirm` runs them,
//! after a dialog that names the action on its button and says users see it at once. Tokens are bound to exactly the
//! method and the { project, args } sent (the same vector as the TypeScript side checks).
use serde_json::json;
use storebound_desktop::commands::{dialog_labels, dialog_summary, owner_summary};
use storebound_desktop::confirm::{canonical, mac, mint};
use storebound_desktop::policy::{sanitize_js_call, Kind};
#[test]
fn owner_actions_are_dry_runs_from_the_window() {
let p = sanitize_js_call("owner.play_rollout", Some(Kind::Owner), &json!({ "args": { "action": "complete" } })).unwrap();
assert_eq!(p["dryRun"], json!(true));
for bad in [json!({ "dryRun": false }), json!({ "confirmToken": "sbt1.x" }), json!({ "credentials": {} }), json!({ "project": "/x" })] {
assert!(sanitize_js_call("owner.reply_send", Some(Kind::Owner), &bad).is_err(), "{bad}");
}
assert_eq!(Kind::parse("owner"), Some(Kind::Owner));
let w = sanitize_js_call("reviews.reply", Some(Kind::Write), &json!({ "args": { "file": "play-1.md", "text": "Thanks" } })).unwrap();
assert_eq!(w["dryRun"], json!(true));
}
#[test]
fn owner_dialogs_name_the_action() {
let (title, ok) = dialog_labels(Kind::Owner, "Change the Play staged rollout");
assert_eq!(title, "Owner action: Change the Play staged rollout");
assert_eq!(ok, "Yes: Change the Play staged rollout");
assert_eq!(dialog_labels(Kind::Write, "Push Play listing text"), ("Apply: Push Play listing text".to_string(), "Apply".to_string()));
let s = owner_summary("Send one approved reply", "Sends one approved, unsent reply draft.", "Prism Puddle");
assert!(s.contains("Prism Puddle") && s.contains("right away") && s.contains("your decision"));
assert!(dialog_summary("Push", "d", "A", true, false).contains("not public until you submit"));
}
#[test]
fn tokens_bind_method_project_and_args_of_each_write() {
let secret = [9u8; 32];
let writes = [
("play.listing", json!({})),
("apple.listing", json!({ "version": "2.4.0" })),
("apple.screenshots", json!({})),
("apple.testflight_distribute", json!({ "build": "52", "groups": "Studio team" })),
("reviews.reply", json!({ "file": "play-r-p1.md", "text": "Thanks!" })),
("owner.play_rollout", json!({ "action": "percent", "percent": 50 })),
("owner.ios_phased", json!({ "action": "resume", "version": "2.3.0" })),
("owner.reply_send", json!({ "file": "play-r-p1.md" })),
];
for (method, args) in writes {
let bound = json!({ "project": "/apps/prism", "args": args });
let t = mint(&secret, method, &bound, 1_000, "AAAAAAAAAAAAAAAAAAAAAA").unwrap();
let sig = t.rsplit('.').next().unwrap().to_string();
assert_eq!(sig, mac(&secret, method, &bound, 61_000, "AAAAAAAAAAAAAAAAAAAAAA").unwrap());
// any change of method, project or args changes the signature
assert_ne!(sig, mac(&secret, "play.images", &bound, 61_000, "AAAAAAAAAAAAAAAAAAAAAA").unwrap(), "{method}");
assert_ne!(sig, mac(&secret, method, &json!({ "project": "/apps/other", "args": bound["args"] }), 61_000, "AAAAAAAAAAAAAAAAAAAAAA").unwrap());
let mut more = bound.clone();
more["args"]["x"] = json!(1);
assert_ne!(sig, mac(&secret, method, &more, 61_000, "AAAAAAAAAAAAAAAAAAAAAA").unwrap());
}
// a rollout share is a safe integer (percent), so it can be bound; fractions as numbers cannot
assert!(canonical(&json!({ "percent": 50 })).is_ok());
assert!(canonical(&json!({ "fraction": 0.5 })).is_err());
}

View file

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

View file

@ -29,7 +29,9 @@ export interface MethodDescriptor {
method: string; method: string;
title: string; title: string;
description: string; description: string;
kind: 'read' | 'write' | 'session' | 'system' | 'portfolio' | 'account'; /** owner: a desktop-only write the owner decides (rollout, phased release, sending one reply); always a dry run
* unless the host's confirm token comes with it, and then the command's own confirmation is answered by that token. */
kind: 'read' | 'write' | 'session' | 'system' | 'portfolio' | 'account' | 'owner';
/** Talks to a store API or the internet. */ /** Talks to a store API or the internet. */
network: boolean; network: boolean;
/** Replaces existing data on a store (screenshots, whole forms). */ /** Replaces existing data on a store (screenshots, whole forms). */

View file

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

View file

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

View file

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

View file

@ -58,10 +58,42 @@ export const DESKTOP_ONLY: ToolDef[] = [
description: 'Sets approved: true (or false with undo) in one local reply draft after its checks pass. Nothing is sent: replies go out with `storebound reviews send` in a terminal.', description: 'Sets approved: true (or false with undo) in one local reply draft after its checks pass. Nothing is sent: replies go out with `storebound reviews send` in a terminal.',
props: { file: { type: 'string', pattern: '^(apple|play)-[A-Za-z0-9._-]{1,120}\\.md$', description: 'Draft file name in .storebound/replies' }, undo: { type: 'boolean', default: false } }, props: { file: { type: 'string', pattern: '^(apple|play)-[A-Za-z0-9._-]{1,120}\\.md$', description: 'Draft file name in .storebound/replies' }, undo: { type: 'boolean', default: false } },
required: ['file'], args: i => [String(i.file), ...(i.undo === true ? ['--undo'] : [])] }, required: ['file'], args: i => [String(i.file), ...(i.undo === true ? ['--undo'] : [])] },
{ name: 'reviews_reply', title: 'Write a reply draft', command: ['reviews', 'reply'], write: true, network: false, idempotent: true,
description: 'Writes the reply text of one local reply draft (.storebound/replies); an edited reply loses its approval. Nothing is sent.',
props: { file: { type: 'string', pattern: '^(apple|play)-[A-Za-z0-9._-]{1,120}\\.md$', description: 'Draft file name in .storebound/replies' },
text: { type: 'string', pattern: '^[\\s\\S]{1,6000}$', description: 'The reply (plain text, the reviewer\'s language)' } },
required: ['file', 'text'], args: i => [String(i.file), '--text', String(i.text)] },
{ name: 'project_init', title: 'Start an app folder', command: ['init'], write: true, network: false, idempotent: true, { name: 'project_init', title: 'Start an app folder', command: ['init'], write: true, network: false, idempotent: true,
description: 'Copies the storebound templates (config, listing, screenshot copy, declarations, privacy policy) for a profile into an empty app folder; existing files are kept.', description: 'Copies the storebound templates (config, listing, screenshot copy, declarations, privacy policy) for a profile into an empty app folder; existing files are kept.',
props: { profile: { type: 'string', enum: ['app', 'game', 'subscription-app'], default: 'app' } }, args: i => ['--profile', String(i.profile ?? 'app')] }, props: { profile: { type: 'string', enum: ['app', 'game', 'subscription-app'], default: 'app' } }, args: i => ['--profile', String(i.profile ?? 'app')] },
]; ];
/**
* Owner actions (desktop only, kind "owner"): changes the owner decides because users see them at once. Each is a dry
* run unless the host's confirm token comes with it, minted after the owner pressed the button of a native dialog that
* showed that dry run; only then the command's own confirmation is answered (STOREBOUND_OWNER_CONFIRMED for that one
* child). Never: submitting for review, releasing an approved version (--manual-release), cancelling a submission,
* external TestFlight or Beta App Review, removing testers. Those stay in the consoles or the terminal.
*/
export const OWNER_TOOLS: ToolDef[] = [
{ name: 'owner_play_rollout', title: 'Change the Play staged rollout', command: ['play', 'rollout'], write: true, network: true,
description: 'Google Play staged rollout of a track: set the user share (percent), halt it (not a rollback), resume it, or complete it (100 %).',
props: { action: { type: 'string', enum: ['percent', 'halt', 'resume', 'complete'] }, percent: { type: 'integer', minimum: 1, maximum: 99, description: 'User share in percent (action percent, or resume at a new share)' },
track: { type: 'string', enum: ['production', 'beta', 'alpha', 'internal'], default: 'production' } },
required: ['action'],
args: i => [...(i.action === 'halt' ? ['--halt'] : i.action === 'resume' ? ['--resume'] : i.action === 'complete' ? ['--complete'] : []),
...(i.percent !== undefined && (i.action === 'percent' || i.action === 'resume') ? ['--fraction', String(Number(i.percent) / 100)] : []), '--track', String(i.track ?? 'production')] },
{ name: 'owner_ios_phased', title: 'Change the App Store phased release', command: ['apple', 'release'], write: true, network: true,
description: 'The 7-day phased release of an App Store version: turn it on, pause it (not a rollback), resume it, or release to everyone now (complete).',
props: { action: { type: 'string', enum: ['on', 'pause', 'resume', 'complete'] }, version: { type: 'string', pattern: '^\\d+(\\.\\d+){0,2}$' } },
required: ['action'], args: i => ['--phased', String(i.action), ...(i.version ? ['--version', String(i.version)] : [])] },
{ name: 'owner_reply_send', title: 'Send one approved reply', command: ['reviews', 'send'], write: true, network: true,
description: 'Sends one approved, unsent reply draft (.storebound/replies) to its store: public, the reviewer is notified. The draft checks (length, no incentives) apply.',
props: { file: { type: 'string', pattern: '^(apple|play)-[A-Za-z0-9._-]{1,120}\\.md$', description: 'Draft file name in .storebound/replies' } },
required: ['file'], args: i => ['--file', String(i.file)] },
];
/** Flags no owner action may ever produce. */
export const OWNER_FORBIDDEN_ARGS = ['--yes', '--manual-release', '--cancel-submission', '--submit-review', '--remove', '--invite', '--production', 'submit', 'publish', 'distribute', 'testers'];
/** Desktop-only methods whose `project` is a folder without a config yet. */ /** Desktop-only methods whose `project` is a folder without a config yet. */
const NEW_PROJECT = new Set(['project_init']); const NEW_PROJECT = new Set(['project_init']);
@ -69,7 +101,8 @@ const NEW_PROJECT = new Set(['project_init']);
export const methodName = (tool: string): string => tool.replace('_', '.'); export const methodName = (tool: string): string => tool.replace('_', '.');
export const DESKTOP_TOOLS: ToolDef[] = [...TOOLS.filter(t => !DESKTOP_EXCLUDED.has(t.name)), ...DESKTOP_ONLY]; export const DESKTOP_TOOLS: ToolDef[] = [...TOOLS.filter(t => !DESKTOP_EXCLUDED.has(t.name)), ...DESKTOP_ONLY];
const byMethod = new Map(DESKTOP_TOOLS.map(t => [methodName(t.name), t] as const)); const OWNER = new Set(OWNER_TOOLS.map(t => t.name));
const byMethod = new Map([...DESKTOP_TOOLS, ...OWNER_TOOLS].map(t => [methodName(t.name), t] as const));
function argsSchema(t: ToolDef): MethodDescriptor['args'] { function argsSchema(t: ToolDef): MethodDescriptor['args'] {
const s = inputSchema(t) as MethodDescriptor['args']; const s = inputSchema(t) as MethodDescriptor['args'];
@ -103,8 +136,8 @@ const PKG_RE = /^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)+$/;
const BUNDLE_RE = /^[A-Za-z0-9][A-Za-z0-9.-]{0,154}$/; const BUNDLE_RE = /^[A-Za-z0-9][A-Za-z0-9.-]{0,154}$/;
export function describeMethods(): MethodDescriptor[] { export function describeMethods(): MethodDescriptor[] {
return [...SYSTEM, ...DESKTOP_TOOLS.map(t => ({ return [...SYSTEM, ...[...DESKTOP_TOOLS, ...OWNER_TOOLS].map(t => ({
method: methodName(t.name), title: t.title, description: t.description, kind: t.write ? 'write' as const : 'read' as const, method: methodName(t.name), title: t.title, description: t.description, kind: OWNER.has(t.name) ? 'owner' as const : t.write ? 'write' as const : 'read' as const,
network: t.network, destructive: !!t.destructive, json: !t.write && JSON_TOOLS.has(t.name), args: argsSchema(t), network: t.network, destructive: !!t.destructive, json: !t.write && JSON_TOOLS.has(t.name), args: argsSchema(t),
}))]; }))];
} }
@ -295,6 +328,11 @@ export class Session {
const built = toArgv(t, { ...args, ...(t.write ? { dry_run: dryRun } : {}) }); const built = toArgv(t, { ...args, ...(t.write ? { dry_run: dryRun } : {}) });
const json = !t.write && JSON_TOOLS.has(t.name); const json = !t.write && JSON_TOOLS.has(t.name);
const argv = json ? [...built.argv, '--json'] : built.argv; const argv = json ? [...built.argv, '--json'] : built.argv;
if (OWNER.has(t.name)) {
if (argv.some(a => OWNER_FORBIDDEN_ARGS.includes(a))) throw new RpcError(ERR.invalidParams, `${method}: not an owner action from here`);
// the verified token is the owner's answer to the command's own question; nothing else can set it
if (!dryRun) env.STOREBOUND_OWNER_CONFIRMED = '1';
}
const r = this.track(id, this.run(argv, { cwd: project, env, machine: true, onLine: (line, stream) => this.progress(id, { line, stream }) })); const 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; const res = await r.result;
if (res.cancelled || this.cancelled.has(id)) throw new RpcError(ERR.cancelled, 'Request cancelled'); if (res.cancelled || this.cancelled.has(id)) throw new RpcError(ERR.cancelled, 'Request cancelled');

169
tests/desktop-d3.test.ts Normal file
View file

@ -0,0 +1,169 @@
// Desktop D3 write actions: every write the window offers is a dry run unless the host's confirm token for exactly
// that method, project and arguments comes with it (single use, short-lived); owner actions (rollout share, phased
// release, sending one approved reply) additionally answer the command's own confirmation, and only with such a token.
import { afterEach, describe, expect, test } from 'bun:test';
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { mint } from '../cli/lib/confirm-token';
import { confirm } from '../cli/lib/ctx';
import { ERR } from '../cli/lib/desktop-protocol';
import { parseDraft } from '../cli/lib/reviews';
import { setReplyText } from '../cli/lib/project-files';
import { childEnv, type RunOptions, type Running } from '../cli/lib/runner';
import { TOOLS } from '../cli/mcp-tools';
import { describeMethods, methodName, OWNER_FORBIDDEN_ARGS, OWNER_TOOLS, Session } from '../cli/serve';
import { toArgv } from '../cli/mcp-tools';
type J = Record<string, unknown>;
const DEMO = join(import.meta.dir, '..', 'examples', 'demo-game');
const SECRET_HEX = Array.from({ length: 32 }, (_, i) => (i + 7).toString(16).padStart(2, '0')).join('');
const SECRET = Buffer.from(SECRET_HEX, 'hex');
async function session(now = () => Date.now()) {
const calls: { argv: string[]; o: RunOptions }[] = [];
const run = (argv: string[], o: RunOptions): Running => { calls.push({ argv, o }); return { result: Promise.resolve({ code: 0, out: 'done', cancelled: false }), cancel: () => {} }; };
const s = new Session(() => {}, run, now);
let id = 0;
const call = async (method: string, params: unknown = {}) => (await s.handle({ jsonrpc: '2.0', id: ++id, method, params }))! as J;
await call('session.hello', { secret: SECRET_HEX });
return { calls, call };
}
const err = (r: J) => r.error as { code: number; data?: J };
/** The writes the D3 screens offer, with arguments as the window sends them. */
const D3_WRITES: [string, J][] = [
['play.listing', {}], ['apple.listing', { version: '2.4.0' }], ['play.images', { only: 'en-US' }], ['apple.screenshots', {}], ['apple.previews', {}],
['play.products', {}], ['apple.iap', {}], ['play.subscriptions', {}], ['apple.subscriptions', {}],
['apple.testflight_distribute', { build: '52', groups: 'Studio team' }], ['apple.testflight_what_to_test', { build: '52', text: 'New combo meter' }],
['reviews.reply', { file: 'play-r-p1.md', text: 'Thanks! The fix is in 2.4.0.' }], ['reviews.approve', { file: 'play-r-p1.md' }],
['shots.render', {}], ['shots.video', {}], ['shots.gallery', {}], ['icons', {}],
['owner.play_rollout', { action: 'percent', percent: 50 }], ['owner.play_rollout', { action: 'halt' }], ['owner.ios_phased', { action: 'pause', version: '2.3.0' }],
['owner.ios_phased', { action: 'resume' }], ['owner.reply_send', { file: 'play-r-p1.md' }],
];
describe('D3 writes: token binding for every method the window offers', () => {
for (const [method, args] of D3_WRITES) {
test(`${method} ${JSON.stringify(args)}`, async () => {
let now = 1_000_000;
const s = await session(() => now);
const p = { project: DEMO, args };
// dry run by default, and without a token
const dry = await s.call(method, p);
expect(err(dry)).toBeUndefined();
expect(s.calls.at(-1)!.argv).toContain('--dry');
expect(s.calls.at(-1)!.o.env?.STOREBOUND_OWNER_CONFIRMED).toBeUndefined();
expect(err(await s.call(method, { ...p, dryRun: false })).code).toBe(ERR.confirmRequired);
// a token for other arguments, another method or another project is refused
const other = method === 'play.listing' ? 'play.images' : 'play.listing';
expect(err(await s.call(method, { ...p, dryRun: false, confirmToken: mint(SECRET, other, p, { now }) })).code).toBe(ERR.confirmInvalid);
expect(err(await s.call(method, { ...p, dryRun: false, confirmToken: mint(SECRET, method, { project: '/elsewhere', args }, { now }) })).code).toBe(ERR.confirmInvalid);
expect(err(await s.call(method, { ...p, dryRun: false, confirmToken: mint(SECRET, method, { project: DEMO, args: { ...args, x: 1 } }, { now }) })).code).toBe(ERR.confirmInvalid);
expect(err(await s.call(method, { ...p, dryRun: false, confirmToken: mint(Buffer.alloc(32, 1), method, p, { now }) })).code).toBe(ERR.confirmInvalid);
// the right token runs it for real, once
const n = s.calls.length;
const token = mint(SECRET, method, p, { now });
const real = await s.call(method, { ...p, dryRun: false, confirmToken: token, credentials: { PLAY_SERVICE_ACCOUNT: '{}' } });
expect(err(real)).toBeUndefined();
expect((real.result as J).dryRun).toBe(false);
const c = s.calls.at(-1)!;
expect(s.calls.length).toBe(n + 1);
expect(c.argv).not.toContain('--dry');
expect(c.o.env?.PLAY_SERVICE_ACCOUNT).toBe('{}');
expect(c.o.env?.STOREBOUND_OWNER_CONFIRMED).toBe(method.startsWith('owner.') ? '1' : undefined);
expect(err(await s.call(method, { ...p, dryRun: false, confirmToken: token })).data).toEqual({ reason: 'replayed' });
// and expires
const late = mint(SECRET, method, p, { now, ttlMs: 1000 });
now += 1000;
expect(err(await s.call(method, { ...p, dryRun: false, confirmToken: late })).data).toEqual({ reason: 'expired' });
});
}
});
describe('owner actions', () => {
test('exactly these, desktop only, kind owner, never a submit / release request / cancel / external TestFlight flag', () => {
expect(OWNER_TOOLS.map(t => methodName(t.name)).sort()).toEqual(['owner.ios_phased', 'owner.play_rollout', 'owner.reply_send']);
for (const t of OWNER_TOOLS) expect(TOOLS.some(x => x.name === t.name)).toBe(false);
const ds = describeMethods().filter(m => m.method.startsWith('owner.'));
for (const d of ds) expect(d.kind).toBe('owner');
const samples: J[] = [
{ action: 'percent', percent: 5 }, { action: 'halt' }, { action: 'resume', percent: 10 }, { action: 'complete', track: 'beta' },
{ action: 'on' }, { action: 'pause', version: '1.2.3' }, { action: 'resume' }, { action: 'complete' }, { file: 'apple-123.md' },
];
for (const t of OWNER_TOOLS) for (const s of samples) {
let argv: string[];
try { argv = toArgv(t, s).argv; } catch { continue; }
for (const a of argv) expect(OWNER_FORBIDDEN_ARGS).not.toContain(a);
}
});
test('argv: rollout share in percent -> fraction, halt / resume / complete, track; phased actions; one reply', () => {
const t = (name: string) => OWNER_TOOLS.find(x => x.name === name)!;
expect(toArgv(t('owner_play_rollout'), { action: 'percent', percent: 20, dry_run: false }).argv).toEqual(['play', 'rollout', '--fraction', '0.2', '--track', 'production']);
expect(toArgv(t('owner_play_rollout'), { action: 'halt' }).argv).toEqual(['play', 'rollout', '--halt', '--track', 'production', '--dry']);
expect(toArgv(t('owner_play_rollout'), { action: 'resume', percent: 50, dry_run: false }).argv).toEqual(['play', 'rollout', '--resume', '--fraction', '0.5', '--track', 'production']);
expect(toArgv(t('owner_play_rollout'), { action: 'complete', percent: 50, track: 'beta', dry_run: false }).argv).toEqual(['play', 'rollout', '--complete', '--track', 'beta']);
expect(toArgv(t('owner_ios_phased'), { action: 'resume', version: '2.3.0', dry_run: false }).argv).toEqual(['apple', 'release', '--phased', 'resume', '--version', '2.3.0']);
expect(toArgv(t('owner_reply_send'), { file: 'play-r1.md', dry_run: false }).argv).toEqual(['reviews', 'send', '--file', 'play-r1.md']);
});
test('bad arguments never reach a command', async () => {
const s = await session();
for (const [m, args] of [['owner.play_rollout', { action: 'manual' }], ['owner.play_rollout', { action: 'percent', percent: 100 }], ['owner.play_rollout', { action: 'percent', percent: 0.5 }],
['owner.ios_phased', { action: 'release' }], ['owner.ios_phased', { action: 'on', version: '--manual-release' }], ['owner.reply_send', { file: '../../etc/passwd' }],
['owner.reply_send', {}], ['reviews.reply', { file: 'play-1.md', text: '--yes' }], ['reviews.reply', { file: 'play-1.md', text: 'x'.repeat(6001) }]] as [string, J][])
expect(err(await s.call(m, { project: DEMO, args })).code).toBe(ERR.invalidParams);
expect(s.calls.length).toBe(0);
});
});
describe('the owner flag', () => {
const saved = { ...process.env };
afterEach(() => { for (const k of ['STOREBOUND_SERVE', 'STOREBOUND_OWNER_CONFIRMED']) { if (saved[k] === undefined) delete process.env[k]; else process.env[k] = saved[k]; } });
const ctx = { loaded: {} as never, args: { has: (n: string) => n === 'yes', get: () => undefined, str: (_: string, d: string) => d, num: (_: string, d: number) => d, list: () => [], _: [] } };
test('under serve: no by default, even with --yes; yes only with the owner flag', async () => {
process.env.STOREBOUND_SERVE = '1';
delete process.env.STOREBOUND_OWNER_CONFIRMED;
expect(await confirm(ctx, 'Resume?')).toBe(false);
process.env.STOREBOUND_OWNER_CONFIRMED = '1';
expect(await confirm(ctx, 'Resume?')).toBe(true);
});
test('a child never inherits it; it comes only per call', () => {
process.env.STOREBOUND_OWNER_CONFIRMED = '1';
expect(childEnv({}, true).STOREBOUND_OWNER_CONFIRMED).toBeUndefined();
expect(childEnv({ STOREBOUND_OWNER_CONFIRMED: '1' }, true).STOREBOUND_OWNER_CONFIRMED).toBe('1');
});
});
describe('reply drafts: write the reply', () => {
const draft = ['---', 'store: play', 'review_id: r-p1', 'rating: 2', 'approved: true', 'sent: null', '---', '# ★★☆☆☆ Crashes', '', '> Game closes at a 20x combo.', '', '## Reply', '',
'<!-- Write the reply below. -->', '', 'Old text', ''].join('\n');
test('replaces the reply, keeps the review, resets the approval', () => {
const next = setReplyText(draft, ' Sorry! Fixed in 2.4.0.\r\nThanks for the level number. ');
const d = parseDraft('/x/play-r-p1.md', next);
expect(d.reply).toBe('Sorry! Fixed in 2.4.0.\nThanks for the level number.');
expect(d.approved).toBe(false);
expect(next).toContain('> Game closes at a 20x combo.');
expect(next).not.toContain('Old text');
expect(parseDraft('/x', setReplyText(next, 'Again <!-- hidden -->')).reply).toBe('Again');
});
test('sent drafts and other files are not edited', () => {
expect(() => setReplyText(draft.replace('sent: null', 'sent: 2026-10-01T00:00:00Z'), 'x')).toThrow();
expect(() => setReplyText('# not a draft', 'x')).toThrow();
});
test('CLI: reviews reply writes one draft, dry run first', async () => {
const dir = mkdtempSync(join(tmpdir(), 'sb-reply-'));
const cfg = readFileSync(join(DEMO, 'storebound.config.ts'), 'utf8');
writeFileSync(join(dir, 'storebound.config.ts'), cfg);
const replies = join(dir, '.storebound', 'replies');
await Bun.$`mkdir -p ${replies}`.quiet();
writeFileSync(join(replies, 'play-r-p1.md'), draft);
const cli = join(import.meta.dir, '..', 'cli', 'index.ts');
const dry = await Bun.$`bun ${cli} reviews reply play-r-p1.md --text ${'New reply'} --dry`.cwd(dir).quiet().nothrow();
expect(dry.exitCode).toBe(0);
expect(readFileSync(join(replies, 'play-r-p1.md'), 'utf8')).toBe(draft);
const real = await Bun.$`bun ${cli} reviews reply play-r-p1.md --text ${'New reply'}`.cwd(dir).quiet().nothrow();
expect(real.exitCode).toBe(0);
expect(parseDraft('x', readFileSync(join(replies, 'play-r-p1.md'), 'utf8'))).toMatchObject({ reply: 'New reply', approved: false });
const outside = await Bun.$`bun ${cli} reviews reply ../../x.md --text y`.cwd(dir).quiet().nothrow();
expect(outside.exitCode).not.toBe(0);
});
});

View file

@ -6,7 +6,7 @@ import { canonical, mac, MAX_TTL_MS, mint, parseSecret, TokenGuard } from '../cl
import { ERR } from '../cli/lib/desktop-protocol'; import { ERR } from '../cli/lib/desktop-protocol';
import { childEnv, pickCallEnv, type RunOptions, type Running } from '../cli/lib/runner'; import { childEnv, pickCallEnv, type RunOptions, type Running } from '../cli/lib/runner';
import { FORBIDDEN_ARGS, TOOLS } from '../cli/mcp-tools'; import { FORBIDDEN_ARGS, TOOLS } from '../cli/mcp-tools';
import { describeMethods, DESKTOP_ONLY, DESKTOP_TOOLS, FORBIDDEN_METHOD_WORDS, JSON_TOOLS, methodName, Session } from '../cli/serve'; import { describeMethods, DESKTOP_ONLY, DESKTOP_TOOLS, FORBIDDEN_METHOD_WORDS, JSON_TOOLS, methodName, OWNER_TOOLS, Session } from '../cli/serve';
import { buildOne, hostTarget, leaks } from '../tools/build-sidecars'; import { buildOne, hostTarget, leaks } from '../tools/build-sidecars';
type J = Record<string, unknown>; type J = Record<string, unknown>;
@ -86,7 +86,13 @@ describe('confirm tokens', () => {
describe('serve --stdio: methods', () => { describe('serve --stdio: methods', () => {
test('nothing submits, releases or publishes', () => { test('nothing submits, releases or publishes', () => {
const names = describeMethods().map(m => m.method); const names = describeMethods().map(m => m.method);
for (const n of names) expect(n).not.toMatch(FORBIDDEN_METHOD_WORDS); // the owner actions (rollout share, phased release, sending one approved reply: tests/desktop-d3.test.ts) are the
// only methods with those words, all under "owner.", and none submits, publishes, cancels, deletes or invites
const owner = describeMethods().filter(m => m.kind === 'owner').map(m => m.method);
expect(owner.sort()).toEqual(OWNER_TOOLS.map(t => methodName(t.name)).sort());
for (const n of owner) expect(n.startsWith('owner.')).toBe(true);
for (const n of names.filter(x => !owner.includes(x))) expect(n).not.toMatch(FORBIDDEN_METHOD_WORDS);
for (const n of names) expect(n).not.toMatch(/submit|publish|cancel|delete|remove|invite|manual/i);
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']) 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); expect(names).not.toContain(n);
// every desktop tool still goes through the MCP rules: no forbidden flag can come out of any of them // every desktop tool still goes through the MCP rules: no forbidden flag can come out of any of them