From 1d2978d0bb68c3657c0605d9e023caf72aa96bf1 Mon Sep 17 00:00:00 2001 From: CRT Date: Sun, 11 Oct 2026 18:21:35 +0000 Subject: [PATCH] console fill: opens the form itself and reuses the owner's Chrome sign-in MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Navigation after sign-in (navPlan + navigate): App Store Connect Apps > + > New App (EN/TR), App Privacy by /apps//distribution/privacy or the app list, Play app list by package name > Policy and programs > App content > Start / Manage. Every navigation click goes through navClick: the click gate stays absolute, only a link named exactly Start / Manage / Başla / Yönet passes. Each step is logged; a step not found in time or two matching apps -> the printed steps and wait (no crash). The TR gate now refuses "uygula" (apply) but not "uygulama" (app). Browser (cli/console/session.ts): attach to a Chrome with remote debugging (--cdp or DevToolsActivePort), else on macOS a temporary profile with only Local State and the profile's Cookies filtered to the console hosts, opened in real Chrome and deleted at the end, else storebound's own profile (--fresh-profile). Cookies are never printed. Desktop: fresh_profile option, the dialog says it uses the Chrome sign-in. Tests: navigation fixtures (ASC EN/TR, Play list, App content, missing step, duplicates, deny-listed decoys), session file selection, host filter, cleanup, and a real-Chrome copy-mode test on a throwaway profile and a local site. --- .cursor/rules/storebound.mdc | 2 +- .github/copilot-instructions.md | 2 +- AGENTS.md | 2 +- GEMINI.md | 2 +- README.md | 13 +- apps/desktop/src-tauri/src/commands.rs | 2 +- apps/desktop/src-tauri/tests/d3_writes.rs | 1 + apps/desktop/src/i18n/en.ts | 2 +- apps/desktop/src/i18n/tr.ts | 2 +- cli/console/fill.ts | 226 ++++++++++++++++-- cli/console/session.ts | 227 +++++++++++++++++++ cli/lib/console-answers.ts | 10 +- cli/lib/console-forms.ts | 93 +++++++- cli/serve.ts | 5 +- cli/shots/browser.ts | 4 + docs/desktop.md | 7 +- skills/console-autofill/SKILL.md | 42 +++- tests/console-fill.test.ts | 150 +++++++++++- tests/console-session.test.ts | 164 ++++++++++++++ tests/fixtures/console/_common.js | 16 +- tests/fixtures/console/asc-app.html | 9 + tests/fixtures/console/asc-apps-dup.html | 8 + tests/fixtures/console/asc-apps-noplus.html | 9 + tests/fixtures/console/asc-apps-tr.html | 22 ++ tests/fixtures/console/asc-apps.html | 33 +++ tests/fixtures/console/play-app-content.html | 12 + tests/fixtures/console/play-apps.html | 16 ++ tests/fixtures/console/play-dashboard.html | 16 ++ 28 files changed, 1034 insertions(+), 63 deletions(-) create mode 100644 cli/console/session.ts create mode 100644 tests/console-session.test.ts create mode 100644 tests/fixtures/console/asc-app.html create mode 100644 tests/fixtures/console/asc-apps-dup.html create mode 100644 tests/fixtures/console/asc-apps-noplus.html create mode 100644 tests/fixtures/console/asc-apps-tr.html create mode 100644 tests/fixtures/console/asc-apps.html create mode 100644 tests/fixtures/console/play-app-content.html create mode 100644 tests/fixtures/console/play-apps.html create mode 100644 tests/fixtures/console/play-dashboard.html diff --git a/.cursor/rules/storebound.mdc b/.cursor/rules/storebound.mdc index 73fdbf99..d48e5e3e 100644 --- a/.cursor/rules/storebound.mdc +++ b/.cursor/rules/storebound.mdc @@ -51,7 +51,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t - `skills/appstore-first-release/SKILL.md`: Step-by-step first (and later) App Store release of a mobile app or game - `skills/aso-basics/SKILL.md`: App store optimization basics for a mobile app's or game's text - `skills/build-and-sign/SKILL.md`: Sign, build and upload a mobile app or game from the terminal -- `skills/console-autofill/SKILL.md`: AI-assisted autofill of App Store Connect and Google Play Console forms that have no API (the New App dialog, App Privacy, the Play IARC content rating questionnaire, Target audience and content plus the Ads declaration; the App Store age rating is shown as guidance because the API sets it) in a visible Chromium the owner signs in to. Answers come only from storebound.config.ts; anything the config does not prove stays empty and highlighted. storebound never signs in, never saves, submits or publishes +- `skills/console-autofill/SKILL.md`: AI-assisted autofill of App Store Connect and Google Play Console forms that have no API (the New App dialog, App Privacy, the Play IARC content rating questionnaire, Target audience and content plus the Ads declaration; the App Store age rating is shown as guidance because the API sets it) in a visible browser that reuses the owner's Chrome sign-in (or one they sign in to); storebound opens the form itself. Answers come only from storebound.config.ts; anything the config does not prove stays empty and highlighted. storebound never signs in, never saves, submits or publishes - `skills/export-compliance/SKILL.md`: Answer App Store export compliance (encryption) for a mobile app or game correctly - `skills/listing-localization/SKILL.md`: Translate the store listing of a mobile app or game into more languages - `skills/migrate-from-fastlane/SKILL.md`: Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane` diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 6140ffc5..f2b87ad3 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -53,7 +53,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t | `appstore-first-release` | Step-by-step first (and later) App Store release of a mobile app or game | | `aso-basics` | App store optimization basics for a mobile app's or game's text | | `build-and-sign` | Sign, build and upload a mobile app or game from the terminal | -| `console-autofill` | AI-assisted autofill of App Store Connect and Google Play Console forms that have no API (the New App dialog, App Privacy, the Play IARC content rating questionnaire, Target audience and content plus the Ads declaration; the App Store age rating is shown as guidance because the API sets it) in a visible Chromium the owner signs in to. Answers come only from storebound.config.ts; anything the config does not prove stays empty and highlighted. storebound never signs in, never saves, submits or publishes | +| `console-autofill` | AI-assisted autofill of App Store Connect and Google Play Console forms that have no API (the New App dialog, App Privacy, the Play IARC content rating questionnaire, Target audience and content plus the Ads declaration; the App Store age rating is shown as guidance because the API sets it) in a visible browser that reuses the owner's Chrome sign-in (or one they sign in to); storebound opens the form itself. Answers come only from storebound.config.ts; anything the config does not prove stays empty and highlighted. storebound never signs in, never saves, submits or publishes | | `export-compliance` | Answer App Store export compliance (encryption) for a mobile app or game correctly | | `listing-localization` | Translate the store listing of a mobile app or game into more languages | | `migrate-from-fastlane` | Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane` | diff --git a/AGENTS.md b/AGENTS.md index ee4b215b..fc28f017 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -52,7 +52,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t - `skills/appstore-first-release/SKILL.md`: Step-by-step first (and later) App Store release of a mobile app or game - `skills/aso-basics/SKILL.md`: App store optimization basics for a mobile app's or game's text - `skills/build-and-sign/SKILL.md`: Sign, build and upload a mobile app or game from the terminal -- `skills/console-autofill/SKILL.md`: AI-assisted autofill of App Store Connect and Google Play Console forms that have no API (the New App dialog, App Privacy, the Play IARC content rating questionnaire, Target audience and content plus the Ads declaration; the App Store age rating is shown as guidance because the API sets it) in a visible Chromium the owner signs in to. Answers come only from storebound.config.ts; anything the config does not prove stays empty and highlighted. storebound never signs in, never saves, submits or publishes +- `skills/console-autofill/SKILL.md`: AI-assisted autofill of App Store Connect and Google Play Console forms that have no API (the New App dialog, App Privacy, the Play IARC content rating questionnaire, Target audience and content plus the Ads declaration; the App Store age rating is shown as guidance because the API sets it) in a visible browser that reuses the owner's Chrome sign-in (or one they sign in to); storebound opens the form itself. Answers come only from storebound.config.ts; anything the config does not prove stays empty and highlighted. storebound never signs in, never saves, submits or publishes - `skills/export-compliance/SKILL.md`: Answer App Store export compliance (encryption) for a mobile app or game correctly - `skills/listing-localization/SKILL.md`: Translate the store listing of a mobile app or game into more languages - `skills/migrate-from-fastlane/SKILL.md`: Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane` diff --git a/GEMINI.md b/GEMINI.md index 5420d619..32af1c94 100644 --- a/GEMINI.md +++ b/GEMINI.md @@ -52,7 +52,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t | `appstore-first-release` | Step-by-step first (and later) App Store release of a mobile app or game | | `aso-basics` | App store optimization basics for a mobile app's or game's text | | `build-and-sign` | Sign, build and upload a mobile app or game from the terminal | -| `console-autofill` | AI-assisted autofill of App Store Connect and Google Play Console forms that have no API (the New App dialog, App Privacy, the Play IARC content rating questionnaire, Target audience and content plus the Ads declaration; the App Store age rating is shown as guidance because the API sets it) in a visible Chromium the owner signs in to. Answers come only from storebound.config.ts; anything the config does not prove stays empty and highlighted. storebound never signs in, never saves, submits or publishes | +| `console-autofill` | AI-assisted autofill of App Store Connect and Google Play Console forms that have no API (the New App dialog, App Privacy, the Play IARC content rating questionnaire, Target audience and content plus the Ads declaration; the App Store age rating is shown as guidance because the API sets it) in a visible browser that reuses the owner's Chrome sign-in (or one they sign in to); storebound opens the form itself. Answers come only from storebound.config.ts; anything the config does not prove stays empty and highlighted. storebound never signs in, never saves, submits or publishes | | `export-compliance` | Answer App Store export compliance (encryption) for a mobile app or game correctly | | `listing-localization` | Translate the store listing of a mobile app or game into more languages | | `migrate-from-fastlane` | Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane` | diff --git a/README.md b/README.md index 49f21744..3b6abfc8 100644 --- a/README.md +++ b/README.md @@ -483,10 +483,15 @@ a terminal first and are never offered over MCP. default offering into a RevenueCat project (REST API v2, secret key from env / `.storebound/`). sync only creates and attaches, never deletes. Runtime entitlements, receipts and paywalls stay RevenueCat's job. Skill: `revenuecat-sync`. - **Console autofill for forms without an API:** `storebound console fill
` (`apple-app-record`, - `apple-age-rating`, `apple-app-privacy`, `play-content-rating`, `play-target-audience`) opens a visible Chromium - with a profile you sign in to yourself, fills what the config proves, highlights the rest and stops before any - Save / Submit / Publish: you click. When the page has changed it falls back to step-by-step guidance with copyable - answers. **Console pages change; this is AI-assisted: review every field and save it yourself.** Desktop: "Fill in + `apple-age-rating`, `apple-app-privacy`, `play-content-rating`, `play-target-audience`) opens a visible browser, + goes to the form by itself (Apps > + > New App, the app's App Privacy, Play app list > App content > Start / Manage; + navigation clicks only, never Save / Submit / Publish / Create / Next), fills what the config proves, highlights the + rest and stops before the final button: you click. **Sign-in:** it attaches to a Chrome running with remote + debugging, else (macOS) reuses your Chrome sign-in: it copies ONLY `Local State` and your profile's `Cookies` + (+ journal) into a temporary profile, keeps only the apple.com / google.com cookies the consoles use, opens real + Chrome on it and deletes it when the run ends (never passwords, history or extensions; cookies are never printed + or sent anywhere; macOS may ask once for Keychain access). `--fresh-profile` uses storebound's own profile instead. + When a page has changed it falls back to step-by-step guidance with copyable answers. **Console pages change; this is AI-assisted: review every field and save it yourself.** Desktop: "Fill in console" on the App info tab. Never over MCP. Skill: `console-autofill`. MCP gets only the safe parts: `prices_ppp`, `web_init`, `apple_adhoc_options` (local files, dry run by default) and diff --git a/apps/desktop/src-tauri/src/commands.rs b/apps/desktop/src-tauri/src/commands.rs index c40dc47c..fec4e4aa 100644 --- a/apps/desktop/src-tauri/src/commands.rs +++ b/apps/desktop/src-tauri/src/commands.rs @@ -261,7 +261,7 @@ pub fn dialog_labels(kind: Kind, title: &str) -> (String, String) { /// the uncertain ones marked for the owner, and the note that the owner reviews and saves in the browser. pub fn console_fill_dialog(project: &str, data: &Value) -> (String, String, String) { let title = data["title"].as_str().unwrap_or("Console form"); - let mut s = format!("{title} · {project}\n\nA browser window opens on the console page. Sign in there yourself; storebound fills the fields below and marks the ones you answer.\n\n{}\n", policy::CONSOLE_FILL_NOTE); + let mut s = format!("{title} · {project}\n\nA browser window opens on the console page. It uses your Chrome sign-in: storebound copies only your Chrome cookies for App Store Connect and Play Console into a temporary profile and deletes it when the window closes (passwords, history and extensions are never copied; macOS may ask once for Keychain access). If you are not signed in, sign in there yourself. storebound opens the form, fills the fields below and marks the ones you answer.\n\n{}\n", policy::CONSOLE_FILL_NOTE); let answers = data["answers"].as_array().cloned().unwrap_or_default(); let mut lines: Vec = answers .iter() diff --git a/apps/desktop/src-tauri/tests/d3_writes.rs b/apps/desktop/src-tauri/tests/d3_writes.rs index e22ae7f0..f9670d78 100644 --- a/apps/desktop/src-tauri/tests/d3_writes.rs +++ b/apps/desktop/src-tauri/tests/d3_writes.rs @@ -72,6 +72,7 @@ fn console_fill_is_a_dry_run_from_the_window_and_its_dialog_lists_the_answers() assert_eq!(title, "Fill in console: Age rating"); assert_eq!(ok, "Open the browser"); assert!(text.contains("Prism Puddle") && text.contains(CONSOLE_FILL_NOTE)); + assert!(text.contains("uses your Chrome sign-in") && text.contains("deletes it when the window closes")); assert!(text.contains("- Cartoon violence: None") && text.contains("- Simulated gambling: you answer this")); let (_, empty, _) = console_fill_dialog("A", &json!(null)); assert!(empty.contains("every field is yours")); diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index 5ba1ee30..97c262f3 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -1276,7 +1276,7 @@ export const en = { 'cf.panelTitle': 'Fill in console: {form}', 'cf.disclaimer': 'Console pages change. This is AI-assisted: review every field in the browser and press Save yourself. storebound never saves, submits or publishes.', 'cf.notOpened': 'You chose Cancel in the dialog: no browser was opened.', - 'cf.runningText': 'The browser is open. Sign in there yourself; storebound fills the fields and marks the ones you answer. Review every field, press Save yourself, then close the browser.', + 'cf.runningText': 'The browser is open with your Chrome sign-in (if it asks, sign in there yourself). storebound opens the form, fills the fields and marks the ones you answer. Review every field, press Save yourself, then close the browser.', 'cf.doneText': 'Browser closed. Filled: {filled}, marked for you: {highlighted}. Check in the console that your answers are saved.', 'cf.closed': 'Browser closed.', 'cf.cancelled': 'Stopped: the browser was closed.', diff --git a/apps/desktop/src/i18n/tr.ts b/apps/desktop/src/i18n/tr.ts index 338abe82..fef95f0a 100644 --- a/apps/desktop/src/i18n/tr.ts +++ b/apps/desktop/src/i18n/tr.ts @@ -1278,7 +1278,7 @@ export const tr: Record = { 'cf.panelTitle': 'Konsolda doldur: {form}', 'cf.disclaimer': 'Konsol sayfaları değişebilir. Bu, yapay zekâ destekli bir yardımdır: tarayıcıda her alanı kontrol edin ve Kaydet\'e kendiniz basın. storebound hiçbir zaman kaydetmez, göndermez veya yayınlamaz.', 'cf.notOpened': 'İletişim kutusunda Vazgeç\'i seçtiniz: tarayıcı açılmadı.', - 'cf.runningText': 'Tarayıcı açık. Orada kendiniz oturum açın; storebound alanları doldurur ve yanıtı size kalanları işaretler. Her alanı kontrol edin, Kaydet\'e kendiniz basın ve ardından tarayıcıyı kapatın.', + 'cf.runningText': 'Tarayıcı Chrome oturumunuzla açık (isterse orada kendiniz oturum açın). storebound formu açar, alanları doldurur ve yanıtı size kalanları işaretler. Her alanı kontrol edin, Kaydet\'e kendiniz basın ve ardından tarayıcıyı kapatın.', 'cf.doneText': 'Tarayıcı kapandı. Doldurulan: {filled}, sizin için işaretlenen: {highlighted}. Yanıtlarınızın kaydedildiğini konsolda kontrol edin.', 'cf.closed': 'Tarayıcı kapandı.', 'cf.cancelled': 'Durduruldu: tarayıcı kapatıldı.', diff --git a/cli/console/fill.ts b/cli/console/fill.ts index 51c8b1d9..653f7c89 100644 --- a/cli/console/fill.ts +++ b/cli/console/fill.ts @@ -7,21 +7,26 @@ // it does not prove stays EMPTY and highlighted (AGENTS.md rule 5). // Safety: storebound never types passwords, never touches sign-in pages (it waits while the owner signs in), never reads // cookies or storage, and never clicks Save / Submit / Publish / Create / Next: every click goes through safeClick and -// its gate. The owner reviews each page, clicks Next, and presses the final button; the command ends when the window -// is closed. Locators are accessible names only (cli/lib/console-forms.ts); a missing or ambiguous field means the UI -// changed: filling stops and the guidance is printed instead. Not exposed over MCP. -// Profile: ~/.storebound/console-profile/ (or --profile / STOREBOUND_CONSOLE_PROFILE), so the sign-in is kept. +// its gate. After sign-in it opens the form itself (navPlan in cli/lib/console-forms.ts: Apps > + > New App, the app's +// App Privacy page, Play app list > the app > App content > Start / Manage); those clicks go through navClick, which +// applies the same gate (only a link named exactly Start / Manage / Başla / Yönet is let through). A step not found in +// time -> the printed steps, and storebound waits as before. The owner reviews each page, clicks Next, and presses the +// final button; the command ends when the window is closed. Locators are accessible names only +// (cli/lib/console-forms.ts); a missing or ambiguous field means the UI changed: filling stops and the guidance is +// printed instead. Not exposed over MCP. +// Browser (cli/console/session.ts): the owner's running Chrome (--cdp / remote debugging), else a temporary copy of only +// their Chrome sign-in cookies (macOS; deleted at the end), else storebound's own profile +// (~/.storebound/console-profile/, or --profile / STOREBOUND_CONSOLE_PROFILE / --fresh-profile). // Sources (checked October 2026): see cli/lib/console-answers.ts; Playwright launchPersistentContext, getByRole, // getByLabel: https://playwright.dev/docs/api/class-browsertype#browser-type-launch-persistent-context , // https://playwright.dev/docs/locators -import { mkdirSync } from 'node:fs'; import { homedir } from 'node:os'; import { join } from 'node:path'; import type { Ctx } from '../lib/ctx'; -import { type Answer, type ConsoleResult, consoleResult, DISCLAIMER, FORM_IDS, fillValue, formMeta, isForm, valueText } from '../lib/console-answers'; -import { consoleReached, type FieldDef, type FormDef, formDef, forbiddenControl, isSignInUrl, type Name } from '../lib/console-forms'; +import { type Answer, type ConsoleResult, consoleResult, DISCLAIMER, FORM_IDS, type FormId, fillValue, formMeta, isForm, valueText } from '../lib/console-answers'; +import { consoleReached, type FieldDef, type FormDef, formDef, FORM_OPENERS, forbiddenControl, hasToken, isSignInUrl, type Name, navAllowed, type NavStep, navPlan } from '../lib/console-forms'; import { log, printJson, warn } from '../lib/log'; -import { launchPersistent } from '../shots/browser'; +import { type ConsoleBrowser, openConsoleBrowser } from './session'; /* eslint-disable @typescript-eslint/no-explicit-any */ type Page = any; @@ -196,7 +201,160 @@ export async function signInPage(page: Page): Promise { try { return (await page.locator('input[type="password"]').count()) > 0; } catch { return false; } } -const active = (context: any): Page | undefined => { const ps = context.pages(); return ps[ps.length - 1]; }; + +// ---- navigation to the form (after sign-in) ---- + +/** The ARIA role the element really has (explicit role, else the implicit one for links, buttons and rows). */ +async function realRole(loc: Locator): Promise { + return loc.evaluate((el: any) => el.getAttribute('role') || (el.tagName === 'A' && el.hasAttribute('href') ? 'link' : el.tagName === 'BUTTON' ? 'button' : el.tagName === 'TR' ? 'row' : el.tagName.toLowerCase())); +} + +/** + * The navigation click gate: reads the element's real accessible name and role and refuses it unless navAllowed says + * so (the click gate stays absolute: never Save / Submit / Publish / Create / Send / Next ...; only a link named exactly + * Start / Manage / Başla / Yönet is let through). Every navigation click goes through here. + */ +export async function navClick(loc: Locator): Promise<{ clicked: boolean; name: string }> { + const name = await accName(loc), role = await realRole(loc); + if (!navAllowed(name, role)) { warn(TAG, `not clicking "${name}" while opening the form: storebound never presses save, submit, publish, next or similar`); return { clicked: false, name }; } + await loc.click(); + return { clicked: true, name }; +} + +export interface NavResult { + ok: boolean; + /** Labels of the steps done (["already open"] when the form was already on the page). */ + steps: string[]; + /** The step that could not be done (not found in time, ambiguous, or refused by the gate). */ + failed?: string; + why?: string; + /** pickApp: the matching apps when more than one matched (storebound stops and lists them). */ + candidates?: string[]; +} + +async function findAny(root: Locator, roles: string[], names: Name[]): Promise { + for (const role of roles) { const f = await find(root, role, names); if (f.state !== 'none') return f; } + return { state: 'none' }; +} + +/** Polls `fn` until it returns a value or the time is up (errors while the page navigates count as "not yet"). */ +async function poll(ms: number, fn: () => Promise): Promise { + const end = Date.now() + ms; + for (;;) { + try { const r = await fn(); if (r !== null) return r; } catch { /* navigating */ } + if (Date.now() >= end) return null; + await Bun.sleep(200); + } +} + +const opener = new RegExp(`^(?:${FORM_OPENERS.join('|')})$`); + +async function pickApp(page: Page, s: Extract, ms: number): Promise<{ loc?: Locator; candidates?: string[] } | null> { + if (s.search && s.tokens[0]) { + const box = await poll(Math.min(ms, 3000), async () => { const f = await findAny(page, ['searchbox', 'textbox', 'combobox'], s.search!); return f.state === 'ok' ? f.loc : null; }); + if (box) { await box.fill(s.tokens[0]); } + } + return poll(ms, async () => { + for (const role of ['row', 'link']) { + const all = vis(page.getByRole(role)); + const n = await all.count(); + const hits: { loc: Locator; name: string }[] = []; + for (let i = 0; i < n; i++) { + const loc = all.nth(i), name = await accName(loc); + const byToken = s.tokens.some(t => hasToken(name, t)); + const byName = role === 'link' && s.name !== undefined && name === s.name; + if (byToken || byName) hits.push({ loc, name }); + } + if (hits.length === 1) { + const row = hits[0]!.loc; + if (role === 'row') { const inner = vis(row.getByRole('link')); if (await inner.count() >= 1) return { loc: inner.first() }; } + return { loc: row }; + } + if (hits.length > 1) return { candidates: hits.map(h => h.name) }; + } + return null; + }); +} + +async function formLink(page: Page, entry: Name[], ms: number): Promise<{ loc?: Locator; ambiguous?: boolean } | null> { + return poll(ms, async () => { + const found: { loc: Locator; key: string }[] = []; + const add = async (box: Locator) => { + const l = vis(box.getByRole('link', { name: opener })); + if (await l.count() !== 1) return; + const b = await l.boundingBox(); + const key = b ? `${Math.round(b.x)},${Math.round(b.y)}` : String(found.length); + if (!found.some(f => f.key === key)) found.push({ loc: l, key }); + }; + for (const n of entry) { + for (const role of ['region', 'listitem', 'row', 'group', 'article']) { + const boxes = vis(page.getByRole(role, nameOpts(n))); + const c = await boxes.count(); + for (let i = 0; i < c; i++) await add(boxes.nth(i)); + } + if (found.length) break; + const boxes = vis(page.locator('section, li, tr, article, [role="listitem"], [role="row"], [role="region"]').filter({ hasText: n })); + const c = await boxes.count(); + for (let i = 0; i < c; i++) await add(boxes.nth(i)); + if (found.length) break; + } + if (found.length === 1) return { loc: found[0]!.loc }; + return found.length > 1 ? { ambiguous: true } : null; + }); +} + +/** The wait target is on the page (a heading of `level` when given). */ +async function present(page: Page, s: Extract): Promise { + if (s.level === undefined) return (await findAny(page, s.roles, s.names)).state !== 'none'; + for (const n of s.names) if (await vis(page.getByRole('heading', { ...nameOpts(n), level: s.level })).count() > 0) return true; + return false; +} + +/** + * Opens the form step by step (navPlan). Logs every step; stops at the first step that is not found within + * `timeoutMs`, is ambiguous, or is refused by the click gate, and says which. Never throws for a missing step. + */ +export async function navigate(page: Page, plan: NavStep[], opts: { timeoutMs?: number; say?: (m: string) => void } = {}): Promise { + const ms = opts.timeoutMs ?? 20_000, say = opts.say ?? ((m: string) => log(TAG, m)); + const steps: string[] = []; + const target = plan.at(-1); + if (target?.kind === 'wait' && await present(page, target).catch(() => false)) { + say(`the form is already open (${target.label})`); + return { ok: true, steps: ['already open'] }; + } + const fail = (s: NavStep, why: string, candidates?: string[]): NavResult => ({ ok: false, steps, failed: s.label, why, ...(candidates ? { candidates } : {}) }); + for (const [i, s] of plan.entries()) { + say(`opening the form, step ${i + 1}/${plan.length}: ${s.label}`); + if (s.kind === 'goto') { + try { await page.goto(s.url, { waitUntil: 'domcontentloaded' }); } catch (e) { return fail(s, `could not load ${s.url} (${(e as Error).message.split('\n')[0]})`); } + } else if (s.kind === 'click') { + if (s.optional && s.unless && (await findAny(page, s.unless.roles, s.unless.names)).state !== 'none') { say(' (not needed)'); continue; } + const f = await poll(s.optional ? Math.min(ms, 2000) : ms, async () => { const r = await findAny(page, s.roles, s.names); return r.state === 'none' ? null : r; }); + if (!f) { if (s.optional) { say(' (not on this page, skipped)'); continue; } return fail(s, 'not found'); } + if (f.state !== 'ok') return fail(s, 'more than one match'); + const c = await navClick(f.loc); + if (!c.clicked) return fail(s, `refused to click "${c.name}"`); + } else if (s.kind === 'pickApp') { + if (!s.tokens.length && !s.name) return fail(s, 'no bundle id, package name or app name in the config'); + const r = await pickApp(page, s, ms); + if (!r) return fail(s, `no app matching ${[...s.tokens, ...(s.name ? [`"${s.name}"`] : [])].join(' / ')} in the list`); + if (r.candidates) return fail(s, 'more than one app matches', r.candidates); + const c = await navClick(r.loc); + if (!c.clicked) return fail(s, `refused to click "${c.name}"`); + } else if (s.kind === 'formLink') { + const r = await formLink(page, s.entry, ms); + if (!r) return fail(s, 'no Start or Manage link next to it'); + if (r.ambiguous) return fail(s, 'more than one Start or Manage link matches'); + const c = await navClick(r.loc); + if (!c.clicked) return fail(s, `refused to click "${c.name}"`); + } else { + const f = await poll(ms, async () => ((await present(page, s)) ? true : null)); + if (!f) return fail(s, 'did not appear'); + } + steps.push(s.label); + } + return { ok: true, steps }; +} function printText(res: ConsoleResult): void { console.log(`${res.title}\n${res.url}\n`); @@ -216,6 +374,7 @@ export async function run(ctx: Ctx): Promise { return; } if (!isForm(form)) throw new Error(`console fill: unknown form "${form}" (one of ${FORM_IDS.join(', ')})`); + const fid: FormId = form; const meta = formMeta(form, config); const store = args.get('store'); if (store && store !== 'apple' && store !== 'play') throw new Error('--store: apple | play'); @@ -230,35 +389,51 @@ export async function run(ctx: Ctx): Promise { for (const d of DISCLAIMER) say(d); const startUrl = args.get('start-url'); if (startUrl && !/^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?\//.test(startUrl)) throw new Error('--start-url: only a local test page (http://127.0.0.1:/...)'); + const ownProfile = args.has('profile') || !!process.env.STOREBOUND_CONSOLE_PROFILE; const dir = args.get('profile') ?? process.env.STOREBOUND_CONSOLE_PROFILE ?? join(homedir(), '.storebound', 'console-profile', meta.store); - mkdirSync(dir, { recursive: true }); - const context = await launchPersistent(root, dir, { headless: false, viewport: null }); - let closed = false; - const closing = new Promise(r => context.on('close', () => { closed = true; r(); })); - const page = context.pages()[0] ?? await context.newPage(); + const b = await openConsoleBrowser(root, { + store: meta.store, profileDir: dir, say, fresh: args.has('fresh-profile') || ownProfile, + ...(args.get('cdp') ? { cdp: args.get('cdp') } : {}), ...(args.get('chrome-profile') ? { chromeProfile: args.get('chrome-profile') } : {}), + }); + // the temporary profile of copy mode goes away on every exit path + const bye = () => { b.cleanup(); process.exit(130); }; + process.once('SIGINT', bye); process.once('SIGTERM', bye); + try { await fillRun(b); } finally { b.cleanup(); process.off('SIGINT', bye); process.off('SIGTERM', bye); } + + async function fillRun(b: ConsoleBrowser): Promise { + const active = (): Page | undefined => b.pages().at(-1); + const page = b.page; await page.goto(startUrl ?? meta.url).catch(() => { /* the owner can navigate */ }); // 1. sign-in: the owner does it; storebound only watches the URL const deadline = Date.now() + 10 * 60_000; let told = false; - while (!closed && Date.now() < deadline) { - const p = active(context); + while (!b.isClosed() && Date.now() < deadline) { + const p = active(); if (p && !(await signInPage(p).catch(() => false)) && consoleReached(meta.store, p.url(), startUrl)) break; if (p && !told && await signInPage(p).catch(() => false)) { say('sign in in the browser window, storebound waits'); told = true; } await Bun.sleep(1000); } // 2. fill section by section as the owner moves through the form - const def = formDef(form, res.answers); - const pageAnswers = res.answers.map(a => ({ ...a, value: fillValue(form, a, config) })); + const def = formDef(fid, res.answers); + const pageAnswers = res.answers.map(a => ({ ...a, value: fillValue(fid, a, config) })); const labels = new Map(res.answers.map(a => [a.id, a.label])); const done = new Set(); let filled = 0, highlighted = 0, fallback = false; - for (const o of meta.open) say(`open the form: ${o}`); + // 2a. open the form: navigation clicks only (navClick); on any miss, the printed steps and wait as before + const plan = startUrl || b.isClosed() ? [] : navPlan(fid, config); + const nav = plan.length ? await navigate(active() ?? page, plan, { say }).catch((e: Error): NavResult => ({ ok: false, steps: [], failed: 'navigation', why: e.message.split('\n')[0] })) : null; + if (nav && !nav.ok) { + warn(TAG, `could not open the form by itself at step "${nav.failed}" (${nav.why}). Open it yourself; storebound waits and fills it when it appears:`); + if (nav.candidates) say(`apps that match: ${nav.candidates.join(' | ')} (set apple.appId / play.packageName in the config to pick one)`); + } + if (!nav?.ok) for (const o of meta.open) say(`open the form: ${o}`); + else if (meta.then) say(`now click ${meta.then} yourself; storebound fills the form when it appears`); const last = def.sections.length - 1; const finished = () => done.size === def.sections.length || (form !== 'apple-app-privacy' && done.has(last)); - while (!closed && !finished()) { - const p = active(context); + while (!b.isClosed() && !finished()) { + const p = active(); if (!p || await signInPage(p).catch(() => true)) { await Bun.sleep(1500); continue; } let s: FillStep; try { s = await fillPage(p, def, pageAnswers, done); } catch { await Bun.sleep(1500); continue; } // navigating @@ -275,8 +450,9 @@ export async function run(ctx: Ctx): Promise { } await Bun.sleep(1500); } - if (!closed && !fallback) say(`review every field and press ${meta.stopBefore} yourself. storebound never saves, submits or publishes. Close the window when done.`); - else if (!closed) say('close the browser window when done'); - await closing; - if (json) printJson({ ...res, filled, highlighted, fallback, stoppedAt: meta.stopBefore }); + if (!b.isClosed() && !fallback) say(`review every field and press ${meta.stopBefore} yourself. storebound never saves, submits or publishes. Close the window when done.`); + else if (!b.isClosed()) say('close the browser window when done'); + await b.closed; + if (json) printJson({ ...res, filled, highlighted, fallback, stoppedAt: meta.stopBefore, browser: b.mode }); + } } diff --git a/cli/console/session.ts b/cli/console/session.ts new file mode 100644 index 00000000..6faafbcb --- /dev/null +++ b/cli/console/session.ts @@ -0,0 +1,227 @@ +// The browser `storebound console fill` works in, picked so the owner signs in as rarely as possible (the log says which): +// (a) attach: Chrome already runs with remote debugging (a DevToolsActivePort file in its user data dir, or +// --cdp http://127.0.0.1:): connectOverCDP and one new tab in that session; storebound closes only its tab. +// (b) copy (default on macOS when Google Chrome is installed): a temporary profile with ONLY `Local State` and the +// profile's `Cookies` (+ `Cookies-journal`), filtered down to the cookies App Store Connect and Play Console use +// (apple.com, google.com domains: appstoreconnect / idmsa / play / accounts), opened in real Google Chrome +// (Chrome 136+ refuses automation on its default user data dir, a copy is fine). Chrome decrypts the cookies with +// its own Keychain key ("Chrome Safe Storage"); macOS may ask once to allow that. Never copied: passwords +// (Login Data), history, extensions, anything else. The temporary profile is deleted when the run ends (also on +// an error, Ctrl+C or when the desktop app cancels). `--chrome-profile ` picks a profile ("Profile 1"); +// default: the last used one. `--fresh-profile` skips (a) and (b). +// (c) storebound's own persistent profile (~/.storebound/console-profile/): the owner signs in there once. +// Cookies are never printed, logged or sent anywhere: only file names and counts are reported. +// Sources (checked October 2026): Chrome user data dir and DevToolsActivePort +// https://chromium.googlesource.com/chromium/src/+/main/docs/user_data_dir.md ; Chrome 136 remote debugging change +// https://developer.chrome.com/blog/remote-debugging-port ; Playwright connectOverCDP / ignoreDefaultArgs +// https://playwright.dev/docs/api/class-browsertype +import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { homedir, tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { chromiumFor, launchPersistent } from '../shots/browser'; + +/* eslint-disable @typescript-eslint/no-explicit-any */ + +/** Hosts whose cookies the consoles need; a cookie is kept when its domain applies to one of them. */ +export const CONSOLE_HOSTS = ['appstoreconnect.apple.com', 'idmsa.apple.com', 'apple.com', 'play.google.com', 'accounts.google.com']; + +/** Files of a Chrome profile that are never copied (passwords, history, extensions, form data ...). */ +export const NEVER_COPY = /(^|\/)(Login Data|History|Extensions|Web Data|Bookmarks|Sessions|Preferences|Secure Preferences|Local Storage|IndexedDB|Account Web Data)/; + +/** Google Chrome's user data dir on this OS. */ +export function chromeDataDir(platform: string = process.platform, home: string = homedir(), env: Record = process.env): string { + if (platform === 'darwin') return join(home, 'Library', 'Application Support', 'Google', 'Chrome'); + if (platform === 'win32') return join(env.LOCALAPPDATA ?? join(home, 'AppData', 'Local'), 'Google', 'Chrome', 'User Data'); + return join(env.XDG_CONFIG_HOME ?? join(home, '.config'), 'google-chrome'); +} + +/** The profile dir name: --chrome-profile, else Local State's last used profile, else Default. */ +export function pickProfile(localState: string | null, requested?: string): string { + if (requested) { + if (!/^[\w .-]+$/.test(requested) || requested.includes('..')) throw new Error('--chrome-profile: a profile folder name such as "Default" or "Profile 1"'); + return requested; + } + try { const last = JSON.parse(localState ?? '{}')?.profile?.last_used; if (typeof last === 'string' && /^[\w .-]+$/.test(last) && !last.includes('..')) return last; } catch { /* default */ } + return 'Default'; +} + +/** + * The files the copy takes, as [source relative to the user data dir, destination relative to the temp dir]: Local + * State and the profile's cookie store (Cookies, or Network/Cookies on newer layouts) with its journal. The profile + * always lands in `Default` of the temp dir. Nothing else, ever. + */ +export function sessionFiles(profile: string, exists: (rel: string) => boolean): [string, string][] { + const out: [string, string][] = []; + if (exists('Local State')) out.push(['Local State', 'Local State']); + for (const sub of ['', 'Network/']) { + const db = `${profile}/${sub}Cookies`; + if (!exists(db)) continue; + out.push([db, `Default/${sub}Cookies`]); + if (exists(`${db}-journal`)) out.push([`${db}-journal`, `Default/${sub}Cookies-journal`]); + } + for (const [s] of out) if (NEVER_COPY.test(s)) throw new Error(`session copy: refusing to copy ${s}`); + return out; +} + +/** A cookie stored for `hostKey` (".google.com" or "play.google.com") is sent to one of `hosts`. */ +export function cookieApplies(hostKey: string, hosts: string[] = CONSOLE_HOSTS): boolean { + const d = hostKey.replace(/^\./, '').toLowerCase(); + if (!d.includes('.')) return false; // never a whole top-level domain + return hosts.some(h => h === d || h.endsWith(`.${d}`)); +} + +/** Deletes every cookie of the copied DB that the consoles never get. Returns counts only (never values or names). */ +export async function filterCookies(dbPath: string, hosts: string[] = CONSOLE_HOSTS): Promise<{ kept: number; removed: number }> { + const { Database } = await import('bun:sqlite'); + const db = new Database(dbPath); + try { + const keys = (db.query('SELECT DISTINCT host_key AS h FROM cookies').all() as { h: string }[]).map(r => r.h); + const drop = keys.filter(k => !cookieApplies(k, hosts)); + const count = (db.query('SELECT COUNT(*) AS n FROM cookies').get() as { n: number }).n; + const del = db.prepare('DELETE FROM cookies WHERE host_key = ?'); + db.transaction(() => { for (const k of drop) del.run(k); })(); + const kept = (db.query('SELECT COUNT(*) AS n FROM cookies').get() as { n: number }).n; + db.exec('VACUUM'); + return { kept, removed: count - kept }; + } finally { db.close(); } +} + +export interface SessionCopy { dir: string; profile: string; files: string[]; filtered: boolean; kept?: number; cleanup: () => void } + +/** + * Copies the session files of `src` (a Chrome user data dir) into a new temp dir and filters the cookies to `hosts`. + * On any error the temp dir is removed before the error is thrown. + */ +export async function copySession(src: string, opts: { profile?: string; hosts?: string[]; tmpRoot?: string } = {}): Promise { + const ls = existsSync(join(src, 'Local State')) ? readFileSync(join(src, 'Local State'), 'utf8') : null; + const profile = pickProfile(ls, opts.profile); + const files = sessionFiles(profile, rel => existsSync(join(src, rel))); + if (!files.some(([s]) => s.endsWith('Cookies'))) throw new Error(`no Chrome cookie store in profile "${profile}"`); + const dir = mkdtempSync(join(opts.tmpRoot ?? tmpdir(), 'storebound-chrome-')); + const cleanup = () => { + // Chrome may still write a file while it exits: retry, and only stop once the folder is gone + for (let i = 0; i < 5 && existsSync(dir); i++) { try { rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 }); } catch { Bun.sleepSync(100); } } + }; + try { + for (const [s, d] of files) { mkdirSync(dirname(join(dir, d)), { recursive: true }); copyFileSync(join(src, s), join(dir, d)); } + let filtered = false, kept: number | undefined; + try { + for (const [, d] of files.filter(([, d]) => d.endsWith('Cookies'))) kept = (kept ?? 0) + (await filterCookies(join(dir, d), opts.hosts)).kept; + filtered = true; + } catch { /* the whole cookie store stays (said in the log) */ } + return { dir, profile, files: files.map(([s]) => s), filtered, ...(kept !== undefined ? { kept } : {}), cleanup }; + } catch (e) { cleanup(); throw e; } +} + +/** The DevTools endpoint of a Chrome running with remote debugging (its DevToolsActivePort file), or null. */ +export function devToolsEndpoint(dataDir: string): string | null { + try { + const [port] = readFileSync(join(dataDir, 'DevToolsActivePort'), 'utf8').split('\n'); + return port && /^\d+$/.test(port.trim()) ? `http://127.0.0.1:${port.trim()}` : null; + } catch { return null; } +} + +const LOCAL_CDP = /^(https?|wss?):\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?(\/|$)/; + +export type BrowserMode = 'attach' | 'copy' | 'profile'; + +export interface ConsoleBrowser { + mode: BrowserMode; + context: any; + /** The tab storebound works in. */ + page: any; + /** The tabs storebound may look at (its own tab and the popups it opened; in copy / profile mode every tab). */ + pages: () => any[]; + /** Resolves when the owner closed the window (copy / profile) or storebound's tab (attach). */ + closed: Promise; + isClosed: () => boolean; + /** Removes the temporary profile (copy mode); safe to call twice. */ + cleanup: () => void; + /** Copy mode: the temporary profile (deleted by cleanup and when the window closes). */ + tempDir?: string; +} + +export interface OpenOpts { + store: 'apple' | 'play'; + /** --cdp: a local DevTools endpoint to attach to. */ + cdp?: string; + /** --chrome-profile. */ + chromeProfile?: string; + /** --fresh-profile: skip attach and copy. */ + fresh?: boolean; + /** storebound's own profile dir (mode c). */ + profileDir: string; + /** Overrides for tests: Chrome's user data dir, the hosts kept, headless, the platform. */ + chromeDir?: string; + hosts?: string[]; + headless?: boolean; + platform?: string; + say: (m: string) => void; +} + +function wrapContext(mode: BrowserMode, context: any, page: any, cleanup: () => void): ConsoleBrowser { + let closed = false; + const done = new Promise(r => context.on('close', async () => { + closed = true; + cleanup(); + await Bun.sleep(300); // a late write of the exiting browser + cleanup(); + r(); + })); + return { mode, context, page, pages: () => context.pages(), closed: done, isClosed: () => closed, cleanup }; +} + +/** Opens the browser in the first mode that works: attach, copy, then storebound's own profile. */ +export async function openConsoleBrowser(root: string, o: OpenOpts): Promise { + const chromeDir = o.chromeDir ?? chromeDataDir(o.platform); + if (!o.fresh) { + // (a) attach to a running Chrome with remote debugging + if (o.cdp && !LOCAL_CDP.test(o.cdp)) throw new Error('--cdp: only a local DevTools endpoint (http://127.0.0.1:)'); + const endpoint = o.cdp ?? devToolsEndpoint(chromeDir); + if (endpoint) { + try { + const c = await chromiumFor(root); + const browser = await c.connectOverCDP(endpoint, { timeout: 5000 }); + const context = browser.contexts()[0] ?? await browser.newContext(); + const page = await context.newPage(); + const own = new Set([page]); + page.on('popup', (p: any) => own.add(p)); + let closed = false; + const done = new Promise(r => page.on('close', () => { closed = true; r(); })); + o.say('browser: attached to your running Chrome (remote debugging); storebound works in one new tab and closes only that tab'); + return { mode: 'attach', context, page, pages: () => [...own].filter(p => !p.isClosed()), closed: done, isClosed: () => closed, cleanup: () => { /* nothing copied */ } }; + } catch (e) { + if (o.cdp) throw new Error(`--cdp: could not attach to ${o.cdp} (${(e as Error).message.split('\n')[0]})`); + o.say('browser: Chrome has a DevTools port file but storebound could not attach; trying your Chrome sign-in instead'); + } + } + // (b) a copy of only the session files, opened in real Google Chrome + if ((o.platform ?? process.platform) === 'darwin' && existsSync(chromeDir)) { + let copy: SessionCopy | null = null; + try { + copy = await copySession(chromeDir, { ...(o.chromeProfile ? { profile: o.chromeProfile } : {}), ...(o.hosts ? { hosts: o.hosts } : {}) }); + const c = await chromiumFor(root); + const context = await c.launchPersistentContext(copy.dir, { + channel: 'chrome', headless: o.headless ?? false, viewport: null, + // Playwright's mock keychain would hide Chrome's own key, and the cookies could not be read + ignoreDefaultArgs: ['--use-mock-keychain', '--password-store=basic'], + }); + o.say(`browser: your Chrome sign-in (profile "${copy.profile}"). storebound copied only ${copy.files.join(', ')} into a temporary profile` + + `${copy.filtered ? `, kept only the cookies for App Store Connect and Play Console (${copy.kept ?? 0})` : ' (the whole cookie file: it could not be filtered)'}` + + ', and deletes it when this run ends. Passwords, history and extensions are never copied. macOS may ask once to let Google Chrome use "Chrome Safe Storage" in your Keychain: that is Chrome reading its own cookies. Opt out: --fresh-profile'); + const page = context.pages()[0] ?? await context.newPage(); + const cp = copy; + return { ...wrapContext('copy', context, page, () => cp.cleanup()), tempDir: cp.dir }; + } catch (e) { + copy?.cleanup(); + o.say(`browser: could not use your Chrome sign-in (${(e as Error).message.split('\n')[0]}); using storebound's own profile`); + } + } + } + // (c) storebound's persistent profile, the owner signs in there + mkdirSync(o.profileDir, { recursive: true }); + const context = await launchPersistent(root, o.profileDir, { headless: o.headless ?? false, viewport: null }); + o.say(`browser: storebound's own profile (${o.profileDir}); sign in there once, it is kept for the next run`); + const page = context.pages()[0] ?? await context.newPage(); + return wrapContext('profile', context, page, () => { /* kept on purpose */ }); +} diff --git a/cli/lib/console-answers.ts b/cli/lib/console-answers.ts index d5b8c68c..d13b3c1a 100644 --- a/cli/lib/console-answers.ts +++ b/cli/lib/console-answers.ts @@ -27,8 +27,10 @@ export interface Answer { id: string; label: string; value: AnswerValue; certain export interface FormMeta { id: FormId; store: Store; title: string; url: string; - /** What the owner clicks to open the form (no deep link exists, or it needs ids the config does not have). */ + /** What the owner clicks to open the form when storebound cannot open it itself (a navigation step was not found). */ open: string[]; + /** What the owner still clicks after storebound opened the page (a control the click gate refuses, e.g. Get Started). */ + then?: string; /** The control storebound stops before; the owner presses it. */ stopBefore: string; /** false: no page filling at all, guidance only (the API covers it). */ @@ -51,14 +53,16 @@ export const isForm = (s: string | undefined): s is FormId => !!s && (FORM_IDS a export function formMeta(id: FormId, config: ShipConfig): FormMeta { const app = config.apple?.appId ? `${ASC}/apps/${config.apple.appId}` : `${ASC}/apps`; + const privacy = config.apple?.appId ? `${app}/distribution/privacy` : app; const pickApp = 'Pick the developer account and the app if Play Console asks'; switch (id) { case 'apple-app-record': return { id, store: 'apple', title: 'App Store Connect: New App', url: `${ASC}/apps`, stopBefore: 'Create', fillable: true, open: ['Apps > the add button (+) at the top left > New App'] }; case 'apple-age-rating': return { id, store: 'apple', title: 'App Store Connect: Age Ratings', url: app, stopBefore: 'Save', fillable: false, open: ['General > App Information > Age Ratings > Set Up Age Ratings (only to look: `storebound apple appinfo` sets it)'] }; - case 'apple-app-privacy': return { id, store: 'apple', title: 'App Store Connect: App Privacy', url: app, stopBefore: 'Publish', fillable: true, - open: [...(config.apple?.appId ? [] : ['Open the app (apple.appId is not in the config, so storebound cannot open it for you)']), 'App Privacy in the sidebar > Get Started (or Edit next to Data Types)'] }; + case 'apple-app-privacy': return { id, store: 'apple', title: 'App Store Connect: App Privacy', url: privacy, stopBefore: 'Publish', fillable: true, + open: [...(config.apple?.appId ? [] : ['Apps > your app (set apple.appId so storebound opens it directly)']), 'App Privacy in the sidebar > Get Started (or Edit next to Data Types)'], + then: 'Get Started (or Edit next to Data Types)' }; case 'play-content-rating': return { id, store: 'play', title: 'Play Console: Content rating (IARC)', url: PLAY, stopBefore: 'Submit', fillable: true, open: [pickApp, 'Policy > App content > Content rating > Start (or Start new questionnaire)'] }; case 'play-target-audience': return { id, store: 'play', title: 'Play Console: Target audience and content', url: PLAY, stopBefore: 'Save', fillable: true, diff --git a/cli/lib/console-forms.ts b/cli/lib/console-forms.ts index 32771753..bf0a113c 100644 --- a/cli/lib/console-forms.ts +++ b/cli/lib/console-forms.ts @@ -5,7 +5,7 @@ // The names are modeled on Apple's and Google's public help pages (sources in console-answers.ts), not recorded from a // signed-in console: the exact App Privacy dialog titles, the IARC question wording and the Play category names could // not be verified without an account, which is why every field has candidates and the engine falls back on a miss. -import { AGE_GROUPS } from './config'; +import { AGE_GROUPS, type ShipConfig } from './config'; import { AGE_LABELS, type Answer, APPLE_PURPOSES, type FormId } from './console-answers'; /** An accessible name: a string matches exactly, a RegExp matches the name. */ @@ -101,10 +101,11 @@ export function formDef(id: FormId, answers: Answer[]): FormDef { */ const EN = ['save', 'saved', 'submit', 'publish', 'create', 'send', 'apply', 'confirm', 'done', 'release', 'rollout', 'roll out', 'start', 'delete', 'remove', 'next', 'continue', 'finish', 'agree', 'accept', 'upload', 'deploy', 'discard', 'update', 'add for review', 'review', 'sign', 'log in', 'login']; -const TR = ['kaydet', 'gönder', 'yayınla', 'yayımla', 'oluştur', 'uygula', 'onayla', 'tamam', 'bitti', 'bitir', 'sil', 'kaldır', 'başlat', 'sürüm', +const TR = ['kaydet', 'gönder', 'yayınla', 'yayımla', 'oluştur', 'onayla', 'tamam', 'bitti', 'bitir', 'sil', 'kaldır', 'başlat', 'sürüm', 'ileri', 'devam', 'sonraki', 'kabul', 'yükle', 'güncelle', 'incelemeye', 'giriş']; const L = '\\p{L}\\p{N}'; -const FORBIDDEN = new RegExp(`(? FORBIDDEN.test(name.toLocaleLowerCase('tr').normalize('NFC')) || FORBIDDEN.test(name.toLowerCase()); @@ -128,3 +129,89 @@ export function consoleReached(store: 'apple' | 'play', url: string, base?: stri : u.hostname === 'play.google.com' && u.pathname.startsWith('/console') && !u.pathname.includes('signup'); } catch { return false; } } + +// ---- navigation to the form after sign-in (`storebound console fill` opens the form itself) ---- +// Navigation clicks are allowed, saving / submitting / publishing never: every navigation click goes through navClick, +// which reads the element's real accessible name and checks it with navAllowed: the click gate above stays absolute. +// The one exception is FORM_OPENERS: a LINK whose whole name is exactly Start / Manage / Başla / Yönet (Play's App +// content entries), which only opens a form; a button named Start, or "Start rollout", stays refused. +// URLs (checked October 2026): App Store Connect app list /apps and an app's App Privacy page +// /apps//distribution/privacy. Play Console has no deep link without the developer and app ids (the config has +// neither), so Play is navigated by role + name from the app list. A step not found in time -> the printed steps. + +/** One navigation step. Steps are logged by `label`; a failed step is named in the fallback. */ +export type NavStep = + | { kind: 'goto'; label: string; url: string } + /** Click the one visible control of one of `roles` named like one of `names`. `optional`: skipped when absent or when `unless` is already visible. */ + | { kind: 'click'; label: string; roles: string[]; names: Name[]; optional?: boolean; unless?: { roles: string[]; names: Name[] } } + /** Pick the app from the list: rows / links whose name contains one of `tokens` (bundle id / package name) as a whole token, else whose name is `name`. */ + | { kind: 'pickApp'; label: string; tokens: string[]; name?: string; search?: Name[] } + /** The Start / Manage link of the App content entry named like `entry`. */ + | { kind: 'formLink'; label: string; entry: Name[] } + /** Wait for a visible element of one of `roles` named like `names` (the form is open); `level`: headings of that level only. */ + | { kind: 'wait'; label: string; roles: string[]; names: Name[]; level?: number }; + +/** Link names that only open a form (whole name, links only): allowed although "start" is in the click gate. */ +export const FORM_OPENERS = ['Start', 'Manage', 'Başla', 'Yönet']; + +/** URL bases (tests point them at 127.0.0.1 fixtures). */ +export interface NavBases { asc: string; play: string } +export const NAV_BASES: NavBases = { asc: 'https://appstoreconnect.apple.com', play: 'https://play.google.com/console' }; + +const APP_CONTENT: Name[] = ['App content', 'Uygulama içeriği', 'Uygulama İçeriği']; +const POLICY: Name[] = ['Policy and programs', 'Policy', 'Politika ve programlar', 'Politika']; + +/** + * The steps that open a form after sign-in, built from the config only (apple.appId, apple.bundleId, play.packageName, + * app.name). The last step waits for the form itself. Pure. + */ +export function navPlan(id: FormId, config: ShipConfig, bases: NavBases = NAV_BASES): NavStep[] { + const asc = bases.asc.replace(/\/$/, ''), play = bases.play.replace(/\/$/, ''); + const name = config.app?.name; + const named = name ? { name } : {}; + switch (id) { + case 'apple-app-record': return [ + { kind: 'goto', label: 'open Apps', url: `${asc}/apps` }, + { kind: 'click', label: 'the add button (+)', roles: ['button'], names: ['+', 'Add Apps', 'Add App', 'New App', 'Uygulama Ekle', 'Uygulama ekle', 'Yeni Uygulama', /^add apps?$/i] }, + { kind: 'click', label: 'New App in the menu', roles: ['menuitem', 'menuitemradio', 'link', 'button'], names: ['New App', 'Yeni Uygulama', /^new app$/i, /^yeni uygulama$/iu] }, + { kind: 'wait', label: 'the New App dialog', roles: ['dialog'], names: ['New App', 'Yeni Uygulama', /^new app\b/i, /^yeni uygulama\b/iu] }, + ]; + case 'apple-age-rating': return []; + case 'apple-app-privacy': { + const appId = config.apple?.appId; + const open: NavStep[] = appId ? [{ kind: 'goto', label: 'open App Privacy of the app (apple.appId)', url: `${asc}/apps/${encodeURIComponent(appId)}/distribution/privacy` }] : [ + { kind: 'goto', label: 'open Apps', url: `${asc}/apps` }, + { kind: 'pickApp', label: 'the app in the list', tokens: config.apple?.bundleId ? [config.apple.bundleId] : [], ...named }, + { kind: 'click', label: 'App Privacy in the sidebar', roles: ['link', 'tab'], names: ['App Privacy', 'Uygulama Gizliliği', /^app privacy$/i] }, + ]; + return [...open, { kind: 'wait', label: 'the App Privacy page', roles: ['heading'], names: ['App Privacy', 'Uygulama Gizliliği', /^app privacy$/i] }]; + } + case 'play-content-rating': + case 'play-target-audience': { + const [title, entry]: [string, Name[]] = id === 'play-content-rating' + ? ['Content rating', ['Content rating', 'Content ratings', 'İçerik derecelendirmesi', /^content ratings?$/i]] + : ['Target audience and content', ['Target audience and content', 'Hedef kitle ve içerik', /^target audience\b/i, /^hedef kitle\b/iu]]; + return [ + { kind: 'goto', label: 'open Play Console', url: play }, + { kind: 'pickApp', label: 'the app in the list', tokens: config.play?.packageName ? [config.play.packageName] : [], ...named, search: [/^search/i, 'Uygulama ara', /^ara$/iu] }, + { kind: 'click', label: 'Policy and programs (opens the menu)', roles: ['button', 'link'], names: POLICY, optional: true, unless: { roles: ['link'], names: APP_CONTENT } }, + { kind: 'click', label: 'App content', roles: ['link'], names: APP_CONTENT }, + { kind: 'formLink', label: `${title}: Start or Manage`, entry }, + { kind: 'wait', label: `the ${title} form`, roles: ['heading'], names: entry, level: 1 }, + ]; + } + } +} + +/** + * The navigation click gate: true when storebound may click a control with this accessible name and role while it + * opens a form. forbiddenControl stays absolute; the only exception is a FORM_OPENERS link (whole name). + */ +export function navAllowed(name: string, role: string): boolean { + const n = name.trim().replace(/\s+/g, ' '); + if (FORM_OPENERS.includes(n)) return role === 'link'; // a Start / Başla BUTTON may start something: never + return n.length > 0 && !forbiddenControl(n); +} + +/** `id` as a whole token of `text` (com.example.game, not com.example.game2 or com.example.gamepro). */ +export const hasToken = (text: string, id: string): boolean => new RegExp(`(? ['--render', String(i.file)] }, { name: 'console_fill', title: 'Fill in a console form', command: ['console', 'fill'], write: true, network: true, description: 'Fills one store console form that has no API (App Store app record, age rating, App Privacy; Play content rating, target audience) from the config in a visible Chromium the owner signs in to; uncertain fields are highlighted. It never saves, submits or publishes: the owner reviews every field and presses Save. The dry run lists the answers; the real run lasts until the owner closes the browser.', - props: { form: { type: 'string', enum: CONSOLE_FORMS, description: 'The console form' }, store: { type: 'string', enum: ['apple', 'play'], description: 'Default: from the form' } }, - required: ['form'], args: i => [String(i.form), ...opt('store', i.store)] }, + props: { form: { type: 'string', enum: CONSOLE_FORMS, description: 'The console form' }, store: { type: 'string', enum: ['apple', 'play'], description: 'Default: from the form' }, + fresh_profile: { type: 'boolean', default: false, description: "Use storebound's own browser profile (sign in there) instead of the owner's Chrome sign-in (a temporary copy of only the console cookies, deleted at the end)" } }, + required: ['form'], args: i => [String(i.form), ...opt('store', i.store), ...(i.fresh_profile === true ? ['--fresh-profile'] : [])] }, { name: 'prices_current', title: 'Current prices', command: ['prices', 'export'], write: false, network: true, description: 'Read-only: the current price of every product on both stores per region (Apple manual prices, with with_automatic also the equalized ones). Writes nothing.', props: { store: { type: 'string', enum: ['apple', 'play'] }, with_automatic: { type: 'boolean', default: false } }, diff --git a/cli/shots/browser.ts b/cli/shots/browser.ts index 4309fd34..7b9617c7 100644 --- a/cli/shots/browser.ts +++ b/cli/shots/browser.ts @@ -19,6 +19,10 @@ async function chromium(root: string): Promise { throw new Error('playwright not found: in your project run `bun add -d playwright` (and `bunx playwright install chromium` if Google Chrome is not installed)'); } +/** Playwright's chromium (same resolution as `launch`), for connectOverCDP and Chrome-channel launches. */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export const chromiumFor = (root: string): Promise => chromium(root); + // eslint-disable-next-line @typescript-eslint/no-explicit-any export async function launch(root: string, opts: Record): Promise { const c = await chromium(root); diff --git a/docs/desktop.md b/docs/desktop.md index dd948e79..a2821959 100644 --- a/docs/desktop.md +++ b/docs/desktop.md @@ -197,8 +197,11 @@ write, never an MCP tool): run lasts until the owner closes the browser: no timeout in serve, the runner or the host. Progress lines show in the panel; **Cancel: close the browser** sends `$/cancelRequest`, which stops the command and its browser. -The browser is the desktop's Chrome for Testing (`STOREBOUND_CHROME`, passed to the sidecar like for screenshot -renders) with the bundled playwright-core; without it, the same fallbacks as `shots render`. +The browser is the same as in the terminal (cli/console/session.ts): a Chrome running with remote debugging, else on +macOS the owner's Chrome sign-in (real Google Chrome on a temporary copy of only `Local State` and the console cookies, +deleted when the run ends or is cancelled; the native dialog says "It uses your Chrome sign-in"), else storebound's own +profile in the desktop's Chrome for Testing (`STOREBOUND_CHROME`) with the bundled playwright-core. The tool's +`fresh_profile: true` passes `--fresh-profile`. storebound opens the form itself after sign-in (navigation clicks only). ## Every CLI area in the window diff --git a/skills/console-autofill/SKILL.md b/skills/console-autofill/SKILL.md index 17684098..2aa2a07f 100644 --- a/skills/console-autofill/SKILL.md +++ b/skills/console-autofill/SKILL.md @@ -1,6 +1,6 @@ --- name: console-autofill -description: AI-assisted autofill of App Store Connect and Google Play Console forms that have no API (the New App dialog, App Privacy, the Play IARC content rating questionnaire, Target audience and content plus the Ads declaration; the App Store age rating is shown as guidance because the API sets it) in a visible Chromium the owner signs in to. Answers come only from storebound.config.ts; anything the config does not prove stays empty and highlighted. storebound never signs in, never saves, submits or publishes. Use when the user wants help filling one of these console forms, asks what to answer in them, or wants the answers as a checklist. +description: AI-assisted autofill of App Store Connect and Google Play Console forms that have no API (the New App dialog, App Privacy, the Play IARC content rating questionnaire, Target audience and content plus the Ads declaration; the App Store age rating is shown as guidance because the API sets it) in a visible browser that reuses the owner's Chrome sign-in (or one they sign in to); storebound opens the form itself. Answers come only from storebound.config.ts; anything the config does not prove stays empty and highlighted. storebound never signs in, never saves, submits or publishes. Use when the user wants help filling one of these console forms, asks what to answer in them, or wants the answers as a checklist. --- # Console autofill (forms without an API) @@ -9,8 +9,10 @@ CLI: `storebound` (or `bunx storebound` in a project that has it, or `bun ` in a terminal (or presses the button in the desktop app). A Chromium - window opens with its own profile (`~/.storebound/console-profile/`, or `--profile ` / - `STOREBOUND_CONSOLE_PROFILE`). If a sign-in page shows, storebound prints "sign in in the browser window, storebound - waits" and waits up to 10 minutes. The sign-in stays in that profile for the next run. -4. storebound prints what to click to open the form (Play Console has no deep link; App Store Connect opens the app - when `apple.appId` is set). When the form appears it fills the certain answers, outlines every unproven or - unfillable field with a "storebound: check this" label, and lists them in the terminal. +3. The owner runs `storebound console fill ` in a terminal (or presses the button in the desktop app). The + first log line says which browser it uses, in this order: + - **attach**: Chrome already runs with remote debugging (a `DevToolsActivePort` file in Chrome's user data folder, + or `--cdp http://127.0.0.1:`): storebound opens one new tab there and closes only that tab. + - **copy** (default on macOS with Google Chrome installed): the owner's existing Chrome sign-in, no second sign-in. + storebound copies ONLY `Local State` and the profile's `Cookies` (+ `Cookies-journal`) into a temporary folder, + deletes every cookie there except the ones App Store Connect and Play Console get (apple.com and google.com + domains), and opens real Google Chrome on that copy. Never copied: passwords (`Login Data`), history, extensions, + bookmarks or anything else. The temporary folder is deleted when the run ends (window closed, error, Ctrl+C, or + Cancel in the desktop app). Chrome decrypts the cookies with its own Keychain key ("Chrome Safe Storage"); macOS + may ask once to allow that. `--chrome-profile "Profile 1"` picks another Chrome profile (default: the last used). + Cookies are never printed, logged or sent anywhere. + - **profile** (`--fresh-profile`, `--profile `, `STOREBOUND_CONSOLE_PROFILE`, or when the other two do not + work): storebound's own profile (`~/.storebound/console-profile/`). The owner signs in there once; it is + kept for the next run. + If a sign-in page shows, storebound prints "sign in in the browser window, storebound waits" and waits up to 10 + minutes. It never types into a sign-in page. +4. After sign-in storebound opens the form itself and logs every step ("opening the form, step 2/4: the add button + (+)"): New App: Apps > + > New App; App Privacy: `/apps//distribution/privacy`, or the app list > the + app (by name / bundle id) > App Privacy; Play forms: the app list > the app (by `play.packageName`) > Policy and + programs > App content > the form's Start or Manage link. These navigation clicks pass the same click gate: never + Save, Submit, Publish, Create, Send, Next or the Turkish equivalents; only a LINK named exactly Start / Manage / + Başla / Yönet is let through. If a step is not found in time, or two apps match (they are listed: set + `apple.appId` / `play.packageName`), storebound says which step failed, prints what to click, and waits. App + Privacy: the owner clicks Get Started (or Edit next to Data Types). When the form appears storebound fills the + certain answers, outlines every unproven or unfillable field with a "storebound: check this" label, and lists them + in the terminal. 5. Multi-page forms: the owner reviews the page and clicks Next; storebound fills the next page when it appears. 6. On the last page storebound prints "review every field and press yourself". The command ends when the owner closes the window (`--json` then prints the result with `filled`, `highlighted`, diff --git a/tests/console-fill.test.ts b/tests/console-fill.test.ts index fb283a43..a1d70301 100644 --- a/tests/console-fill.test.ts +++ b/tests/console-fill.test.ts @@ -3,11 +3,11 @@ // the public help pages, not recorded) served on 127.0.0.1. No network. Browser tests skip when no Chromium launches. import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; import { join } from 'node:path'; -import { fillPage, run, safeClick, signInPage } from '../cli/console/fill'; +import { fillPage, navClick, navigate, run, safeClick, signInPage } from '../cli/console/fill'; import { parseArgs } from '../cli/lib/args'; import { type ShipConfig, validateExtras } from '../cli/lib/config'; -import { AGE_RATING_API, consoleAnswers, consoleResult, fillValue, FORM_IDS, type FormId } from '../cli/lib/console-answers'; -import { consoleReached, formDef, forbiddenControl, isSignInUrl } from '../cli/lib/console-forms'; +import { AGE_RATING_API, consoleAnswers, consoleResult, fillValue, FORM_IDS, type FormId, formMeta } from '../cli/lib/console-answers'; +import { consoleReached, formDef, FORM_OPENERS, forbiddenControl, hasToken, isSignInUrl, navAllowed, navPlan } from '../cli/lib/console-forms'; const config: ShipConfig = { app: { name: 'Example Game', profile: 'game', privacyPolicyUrl: 'https://example.com/privacy', supportUrl: 'https://example.com/support', website: 'https://example.com', contactEmail: 'support@example.com' }, @@ -154,11 +154,17 @@ try { if (!browser) console.warn(`console-fill browser tests skipped: no Chromium could launch (${skipWhy}). Run \`bunx playwright install chromium\`.`); const FIX = join(import.meta.dir, 'fixtures', 'console'); +/** Console URLs of the navigation plans -> modeled pages (bases: asc = asc, play = play). */ +const ROUTES: Record = { + '/asc/apps': 'asc-apps.html', '/asc-tr/apps': 'asc-apps-tr.html', '/asc-noplus/apps': 'asc-apps-noplus.html', '/asc-dup/apps': 'asc-apps-dup.html', + '/asc/apps/123/distribution/privacy': 'apple-app-privacy.html', '/play': 'play-apps.html', +}; let server: ReturnType | null = null; let base = ''; beforeAll(() => { server = Bun.serve({ hostname: '127.0.0.1', port: 0, fetch: req => { - const name = new URL(req.url).pathname.slice(1); + const path = new URL(req.url).pathname; + const name = path.endsWith('/_common.js') ? '_common.js' : ROUTES[path] ?? path.slice(1); if (!/^[a-z_-]+\.(html|js)$/.test(name)) return new Response('not found', { status: 404 }); return new Response(Bun.file(join(FIX, name))); } }); @@ -293,3 +299,139 @@ describe.skipIf(!browser)('engine (headless, modeled pages)', () => { await page.close(); }); }); + +// ---- navigation to the form after sign-in ---- + +const bases = (asc = 'asc') => ({ asc: base + asc, play: base + 'play' }); + +describe('navigation plan (pure)', () => { + test('apple-app-record: Apps > + > New App > the dialog', () => { + const p = navPlan('apple-app-record', config); + expect(p.map(s => s.kind)).toEqual(['goto', 'click', 'click', 'wait']); + expect(p[0]).toMatchObject({ url: 'https://appstoreconnect.apple.com/apps' }); + }); + test('apple-app-privacy: deep link with apple.appId, else the app list by name / bundle id', () => { + const withId = { ...config, apple: { ...config.apple!, appId: '123' } } as ShipConfig; + const deep = navPlan('apple-app-privacy', withId); + expect(deep[0]).toMatchObject({ kind: 'goto', url: 'https://appstoreconnect.apple.com/apps/123/distribution/privacy' }); + expect(deep).toHaveLength(2); + expect(formMeta('apple-app-privacy', withId).url).toBe('https://appstoreconnect.apple.com/apps/123/distribution/privacy'); + expect(navPlan('apple-app-privacy', config)[1]).toMatchObject({ kind: 'pickApp', tokens: ['com.example.game'], name: 'Example Game' }); + }); + test('play forms: app list by package name > App content > Start / Manage', () => { + for (const f of ['play-content-rating', 'play-target-audience'] as const) { + const p = navPlan(f, config); + expect(p.map(s => s.kind)).toEqual(['goto', 'pickApp', 'click', 'click', 'formLink', 'wait']); + expect(p[1]).toMatchObject({ tokens: ['com.example.game'] }); + } + expect(navPlan('apple-age-rating', config)).toEqual([]); + }); + test('no navigation step names a deny-listed control; Start / Manage pass only as links', () => { + const withId = { ...config, apple: { ...config.apple!, appId: '123' } } as ShipConfig; + for (const f of FORM_IDS) for (const s of [...navPlan(f, withId), ...navPlan(f, config)]) { + if (s.kind !== 'click') continue; + for (const n of s.names) if (typeof n === 'string') expect(forbiddenControl(n)).toBe(false); + } + for (const n of FORM_OPENERS) { expect(navAllowed(n, 'link')).toBe(true); expect(navAllowed(n, 'button')).toBe(false); } + for (const n of ['Save', 'Submit for Review', 'Publish', 'Create', 'Create app', 'Send 2 changes for review', 'Next', 'Kaydet', 'Gönder', 'Yayınla', 'Oluştur', + 'İleri', 'İncelemeye Gönder', 'Start rollout to Production', 'Start new release', 'Başlat', '']) + for (const role of ['link', 'button', 'menuitem', 'row']) expect(navAllowed(n, role)).toBe(false); + for (const n of ['+', 'Add Apps', 'New App', 'Yeni Uygulama', 'Uygulama Ekle', 'App content', 'Uygulama içeriği', 'App Privacy', 'Policy and programs', 'Example Game']) + expect(navAllowed(n, 'button')).toBe(true); + for (const n of ['Uygula', 'Değişiklikleri uygula', 'Uygulandı']) expect(forbiddenControl(n)).toBe(true); + for (const n of ['Uygulama Ekle', 'Yeni Uygulama', 'Uygulama içeriği', 'Uygulamalar']) expect(forbiddenControl(n)).toBe(false); + expect(hasToken('Example Game com.example.game', 'com.example.game')).toBe(true); + expect(hasToken('Example Game Pro com.example.gamepro', 'com.example.game')).toBe(false); + expect(hasToken('com.example.game.beta', 'com.example.game')).toBe(false); + }); +}); + +describe.skipIf(!browser)('navigation (headless, modeled pages)', () => { + const quiet = { timeoutMs: 1500, say: () => {} }; + const navClicks = (page: any): Promise => page.evaluate(() => (window as any).__navClicks()); + const noneDenied = (names: string[]) => { for (const n of names) expect(navAllowed(n, 'link')).toBe(true); }; + const fresh = async () => { const p = await browser.newPage(); await p.goto(base + 'signin.html'); await p.evaluate(() => sessionStorage.clear()); return p; }; + + test('App Store Connect (EN): + > New App opens the dialog and it is filled; Create and Submit for Review never clicked', async () => { + const page = await fresh(); + const r = await navigate(page, navPlan('apple-app-record', config, bases()), quiet); + expect(r).toMatchObject({ ok: true, steps: ['open Apps', 'the add button (+)', 'New App in the menu', 'the New App dialog'] }); + expect(await navClicks(page)).toEqual(['Add Apps', 'New App']); + const s = await fillPage(page, formDef('apple-app-record', pageAnswers('apple-app-record')), pageAnswers('apple-app-record')); + expect(s.fallback).toBe(false); + expect(s.filled).toContain('name'); + expect(await clicks(page)).toEqual(['+']); // the + button only, never Create / Submit for Review + await page.close(); + }); + + test('App Store Connect (TR): Uygulama Ekle > Yeni Uygulama; Oluştur and İncelemeye Gönder never clicked', async () => { + const page = await fresh(); + const r = await navigate(page, navPlan('apple-app-record', config, bases('asc-tr')), quiet); + expect(r.ok).toBe(true); + expect(await navClicks(page)).toEqual(['Uygulama Ekle', 'Yeni Uygulama']); + expect(await clicks(page)).toEqual(['+']); + await page.close(); + }); + + test('a missing step stops navigation, names the step and clicks nothing', async () => { + const page = await fresh(); + const said: string[] = []; + const r = await navigate(page, navPlan('apple-app-record', config, bases('asc-noplus')), { timeoutMs: 800, say: m => said.push(m) }); + expect(r).toMatchObject({ ok: false, failed: 'the add button (+)', why: 'not found', steps: ['open Apps'] }); + expect(said.some(m => m.includes('step 2/4: the add button (+)'))).toBe(true); + expect(await navClicks(page)).toEqual([]); + expect(formMeta('apple-app-record', config).open[0]).toContain('New App'); + await page.close(); + }); + + test('App Privacy: appId deep link, or app list > the app > App Privacy; two apps of one name -> stop and list', async () => { + let page = await fresh(); + let r = await navigate(page, navPlan('apple-app-privacy', { ...config, apple: { ...config.apple!, appId: '123' } } as ShipConfig, bases()), quiet); + expect(r).toMatchObject({ ok: true, steps: ['open App Privacy of the app (apple.appId)', 'the App Privacy page'] }); + await page.close(); + page = await fresh(); + r = await navigate(page, navPlan('apple-app-privacy', config, bases()), quiet); + expect(r.ok).toBe(true); + expect(await navClicks(page)).toEqual(['Example Game', 'App Privacy']); + expect(await clicks(page)).toEqual([]); // Publish on that page never clicked + await page.close(); + page = await fresh(); + r = await navigate(page, navPlan('apple-app-privacy', config, bases('asc-dup')), quiet); + expect(r).toMatchObject({ ok: false, failed: 'the app in the list', candidates: ['Example Game', 'Example Game'] }); + expect(await navClicks(page)).toEqual([]); + await page.close(); + }); + + test('Play: the app by package name > Policy and programs > App content > Start / Manage; nothing deny-listed clicked', async () => { + for (const [form, link, heading] of [['play-content-rating', 'Start', 'Content rating'], ['play-target-audience', 'Manage', 'Target audience and content']] as const) { + const page = await fresh(); + const r = await navigate(page, navPlan(form, config, bases()), quiet); + expect(r.ok).toBe(true); + const names = await navClicks(page); + expect(names).toEqual(['Example Game', 'Policy and programs', 'App content', link]); + noneDenied(names); + expect(await page.getByRole('heading', { level: 1 }).textContent()).toBe(heading); + await page.close(); + } + }); + + test('navClick refuses a Start button, Start rollout, Save and Publish even when pointed at them', async () => { + const page = await open('play-app-content.html'); + expect((await navClick(page.getByRole('button', { name: 'Start' }))).clicked).toBe(false); + expect((await navClick(page.getByRole('button', { name: 'Save' }))).clicked).toBe(false); + expect(await clicks(page)).toEqual([]); + await page.goto(base + 'play-dashboard.html'); + expect((await navClick(page.getByRole('link', { name: /Start rollout/ }))).clicked).toBe(false); + expect((await navClick(page.getByRole('button', { name: 'Publish' }))).clicked).toBe(false); + expect(await clicks(page)).toEqual([]); + await page.close(); + }); + + test('already on the form: nothing is clicked', async () => { + const page = await open('play-content-rating.html'); + const r = await navigate(page, navPlan('play-content-rating', config, bases()), quiet); + expect(r).toMatchObject({ ok: true, steps: ['already open'] }); + expect(await clicks(page)).toEqual([]); + await page.close(); + }); +}); diff --git a/tests/console-session.test.ts b/tests/console-session.test.ts new file mode 100644 index 00000000..f6602149 --- /dev/null +++ b/tests/console-session.test.ts @@ -0,0 +1,164 @@ +// storebound console fill: which browser it uses. Pure parts (data dir, profile pick, file selection, cookie host +// filter, DevToolsActivePort) and the session copy on throwaway folders (cleanup on success and on error). The +// integration test sets a cookie on a local fixture site in a THROWAWAY Chrome profile, then opens the console browser +// in copy mode from that profile and sees the cookie (and not the one of another host). It never touches the real +// Chrome profile or a store site; it skips when Google Chrome is not installed or not on macOS. +import { afterAll, describe, expect, test } from 'bun:test'; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { chromeDataDir, CONSOLE_HOSTS, cookieApplies, copySession, devToolsEndpoint, filterCookies, NEVER_COPY, openConsoleBrowser, pickProfile, sessionFiles } from '../cli/console/session'; + +const scratch = mkdtempSync(join(tmpdir(), 'sb-session-test-')); +afterAll(() => rmSync(scratch, { recursive: true, force: true })); +const tmp = (name: string) => { const d = join(scratch, name); mkdirSync(d, { recursive: true }); return d; }; + +async function cookieDb(path: string, hosts: string[]): Promise { + const { Database } = await import('bun:sqlite'); + const db = new Database(path); + db.exec('CREATE TABLE cookies (host_key TEXT, name TEXT, value TEXT, encrypted_value BLOB)'); + const ins = db.prepare('INSERT INTO cookies VALUES (?, ?, ?, ?)'); + for (const h of hosts) ins.run(h, 'c', '', new Uint8Array([1])); + db.close(); +} + +/** A fake Chrome user data dir with the session files and the ones that must never be copied. */ +async function fakeChrome(name: string, profile = 'Default'): Promise { + const d = tmp(name); + writeFileSync(join(d, 'Local State'), JSON.stringify({ profile: { last_used: profile } })); + mkdirSync(join(d, profile), { recursive: true }); + await cookieDb(join(d, profile, 'Cookies'), ['.apple.com', 'appstoreconnect.apple.com', '.google.com', 'play.google.com', 'accounts.google.com', '.youtube.com', 'mail.google.com', '.example.com', 'news.example.org']); + writeFileSync(join(d, profile, 'Cookies-journal'), ''); + for (const f of ['Login Data', 'History', 'Web Data', 'Bookmarks', 'Preferences']) writeFileSync(join(d, profile, f), 'x'); + mkdirSync(join(d, profile, 'Extensions'), { recursive: true }); + return d; +} + +describe('pure parts', () => { + test('Chrome user data dir per OS', () => { + expect(chromeDataDir('darwin', '/Users/you')).toBe('/Users/you/Library/Application Support/Google/Chrome'); + expect(chromeDataDir('linux', '/home/you', {})).toBe('/home/you/.config/google-chrome'); + expect(chromeDataDir('win32', 'C:\\Users\\you', { LOCALAPPDATA: 'L' })).toContain('User Data'); + }); + test('profile: --chrome-profile, else last used, else Default; no path tricks', () => { + expect(pickProfile(null)).toBe('Default'); + expect(pickProfile('{"profile":{"last_used":"Profile 2"}}')).toBe('Profile 2'); + expect(pickProfile('{"profile":{"last_used":"../x"}}')).toBe('Default'); + expect(pickProfile('not json', 'Profile 1')).toBe('Profile 1'); + expect(() => pickProfile(null, '../Default')).toThrow('--chrome-profile'); + }); + test('files: Local State and the cookie store only, never passwords, history or extensions', () => { + const all = new Set(['Local State', 'Default/Cookies', 'Default/Cookies-journal', 'Default/Login Data', 'Default/History', 'Default/Network/Cookies']); + expect(sessionFiles('Default', r => all.has(r))).toEqual([ + ['Local State', 'Local State'], ['Default/Cookies', 'Default/Cookies'], ['Default/Cookies-journal', 'Default/Cookies-journal'], ['Default/Network/Cookies', 'Default/Network/Cookies'], + ]); + expect(sessionFiles('Profile 1', r => r === 'Profile 1/Cookies')).toEqual([['Profile 1/Cookies', 'Default/Cookies']]); + for (const f of ['Default/Login Data', 'Default/History', 'Default/Extensions', 'Default/Web Data']) expect(NEVER_COPY.test(f)).toBe(true); + expect(NEVER_COPY.test('Default/Cookies')).toBe(false); + }); + test('cookie hosts: only domains the consoles get', () => { + for (const h of ['.apple.com', 'appstoreconnect.apple.com', 'idmsa.apple.com', '.google.com', 'play.google.com', 'accounts.google.com']) expect(cookieApplies(h)).toBe(true); + for (const h of ['.youtube.com', 'mail.google.com', 'developer.apple.com', '.example.com', 'apple.com.example.org', '', '.com']) expect(cookieApplies(h)).toBe(false); + expect(CONSOLE_HOSTS).toContain('play.google.com'); + }); + test('DevToolsActivePort -> a local endpoint', () => { + const d = tmp('devtools'); + expect(devToolsEndpoint(d)).toBeNull(); + writeFileSync(join(d, 'DevToolsActivePort'), '9333\n/devtools/browser/abc\n'); + expect(devToolsEndpoint(d)).toBe('http://127.0.0.1:9333'); + writeFileSync(join(d, 'DevToolsActivePort'), 'nope'); + expect(devToolsEndpoint(d)).toBeNull(); + }); +}); + +describe('session copy', () => { + test('copies only the session files, filters the cookies, cleans up', async () => { + const src = await fakeChrome('chrome-a'); + const root = tmp('copies-a'); + const c = await copySession(src, { tmpRoot: root }); + expect(c.profile).toBe('Default'); + expect(c.files).toEqual(['Local State', 'Default/Cookies', 'Default/Cookies-journal']); + for (const f of readdirSync(join(c.dir, 'Default'))) expect(['Cookies', 'Cookies-journal']).toContain(f); + expect(readdirSync(c.dir).sort()).toEqual(['Default', 'Local State']); + for (const f of ['Login Data', 'History', 'Web Data', 'Bookmarks', 'Preferences', 'Extensions']) expect(existsSync(join(c.dir, 'Default', f))).toBe(false); + expect(c.filtered).toBe(true); + expect(c.kept).toBe(5); + const { Database } = await import('bun:sqlite'); + const db = new Database(join(c.dir, 'Default', 'Cookies'), { readonly: true }); + expect((db.query('SELECT host_key AS h FROM cookies ORDER BY h').all() as { h: string }[]).map(r => r.h)).toEqual(['.apple.com', '.google.com', 'accounts.google.com', 'appstoreconnect.apple.com', 'play.google.com']); + db.close(); + c.cleanup(); c.cleanup(); + expect(existsSync(c.dir)).toBe(false); + expect(readdirSync(root)).toEqual([]); + // the source is untouched + expect(existsSync(join(src, 'Default', 'Login Data'))).toBe(true); + }); + test('a named profile lands in Default of the copy', async () => { + const src = await fakeChrome('chrome-b', 'Profile 3'); + const c = await copySession(src, { tmpRoot: tmp('copies-b'), profile: 'Profile 3' }); + expect(c.files).toContain('Profile 3/Cookies'); + expect(existsSync(join(c.dir, 'Default', 'Cookies'))).toBe(true); + c.cleanup(); + }); + test('an error removes the temporary profile before it is thrown', async () => { + const src = tmp('chrome-broken'); + mkdirSync(join(src, 'Default', 'Cookies'), { recursive: true }); // a folder where the file should be: the copy fails + const root = tmp('copies-c'); + await expect(copySession(src, { tmpRoot: root })).rejects.toThrow(); + expect(readdirSync(root)).toEqual([]); + await expect(copySession(tmp('chrome-empty'), { tmpRoot: root })).rejects.toThrow('no Chrome cookie store'); + expect(readdirSync(root)).toEqual([]); + }); + test('an unreadable cookie file is copied whole and the log says so (filtered: false)', async () => { + const src = tmp('chrome-notdb'); + writeFileSync(join(src, 'Local State'), '{}'); + mkdirSync(join(src, 'Default')); + writeFileSync(join(src, 'Default', 'Cookies'), 'not a database'); + const c = await copySession(src, { tmpRoot: tmp('copies-d') }); + expect(c.filtered).toBe(false); + c.cleanup(); + expect(await filterCookies(join(scratch, 'none.db')).catch(() => 'err')).toBe('err'); + }); +}); + +// ---- integration: real Google Chrome, throwaway profiles, a local fixture site ---- + +const CHROME = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +const hasChrome = process.platform === 'darwin' && existsSync(CHROME); +if (!hasChrome) console.warn('console-session integration test skipped: Google Chrome is not installed (or not macOS)'); + +describe.skipIf(!hasChrome)('copy mode with real Chrome (throwaway profile, local site)', () => { + test('a cookie set in the source profile is there in the copy; another host\'s is filtered out; the copy is deleted on close', async () => { + let chromium: any; + try { chromium = (await import('playwright')).chromium; } catch { console.warn('skipped: playwright not installed'); return; } + const server = Bun.serve({ hostname: '127.0.0.1', port: 0, fetch: req => { + const u = new URL(req.url); + if (u.pathname === '/set') return new Response('set', { headers: { 'set-cookie': 'sb_test=1; Max-Age=3600; Path=/' } }); + return new Response(`cookie: ${/sb_test=1/.test(req.headers.get('cookie') ?? '') ? 'yes' : 'no'}`); + } }); + const site = `http://127.0.0.1:${server.port}`, other = `http://localhost:${server.port}`; + const src = tmp('chrome-real'); + try { + const opts = { channel: 'chrome', headless: true, ignoreDefaultArgs: ['--use-mock-keychain', '--password-store=basic'] }; + const seed = await chromium.launchPersistentContext(src, opts); + const p0 = seed.pages()[0] ?? await seed.newPage(); + await p0.goto(`${site}/set`); await p0.goto(`${other}/set`); + await seed.close(); + const said: string[] = []; + const b = await openConsoleBrowser(join(import.meta.dir, '..'), { + store: 'apple', profileDir: tmp('own-profile'), say: m => said.push(m), chromeDir: src, hosts: ['127.0.0.1'], headless: true, platform: 'darwin', + }); + expect(b.mode).toBe('copy'); + expect(said.join('\n')).toContain('your Chrome sign-in'); + expect(said.join('\n')).not.toContain('sb_test'); + expect(b.tempDir && existsSync(b.tempDir)).toBe(true); + await b.page.goto(`${site}/check`); + expect(await b.page.textContent('body')).toBe('cookie: yes'); + await b.page.goto(`${other}/check`); + expect(await b.page.textContent('body')).toBe('cookie: no'); + await b.context.close(); + await b.closed; + expect(existsSync(b.tempDir!)).toBe(false); + } finally { server.stop(true); } + }, 60_000); +}); diff --git a/tests/fixtures/console/_common.js b/tests/fixtures/console/_common.js index 2d0d5d83..b4d54265 100644 --- a/tests/fixtures/console/_common.js +++ b/tests/fixtures/console/_common.js @@ -1,7 +1,17 @@ -// Shared by the console fixtures (modeled pages, not recorded): records every button click (the engine must never click -// one) and lets a test act as the owner (window.__next() shows the next step, like the owner pressing Next). +// Shared by the console fixtures (modeled pages, not recorded): records every click on a button, link, menu item or row +// (the engine must never click a save / submit / publish / create / next control) and lets a test act as the owner +// (window.__next() shows the next step, like the owner pressing Next). Navigation pages keep the log across pages in +// sessionStorage (window.__navClicks). window.__clicks = []; -document.addEventListener('click', e => { const b = e.target.closest('button'); if (b) window.__clicks.push(b.textContent.trim()); }, true); +const navLog = () => { try { return JSON.parse(sessionStorage.getItem('navClicks') || '[]'); } catch { return []; } }; +window.__navClicks = navLog; +document.addEventListener('click', e => { + const b = e.target.closest('button, a, [role="button"], [role="menuitem"], [role="link"], [role="row"], tr'); + if (!b) return; + const name = (b.getAttribute('aria-label') || b.textContent).trim().replace(/\s+/g, ' '); + if (b.matches('button')) window.__clicks.push(b.textContent.trim()); + try { sessionStorage.setItem('navClicks', JSON.stringify([...navLog(), name])); } catch { /* file: pages */ } +}, true); window.__step = 0; window.__next = () => { const steps = [...document.querySelectorAll('[data-step]')]; diff --git a/tests/fixtures/console/asc-app.html b/tests/fixtures/console/asc-app.html new file mode 100644 index 00000000..cbfcc5bd --- /dev/null +++ b/tests/fixtures/console/asc-app.html @@ -0,0 +1,9 @@ + + +Example Game - App Store Connect + +

Example Game

+ + + diff --git a/tests/fixtures/console/asc-apps-dup.html b/tests/fixtures/console/asc-apps-dup.html new file mode 100644 index 00000000..b630d73c --- /dev/null +++ b/tests/fixtures/console/asc-apps-dup.html @@ -0,0 +1,8 @@ + + +Apps - App Store Connect + +

Apps

+ + diff --git a/tests/fixtures/console/asc-apps-noplus.html b/tests/fixtures/console/asc-apps-noplus.html new file mode 100644 index 00000000..d2114f4d --- /dev/null +++ b/tests/fixtures/console/asc-apps-noplus.html @@ -0,0 +1,9 @@ + + +Apps - App Store Connect + +

Apps

+ + + diff --git a/tests/fixtures/console/asc-apps-tr.html b/tests/fixtures/console/asc-apps-tr.html new file mode 100644 index 00000000..1c05683b --- /dev/null +++ b/tests/fixtures/console/asc-apps-tr.html @@ -0,0 +1,22 @@ + + +Uygulamalar - App Store Connect + +

Uygulamalar

+ + + + + + diff --git a/tests/fixtures/console/asc-apps.html b/tests/fixtures/console/asc-apps.html new file mode 100644 index 00000000..1f436654 --- /dev/null +++ b/tests/fixtures/console/asc-apps.html @@ -0,0 +1,33 @@ + + +Apps - App Store Connect + +

Apps

+ + + + + + + diff --git a/tests/fixtures/console/play-app-content.html b/tests/fixtures/console/play-app-content.html new file mode 100644 index 00000000..d9da2a71 --- /dev/null +++ b/tests/fixtures/console/play-app-content.html @@ -0,0 +1,12 @@ + + +App content - Play Console + +

App content

+

Content rating

Receive ratings for your app from official rating authorities.

Start
+

Target audience and content

Let us know about the target age group of your app.

Manage
+

Ads

Let us know whether your app contains ads.

+ + diff --git a/tests/fixtures/console/play-apps.html b/tests/fixtures/console/play-apps.html new file mode 100644 index 00000000..f56c5899 --- /dev/null +++ b/tests/fixtures/console/play-apps.html @@ -0,0 +1,16 @@ + + +All apps - Play Console + +

All apps

+ + + + + + + +
AppPackage
Other Appcom.example.other
Example Gamecom.example.game
Example Game Procom.example.gamepro
+ diff --git a/tests/fixtures/console/play-dashboard.html b/tests/fixtures/console/play-dashboard.html new file mode 100644 index 00000000..e440786e --- /dev/null +++ b/tests/fixtures/console/play-dashboard.html @@ -0,0 +1,16 @@ + + +Dashboard - Play Console + +

Example Game

+ + +Start rollout to Production + +