console fill: no silent waits; an unknown page gets a debug dump and a bounded stop
A real `console fill apple-app-privacy` clicked Next onto a console page the engine did not recognise and logged nothing for 8 hours. - Step watchdog: after a click, or while the form is expected, no known page within --step-timeout seconds (default 30) -> "the page after "Next" is not a page storebound knows ... Buttons there: ...", a debug dump, and the manual steps. It keeps watching, but 20 min without progress closes the window and exits 1. - A heartbeat line every minute while waiting (also during sign-in); the final review wait is bounded (2 h) with a reminder every 10 min. - Debug dump (cli/console/debug.ts) in .storebound/console-debug/ <form>-<time>/: page.json (URL without query, headings, dialogs, every visible control with role and name), page.html (rebuilt from a clone: no scripts, values, hidden inputs or non-whitelisted attributes) and a small screenshot. Emails, phone numbers and the header / account area are replaced; cookies, storage and tokens are never read. --debug-dump writes one at every step for bug reports. - Guardrail tests: an unknown-page fixture (dump sanitized, bounded exit) and a scan of cli/console for while loops without a deadline and Playwright waits without a timeout (one waitForLoadState fixed). - Pitfall 14 (docs/pitfalls.md, store-pitfalls skill); the console-autofill skill says how to send a dump.
This commit is contained in:
parent
ece6644522
commit
81313b6fa4
9 changed files with 358 additions and 13 deletions
|
|
@ -140,7 +140,7 @@ export async function switchTeam(page: Page, name: string, listed: string[], ms:
|
||||||
const real = await accName(it.loc), role = await realRole(it.loc);
|
const real = await accName(it.loc), role = await realRole(it.loc);
|
||||||
if (!switchAllowed(real, role, listed)) { await closeMenu(page); return false; }
|
if (!switchAllowed(real, role, listed)) { await closeMenu(page); return false; }
|
||||||
await it.loc.click();
|
await it.loc.click();
|
||||||
await page.waitForLoadState('domcontentloaded').catch(() => { /* same page */ });
|
await page.waitForLoadState('domcontentloaded', { timeout: ms }).catch(() => { /* same page, or slow: read what is there */ });
|
||||||
await Bun.sleep(300);
|
await Bun.sleep(300);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
123
cli/console/debug.ts
Normal file
123
cli/console/debug.ts
Normal file
|
|
@ -0,0 +1,123 @@
|
||||||
|
// Diagnostics of a console page storebound does not recognise (`console fill`): what is on the page, written to
|
||||||
|
// .storebound/console-debug/<form>-<time>/ (gitignored) so a bug report can attach the real console structure.
|
||||||
|
// page.json URL (query and fragment dropped), title, headings, dialog titles, every visible button, link, radio,
|
||||||
|
// checkbox, switch, combobox and textbox as { role, name } (checked state for choices, never a value)
|
||||||
|
// page.html the DOM rebuilt from a clone: scripts, styles, frames, hidden inputs and every attribute outside a short
|
||||||
|
// list (id, class, role, aria-*, type, for, name, hidden, disabled, checked, href without its query) are
|
||||||
|
// dropped; input / textarea values and selected options are never written
|
||||||
|
// screen.jpg the visible part of the window, small (JPEG, quality 50)
|
||||||
|
// Personal data: emails, phone-like numbers and the texts of the page header / account menu (where the account name
|
||||||
|
// and the signed-in user show) are replaced; cookies, storage, tokens and request data are never read. The screenshot
|
||||||
|
// shows what the window shows: the owner looks at it before sending it.
|
||||||
|
import { mkdirSync, writeFileSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
|
||||||
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
|
type Page = any;
|
||||||
|
|
||||||
|
export interface PageSummary {
|
||||||
|
url: string;
|
||||||
|
title: string;
|
||||||
|
headings: string[];
|
||||||
|
dialogs: string[];
|
||||||
|
controls: { role: string; name: string; checked?: boolean }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const EMAIL = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi;
|
||||||
|
const PHONE = /\+?\d[\d\s().-]{7,}\d/g;
|
||||||
|
/** Emails and phone-like numbers out of a text (ids of 6+ digits without separators stay: they are app / account ids). */
|
||||||
|
export const scrub = (t: string): string => t.replace(EMAIL, '[email]').replace(PHONE, m => (/^\d+$/.test(m) ? m : '[number]'));
|
||||||
|
|
||||||
|
/** The URL without its query and fragment (they can carry tokens). */
|
||||||
|
export const bareUrl = (u: string): string => { try { const x = new URL(u); return `${x.origin}${x.pathname}`; } catch { return ''; } };
|
||||||
|
|
||||||
|
/** What the page shows, read in the page (labels only, never values). */
|
||||||
|
export async function summarize(page: Page): Promise<PageSummary> {
|
||||||
|
const r: Omit<PageSummary, 'url'> = await page.evaluate(() => {
|
||||||
|
const PRIVATE = 'header, [role="banner"], [aria-label*="account" i], [aria-label*="hesap" i]';
|
||||||
|
const shown = (el: Element) => !!(el as HTMLElement).getClientRects().length && getComputedStyle(el).visibility !== 'hidden';
|
||||||
|
const text = (el: Element | null) => (el?.textContent ?? '').trim().replace(/\s+/g, ' ').slice(0, 120);
|
||||||
|
const name = (el: Element): string => {
|
||||||
|
if (el.closest(PRIVATE)) return '[account area]';
|
||||||
|
const by = el.getAttribute('aria-labelledby');
|
||||||
|
const ref = by ? by.split(/\s+/).map(id => text(document.getElementById(id))).join(' ') : '';
|
||||||
|
const labels = (el as HTMLInputElement).labels ? [...(el as HTMLInputElement).labels!].map(l => text(l)).join(' ') : '';
|
||||||
|
return (el.getAttribute('aria-label') || ref || labels || el.getAttribute('title') || el.getAttribute('placeholder') || text(el)).trim().slice(0, 120);
|
||||||
|
};
|
||||||
|
const roleOf = (el: Element): string => {
|
||||||
|
const r = el.getAttribute('role');
|
||||||
|
if (r) return r;
|
||||||
|
const t = el.tagName.toLowerCase(), type = (el.getAttribute('type') ?? '').toLowerCase();
|
||||||
|
if (t === 'a') return 'link';
|
||||||
|
if (t === 'button' || (t === 'input' && ['button', 'submit', 'reset'].includes(type))) return 'button';
|
||||||
|
if (t === 'select') return 'combobox';
|
||||||
|
if (t === 'textarea') return 'textbox';
|
||||||
|
if (t === 'input') return type === 'radio' ? 'radio' : type === 'checkbox' ? 'checkbox' : type === 'hidden' ? '' : 'textbox';
|
||||||
|
return t;
|
||||||
|
};
|
||||||
|
const controls: { role: string; name: string; checked?: boolean }[] = [];
|
||||||
|
const sel = 'a[href], button, input, select, textarea, [role="button"], [role="link"], [role="radio"], [role="checkbox"], [role="switch"], [role="combobox"], [role="textbox"], [role="tab"], [role="menuitem"], [role="option"]';
|
||||||
|
for (const el of document.querySelectorAll(sel)) {
|
||||||
|
if (!shown(el)) continue;
|
||||||
|
const role = roleOf(el);
|
||||||
|
if (!role) continue;
|
||||||
|
const c: { role: string; name: string; checked?: boolean } = { role, name: name(el) };
|
||||||
|
if (['radio', 'checkbox', 'switch'].includes(role)) c.checked = (el as HTMLInputElement).checked ?? el.getAttribute('aria-checked') === 'true';
|
||||||
|
controls.push(c);
|
||||||
|
if (controls.length >= 400) break;
|
||||||
|
}
|
||||||
|
const headings = [...document.querySelectorAll('h1, h2, h3, h4, [role="heading"]')].filter(shown).map(h => text(h)).filter(Boolean).slice(0, 60);
|
||||||
|
const dialogs = [...document.querySelectorAll('[role="dialog"], dialog, [role="alertdialog"]')].filter(shown)
|
||||||
|
.map(d => d.getAttribute('aria-label') || text(d.querySelector('h1, h2, h3, [role="heading"]')) || '(untitled dialog)');
|
||||||
|
return { title: document.title.slice(0, 200), headings, dialogs, controls };
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
url: bareUrl(page.url()), title: scrub(r.title), headings: r.headings.map(scrub), dialogs: r.dialogs.map(scrub),
|
||||||
|
controls: r.controls.map(c => ({ ...c, name: scrub(c.name) })),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The page's DOM without scripts, values, tokens or personal texts (see the header). */
|
||||||
|
export async function sanitizedHtml(page: Page): Promise<string> {
|
||||||
|
const html: string = await page.evaluate(() => {
|
||||||
|
const KEEP = new Set(['id', 'class', 'role', 'type', 'for', 'name', 'hidden', 'disabled', 'checked', 'href', 'tabindex', 'title', 'alt', 'placeholder', 'data-step']);
|
||||||
|
const root = document.documentElement.cloneNode(true) as HTMLElement;
|
||||||
|
root.querySelectorAll('script, style, noscript, iframe, object, embed, template, link, meta, input[type="hidden"], svg, canvas, video, audio').forEach(e => e.remove());
|
||||||
|
root.querySelectorAll('header, [role="banner"], [aria-label*="account" i], [aria-label*="hesap" i]').forEach(e => { e.textContent = '[account area]'; });
|
||||||
|
for (const el of root.querySelectorAll('*')) {
|
||||||
|
for (const a of [...el.attributes]) {
|
||||||
|
if (!(KEEP.has(a.name) || a.name.startsWith('aria-'))) { el.removeAttribute(a.name); continue; }
|
||||||
|
if (a.name === 'href') { try { const u = new URL(a.value, location.href); el.setAttribute('href', `${u.origin}${u.pathname}`); } catch { el.removeAttribute('href'); } }
|
||||||
|
}
|
||||||
|
if (el.tagName === 'INPUT') el.removeAttribute('value');
|
||||||
|
if (el.tagName === 'TEXTAREA') el.textContent = '';
|
||||||
|
if (el.tagName === 'OPTION') el.removeAttribute('selected');
|
||||||
|
if (el.tagName === 'IMG') el.removeAttribute('src');
|
||||||
|
}
|
||||||
|
return `<!doctype html>\n${root.outerHTML}`;
|
||||||
|
});
|
||||||
|
return scrub(html);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A short name for a dump folder ("after-next", "page-3"). */
|
||||||
|
const slug = (s: string): string => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 40) || 'page';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Writes the dump of the page into `dir/<nn>-<label>/` (page.json, page.html, screen.jpg) and returns that folder and
|
||||||
|
* the summary. Never throws: a part that fails is left out (a note in page.json says which).
|
||||||
|
*/
|
||||||
|
export async function dumpPage(page: Page, dir: string, n: number, label: string): Promise<{ dir: string; summary: PageSummary | null }> {
|
||||||
|
const out = join(dir, `${String(n).padStart(2, '0')}-${slug(label)}`);
|
||||||
|
mkdirSync(out, { recursive: true });
|
||||||
|
const failed: string[] = [];
|
||||||
|
let summary: PageSummary | null = null;
|
||||||
|
try { summary = await summarize(page); } catch (e) { failed.push(`summary: ${(e as Error).message.split('\n')[0]}`); }
|
||||||
|
try { writeFileSync(join(out, 'page.html'), await sanitizedHtml(page)); } catch (e) { failed.push(`html: ${(e as Error).message.split('\n')[0]}`); }
|
||||||
|
try { await page.screenshot({ path: join(out, 'screen.jpg'), type: 'jpeg', quality: 50, scale: 'css', timeout: 10_000 }); } catch (e) { failed.push(`screenshot: ${(e as Error).message.split('\n')[0]}`); }
|
||||||
|
writeFileSync(join(out, 'page.json'), `${JSON.stringify({ label, at: new Date().toISOString(), ...(summary ?? {}), ...(failed.length ? { failed } : {}) }, null, 1)}\n`);
|
||||||
|
return { dir: out, summary };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The first `n` distinct button / link names of a summary, for the log. */
|
||||||
|
export const topButtons = (s: PageSummary | null, n = 10): string[] =>
|
||||||
|
[...new Set((s?.controls ?? []).filter(c => c.role === 'button' || c.role === 'link').map(c => c.name).filter(x => x && x !== '[account area]'))].slice(0, n);
|
||||||
|
|
@ -320,12 +320,13 @@ export async function flowWhere(loc: Locator, dataTypes: string[]): Promise<Flow
|
||||||
* The flow click gate (flowAllowed): a navigation control of the form, or App Privacy's in-dialog Save (a draft, public
|
* The flow click gate (flowAllowed): a navigation control of the form, or App Privacy's in-dialog Save (a draft, public
|
||||||
* only after the owner's Publish). Reads the real name, role and place of the control; logs the click.
|
* only after the owner's Publish). Reads the real name, role and place of the control; logs the click.
|
||||||
*/
|
*/
|
||||||
export async function flowClick(loc: Locator, form: FormId, dataTypes: string[], say: (m: string) => void): Promise<boolean> {
|
export async function flowClick(loc: Locator, form: FormId, dataTypes: string[], say: (m: string) => void, onClick?: (name: string) => void): Promise<boolean> {
|
||||||
const name = await accName(loc), role = await realRole(loc);
|
const name = await accName(loc), role = await realRole(loc);
|
||||||
const where = await flowWhere(loc, dataTypes);
|
const where = await flowWhere(loc, dataTypes);
|
||||||
if (!flowAllowed(form, name, role, where)) { warn(TAG, `not clicking "${name}": only the owner presses it`); return false; }
|
if (!flowAllowed(form, name, role, where)) { warn(TAG, `not clicking "${name}": only the owner presses it`); return false; }
|
||||||
await loc.click();
|
await loc.click();
|
||||||
say(`clicked "${name}" (${flowClass(form, name, role, where)})`);
|
say(`clicked "${name}" (${flowClass(form, name, role, where)})`);
|
||||||
|
onClick?.(name);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -573,7 +574,7 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
if (!form) {
|
if (!form) {
|
||||||
const forms = FORM_IDS.map(id => { const m = formMeta(id, config); return { id, store: m.store, title: m.title, fillable: m.fillable }; });
|
const forms = FORM_IDS.map(id => { const m = formMeta(id, config); return { id, store: m.store, title: m.title, fillable: m.fillable }; });
|
||||||
if (json) return printJson({ forms });
|
if (json) return printJson({ forms });
|
||||||
console.log('storebound console fill <form> [--store apple|play] [--dry] [--json] [--profile <dir>]\n');
|
console.log('storebound console fill <form> [--store apple|play] [--dry] [--json] [--profile <dir>] [--step-timeout <seconds>] [--debug-dump]\n');
|
||||||
for (const f of forms) console.log(` ${f.id.padEnd(22)} ${f.store.padEnd(6)} ${f.title}${f.fillable ? '' : ' (guide only)'}`);
|
for (const f of forms) console.log(` ${f.id.padEnd(22)} ${f.store.padEnd(6)} ${f.title}${f.fillable ? '' : ' (guide only)'}`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
@ -606,7 +607,15 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
try {
|
try {
|
||||||
// App Privacy opens by deep link when the app id is known (config, cache or the API by bundle id), else by the list
|
// App Privacy opens by deep link when the app id is known (config, cache or the API by bundle id), else by the list
|
||||||
const cfg = form === 'apple-app-privacy' && !startUrl ? withAppleAppId(config, await appleAppId(root, config, { say })) : config;
|
const cfg = form === 'apple-app-privacy' && !startUrl ? withAppleAppId(config, await appleAppId(root, config, { say })) : config;
|
||||||
const out = await fillSession(b, { form, config: cfg, say, ...(startUrl ? { startUrl } : {}) });
|
const step = args.get('step-timeout');
|
||||||
|
if (step !== undefined && !(Number(step) > 0)) throw new Error('--step-timeout: seconds (a number above 0)');
|
||||||
|
const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\..*$/, '').replace('T', '-');
|
||||||
|
const out = await fillSession(b, {
|
||||||
|
form, config: cfg, say, ...(startUrl ? { startUrl } : {}), ...(step !== undefined ? { stepTimeoutMs: Number(step) * 1000 } : {}),
|
||||||
|
debugDir: join(root, '.storebound', 'console-debug', `${form}-${stamp}`), debugEveryStep: args.has('debug-dump'),
|
||||||
|
});
|
||||||
|
if (out.debugDir) say(`debug dump: ${out.debugDir} (page.json, page.html, screen.jpg per step; no values, cookies or tokens; look at screen.jpg before you attach it to a bug report)`);
|
||||||
|
if (out.timedOut) process.exitCode = 1;
|
||||||
if (json) printJson({ ...res, ...out, stoppedAt: meta.stopBefore, browser: b.mode });
|
if (json) printJson({ ...res, ...out, stoppedAt: meta.stopBefore, browser: b.mode });
|
||||||
} finally { b.cleanup(); process.off('SIGINT', bye); process.off('SIGTERM', bye); }
|
} finally { b.cleanup(); process.off('SIGINT', bye); process.off('SIGTERM', bye); }
|
||||||
}
|
}
|
||||||
|
|
@ -626,8 +635,23 @@ export interface FillSessionOpts {
|
||||||
/** Tests only: the account cache file (default ~/.storebound/console-accounts.json) and the env ids are read from. */
|
/** Tests only: the account cache file (default ~/.storebound/console-accounts.json) and the env ids are read from. */
|
||||||
accountsFile?: string;
|
accountsFile?: string;
|
||||||
env?: Record<string, string | undefined>;
|
env?: Record<string, string | undefined>;
|
||||||
|
/** Watchdog (see fillSession): no known page within stepTimeoutMs after a click or while the form is expected -> a
|
||||||
|
* diagnostic dump and the manual steps; no progress at all for idleLimitMs -> the run stops (timedOut). A line every
|
||||||
|
* heartbeatMs while waiting; the owner's final review is waited for at most finalWaitMs. */
|
||||||
|
stepTimeoutMs?: number;
|
||||||
|
idleLimitMs?: number;
|
||||||
|
heartbeatMs?: number;
|
||||||
|
finalWaitMs?: number;
|
||||||
|
/** Where diagnostics go (.storebound/console-debug/<form>-<time>); none: no files, the log still says what is there. */
|
||||||
|
debugDir?: string;
|
||||||
|
/** --debug-dump: a dump at every step (the form open, every filled page, every click), not only on a stall. */
|
||||||
|
debugEveryStep?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Watchdog defaults: 30 s for a page to show up, 20 min without any progress, a line a minute, 2 h for the review. */
|
||||||
|
export const WATCH = { stepMs: 30_000, idleMs: 20 * 60_000, heartbeatMs: 60_000, finalMs: 2 * 3600_000 };
|
||||||
|
const mins = (ms: number): string => (ms < 60_000 ? `${Math.round(ms / 1000)} s` : `${Math.floor(ms / 60_000)} min ${Math.round((ms % 60_000) / 1000)} s`);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* One fill run in an open browser, until the owner closes the window:
|
* One fill run in an open browser, until the owner closes the window:
|
||||||
* 1. sign-in: while a sign-in page shows (signInPage), the owner signs in and storebound waits (up to 10 minutes; it
|
* 1. sign-in: while a sign-in page shows (signInPage), the owner signs in and storebound waits (up to 10 minutes; it
|
||||||
|
|
@ -640,9 +664,20 @@ export interface FillSessionOpts {
|
||||||
* data type, and the draft Save of its dialogs). An uncertain answer stops it on that page until the owner set it.
|
* data type, and the draft Save of its dialogs). An uncertain answer stops it on that page until the owner set it.
|
||||||
* The final button (Publish, Submit, Save, Create) and agreements stay the owner's.
|
* The final button (Publish, Submit, Save, Create) and agreements stay the owner's.
|
||||||
*/
|
*/
|
||||||
export async function fillSession(b: ConsoleBrowser, o: FillSessionOpts): Promise<{ filled: number; highlighted: number; fallback: boolean }> {
|
export async function fillSession(b: ConsoleBrowser, o: FillSessionOpts): Promise<{ filled: number; highlighted: number; fallback: boolean; timedOut?: boolean; debugDir?: string }> {
|
||||||
const { form, config, say, startUrl } = o;
|
const { form, config, say, startUrl } = o;
|
||||||
const tick = o.tickMs ?? 1000, navMs = o.navTimeoutMs ?? 20_000, signInMs = o.signInWaitMs ?? 10 * 60_000;
|
const tick = o.tickMs ?? 1000, navMs = o.navTimeoutMs ?? 20_000, signInMs = o.signInWaitMs ?? 10 * 60_000;
|
||||||
|
const stepMs = o.stepTimeoutMs ?? WATCH.stepMs, idleMs = o.idleLimitMs ?? WATCH.idleMs, heartbeatMs = o.heartbeatMs ?? WATCH.heartbeatMs, finalMs = o.finalWaitMs ?? WATCH.finalMs;
|
||||||
|
// ---- the watchdog: what storebound expects next, since when; a dump of the page when it does not come ----
|
||||||
|
let expecting = 'the form', progressAt = Date.now(), lastBeat = Date.now(), stalled = false, dumps = 0, timedOut = false;
|
||||||
|
const dump = async (p: Page, label: string) => {
|
||||||
|
if (!o.debugDir) return null;
|
||||||
|
const { dumpPage } = await import('./debug');
|
||||||
|
return dumpPage(p, o.debugDir, ++dumps, label);
|
||||||
|
};
|
||||||
|
/** Something storebound knows happened; `next`: what it waits for now. */
|
||||||
|
const progress = (next: string) => { progressAt = Date.now(); lastBeat = progressAt; expecting = next; stalled = false; };
|
||||||
|
const clicked = (name: string) => { progress(`the page after "${name}"`); if (o.debugEveryStep) { const p = active(); if (p) void Bun.sleep(tick).then(() => dump(p, `after ${name}`)).catch(() => { /* gone */ }); } };
|
||||||
const meta = formMeta(form, config), res = consoleResult(form, config);
|
const meta = formMeta(form, config), res = consoleResult(form, config);
|
||||||
const active = (): Page | undefined => b.pages().at(-1);
|
const active = (): Page | undefined => b.pages().at(-1);
|
||||||
const isSignIn = (p: Page) => signInPage(p).catch(() => false);
|
const isSignIn = (p: Page) => signInPage(p).catch(() => false);
|
||||||
|
|
@ -660,8 +695,10 @@ export async function fillSession(b: ConsoleBrowser, o: FillSessionOpts): Promis
|
||||||
/** Waits until the console is open and no sign-in page shows (two rounds in a row). false: window closed or time up. */
|
/** Waits until the console is open and no sign-in page shows (two rounds in a row). false: window closed or time up. */
|
||||||
async function signedIn(): Promise<boolean> {
|
async function signedIn(): Promise<boolean> {
|
||||||
const end = Date.now() + signInMs;
|
const end = Date.now() + signInMs;
|
||||||
let told = false, ok = 0;
|
let told = false, ok = 0, beat = Date.now();
|
||||||
|
const start = Date.now();
|
||||||
while (!b.isClosed() && Date.now() < end) {
|
while (!b.isClosed() && Date.now() < end) {
|
||||||
|
if (Date.now() - beat >= heartbeatMs) { beat = Date.now(); say(`still waiting for the sign-in, ${mins(Date.now() - start)}`); }
|
||||||
const p = active();
|
const p = active();
|
||||||
if (p && await isSignIn(p)) { ok = 0; if (!told) { signInHint(); told = true; } }
|
if (p && await isSignIn(p)) { ok = 0; if (!told) { signInHint(); told = true; } }
|
||||||
else if (p && reached(p)) { if (++ok >= 2) { if (told) say('signed in'); return true; } }
|
else if (p && reached(p)) { if (++ok >= 2) { if (told) say('signed in'); return true; } }
|
||||||
|
|
@ -719,6 +756,8 @@ export async function fillSession(b: ConsoleBrowser, o: FillSessionOpts): Promis
|
||||||
let nav: NavResult | null = plan.length && !b.isClosed() ? await openForm(0) : null;
|
let nav: NavResult | null = plan.length && !b.isClosed() ? await openForm(0) : null;
|
||||||
if (nav) report(nav, true);
|
if (nav) report(nav, true);
|
||||||
else for (const s of meta.open) say(`open the form: ${s}`);
|
else for (const s of meta.open) say(`open the form: ${s}`);
|
||||||
|
progress(nav?.ok ? 'the form' : 'the form (opened by you)');
|
||||||
|
if (o.debugEveryStep && !b.isClosed()) await dump(active() ?? b.page, 'start');
|
||||||
|
|
||||||
const last = def.sections.length - 1;
|
const last = def.sections.length - 1;
|
||||||
const privacy = form === 'apple-app-privacy';
|
const privacy = form === 'apple-app-privacy';
|
||||||
|
|
@ -757,14 +796,14 @@ export async function fillSession(b: ConsoleBrowser, o: FillSessionOpts): Promis
|
||||||
if (form === 'play-content-rating' && filledAt !== null && !drafted.has(filledAt)) {
|
if (form === 'play-content-rating' && filledAt !== null && !drafted.has(filledAt)) {
|
||||||
drafted.add(filledAt);
|
drafted.add(filledAt);
|
||||||
const draft = await controlWhere(p, FLOW_NAMES.saveDraft, () => true, dataTypes);
|
const draft = await controlWhere(p, FLOW_NAMES.saveDraft, () => true, dataTypes);
|
||||||
if (draft && await flowClick(draft, form, dataTypes, say)) return 'draft';
|
if (draft && await flowClick(draft, form, dataTypes, say, clicked)) return 'draft';
|
||||||
}
|
}
|
||||||
const next = await nextControl(p);
|
const next = await nextControl(p);
|
||||||
if (next) return flowClick(next, form, dataTypes, say);
|
if (next) return flowClick(next, form, dataTypes, say, clicked);
|
||||||
const d = privacy ? await anchorDialog() : null;
|
const d = privacy ? await anchorDialog() : null;
|
||||||
if (!d) return false;
|
if (!d) return false;
|
||||||
const save = await controlWhere(d, FLOW_NAMES.save, w => w.inDialog && w.privacyPage, dataTypes);
|
const save = await controlWhere(d, FLOW_NAMES.save, w => w.inDialog && w.privacyPage, dataTypes);
|
||||||
return save ? flowClick(save, form, dataTypes, say) : false;
|
return save ? flowClick(save, form, dataTypes, say, clicked) : false;
|
||||||
}
|
}
|
||||||
/** App Privacy with no dialog open: opens the next part (Get Started, Edit next to Data Types, the next data type). */
|
/** App Privacy with no dialog open: opens the next part (Get Started, Edit next to Data Types, the next data type). */
|
||||||
async function privacyStep(p: Page): Promise<void> {
|
async function privacyStep(p: Page): Promise<void> {
|
||||||
|
|
@ -776,7 +815,7 @@ export async function fillSession(b: ConsoleBrowser, o: FillSessionOpts): Promis
|
||||||
if (n === 2) { opened.set(key, 3); warn(TAG, `${what} did not open after two clicks: the console UI may have changed. Open it yourself; storebound fills it when it appears`); }
|
if (n === 2) { opened.set(key, 3); warn(TAG, `${what} did not open after two clicks: the console UI may have changed. Open it yourself; storebound fills it when it appears`); }
|
||||||
if (n >= 2) return;
|
if (n >= 2) return;
|
||||||
opened.set(key, n + 1);
|
opened.set(key, n + 1);
|
||||||
await flowClick(loc, form, dataTypes, say);
|
await flowClick(loc, form, dataTypes, say, clicked);
|
||||||
};
|
};
|
||||||
const editTypes = () => controlWhere(p, FLOW_NAMES.edit, w => w.inDataTypes && !w.inDialog, dataTypes);
|
const editTypes = () => controlWhere(p, FLOW_NAMES.edit, w => w.inDataTypes && !w.inDialog, dataTypes);
|
||||||
if (!done.has(0)) {
|
if (!done.has(0)) {
|
||||||
|
|
@ -799,9 +838,30 @@ export async function fillSession(b: ConsoleBrowser, o: FillSessionOpts): Promis
|
||||||
if (t) return open(`type:${t}`, t, await controlWhere(p, [t, `Set Up ${t}`, `${t} ayarla`], w => w.inDataTypes && !w.inDialog, dataTypes));
|
if (t) return open(`type:${t}`, t, await controlWhere(p, [t, `Set Up ${t}`, `${t} ayarla`], w => w.inDataTypes && !w.inDialog, dataTypes));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A page storebound does not know: what is there (top buttons), the dump, and the manual steps. Once per wait. */
|
||||||
|
const stall = async (p: Page) => {
|
||||||
|
stalled = true;
|
||||||
|
const dbg = await import('./debug');
|
||||||
|
const d = await dump(p, `unknown ${expecting}`).catch(() => null);
|
||||||
|
const top = dbg.topButtons(d?.summary ?? await dbg.summarize(p).catch(() => null));
|
||||||
|
say(`${expecting} is not a page storebound knows (nothing it can fill or click after ${mins(Date.now() - progressAt)}). Buttons there: ${top.length ? top.map(t => `"${t}"`).join(', ') : '(none)'}${d ? `. Debug saved to ${d.dir}` : ''}`);
|
||||||
|
say(`do this part yourself; storebound keeps watching and goes on when it sees a page it knows (it stops after ${mins(idleMs)} without progress):`);
|
||||||
|
for (const g of res.guidance) say(` ${g}`);
|
||||||
|
};
|
||||||
|
/** Every round: a heartbeat line, the step watchdog (not while the owner answers or signs in), the idle limit. */
|
||||||
|
const watch = async (p: Page | undefined): Promise<boolean> => {
|
||||||
|
const now = Date.now();
|
||||||
|
const owner = waitFor ? `your answer on "${waitFor.title}"` : signedOut ? 'the sign-in' : null;
|
||||||
|
if (now - lastBeat >= heartbeatMs) { lastBeat = now; say(`still waiting for ${owner ?? expecting}, ${mins(now - progressAt)}`); }
|
||||||
|
if (p && !owner && !stalled && now - progressAt >= stepMs) await stall(p);
|
||||||
|
if (now - progressAt >= idleMs) { timedOut = true; return false; }
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
let signedOut = false, misses = 0, firstMiss = 0;
|
let signedOut = false, misses = 0, firstMiss = 0;
|
||||||
while (!b.isClosed() && !finished()) {
|
while (!b.isClosed() && !finished()) {
|
||||||
const p = active();
|
const p = active();
|
||||||
|
if (!await watch(p)) break;
|
||||||
if (!p) { await Bun.sleep(tick); continue; }
|
if (!p) { await Bun.sleep(tick); continue; }
|
||||||
if (await signInPage(p).catch(() => true)) {
|
if (await signInPage(p).catch(() => true)) {
|
||||||
if (!signedOut && plan.length) signInHint();
|
if (!signedOut && plan.length) signInHint();
|
||||||
|
|
@ -825,6 +885,7 @@ export async function fillSession(b: ConsoleBrowser, o: FillSessionOpts): Promis
|
||||||
tried = key;
|
tried = key;
|
||||||
say(`the page changed: storebound opens the form from step ${at + 1}/${plan.length}`);
|
say(`the page changed: storebound opens the form from step ${at + 1}/${plan.length}`);
|
||||||
nav = await openForm(at); report(nav, false);
|
nav = await openForm(at); report(nav, false);
|
||||||
|
progress(nav.ok ? 'the form' : 'the form (opened by you)');
|
||||||
if (nav.ok) say('the form is open');
|
if (nav.ok) say('the form is open');
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
@ -845,6 +906,8 @@ export async function fillSession(b: ConsoleBrowser, o: FillSessionOpts): Promis
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
filled += s.filled.length; highlighted += s.highlighted.length;
|
filled += s.filled.length; highlighted += s.highlighted.length;
|
||||||
|
progress(`the next part after "${s.title}"`);
|
||||||
|
if (o.debugEveryStep) await dump(p, `filled ${s.title}`);
|
||||||
say(`${s.title}: filled ${s.filled.length}, check ${s.highlighted.length}${s.highlighted.length ? `: ${s.highlighted.map(id => labels.get(id) ?? id).join('; ')}` : ''}`);
|
say(`${s.title}: filled ${s.filled.length}, check ${s.highlighted.length}${s.highlighted.length ? `: ${s.highlighted.map(id => labels.get(id) ?? id).join('; ')}` : ''}`);
|
||||||
anchor = s.anchor; filledAt = s.section;
|
anchor = s.anchor; filledAt = s.section;
|
||||||
// the last page of a Play / App Store form without a Next ends the run: its button is the owner's (Save, Submit, Create)
|
// the last page of a Play / App Store form without a Next ends the run: its button is the owner's (Save, Submit, Create)
|
||||||
|
|
@ -861,6 +924,7 @@ export async function fillSession(b: ConsoleBrowser, o: FillSessionOpts): Promis
|
||||||
if (waitFor) {
|
if (waitFor) {
|
||||||
if (!await answered(waitFor.pending)) { await Bun.sleep(tick); continue; }
|
if (!await answered(waitFor.pending)) { await Bun.sleep(tick); continue; }
|
||||||
say(`"${waitFor.title}" answered: storebound goes on`);
|
say(`"${waitFor.title}" answered: storebound goes on`);
|
||||||
|
progress(`the next part after "${waitFor.title}"`);
|
||||||
waitFor = null;
|
waitFor = null;
|
||||||
}
|
}
|
||||||
if (pendingAdvance) {
|
if (pendingAdvance) {
|
||||||
|
|
@ -872,10 +936,22 @@ export async function fillSession(b: ConsoleBrowser, o: FillSessionOpts): Promis
|
||||||
if (privacy) await privacyStep(p).catch(() => { /* navigating */ });
|
if (privacy) await privacyStep(p).catch(() => { /* navigating */ });
|
||||||
await Bun.sleep(tick);
|
await Bun.sleep(tick);
|
||||||
}
|
}
|
||||||
|
if (timedOut) {
|
||||||
|
say(`nothing storebound knows happened for ${mins(idleMs)}: it stops here and closes the window${o.debugDir && dumps ? ` (debug: ${o.debugDir})` : ''}. Answers saved as drafts stay; run it again when the page is fixed.`);
|
||||||
|
await b.close();
|
||||||
|
return { filled, highlighted, fallback, timedOut: true, ...(o.debugDir && dumps ? { debugDir: o.debugDir } : {}) };
|
||||||
|
}
|
||||||
if (!b.isClosed() && !fallback) say(privacy
|
if (!b.isClosed() && !fallback) say(privacy
|
||||||
? 'review the summary, then press Publish yourself. storebound saved the answers as a draft (Save in each dialog); nothing is public until you press Publish. Close the window when done.'
|
? 'review the summary, then press Publish yourself. storebound saved the answers as a draft (Save in each dialog); nothing is public until you press Publish. Close the window when done.'
|
||||||
: `review every field and press ${meta.stopBefore} yourself. storebound never saves, submits or publishes. Close the window when done.`);
|
: `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');
|
else if (!b.isClosed()) say('close the browser window when done');
|
||||||
|
// the owner reviews and presses the final button, then closes the window: a reminder every 10 heartbeats, at most finalMs
|
||||||
|
const end = Date.now() + finalMs;
|
||||||
|
while (!b.isClosed() && Date.now() < end) {
|
||||||
|
await Promise.race([b.closed, Bun.sleep(Math.min(10 * heartbeatMs, Math.max(0, end - Date.now())))]);
|
||||||
|
if (!b.isClosed() && Date.now() < end) say('still open: storebound waits for you to review, press the final button and close the window');
|
||||||
|
}
|
||||||
|
if (!b.isClosed()) { say(`the window has been open for ${mins(finalMs)} after the fill: storebound closes it now`); await b.close(); }
|
||||||
await b.closed;
|
await b.closed;
|
||||||
return { filled, highlighted, fallback };
|
return { filled, highlighted, fallback, ...(o.debugDir && dumps ? { debugDir: o.debugDir } : {}) };
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -286,9 +286,11 @@
|
||||||
"console fill": [
|
"console fill": [
|
||||||
"cdp",
|
"cdp",
|
||||||
"chrome-profile",
|
"chrome-profile",
|
||||||
|
"debug-dump",
|
||||||
"fresh-profile",
|
"fresh-profile",
|
||||||
"profile",
|
"profile",
|
||||||
"start-url",
|
"start-url",
|
||||||
|
"step-timeout",
|
||||||
"store"
|
"store"
|
||||||
],
|
],
|
||||||
"desktop": [
|
"desktop": [
|
||||||
|
|
@ -666,6 +668,7 @@
|
||||||
"daily",
|
"daily",
|
||||||
"date",
|
"date",
|
||||||
"days",
|
"days",
|
||||||
|
"debug-dump",
|
||||||
"declarations",
|
"declarations",
|
||||||
"delay",
|
"delay",
|
||||||
"detail",
|
"detail",
|
||||||
|
|
@ -779,6 +782,7 @@
|
||||||
"state",
|
"state",
|
||||||
"status",
|
"status",
|
||||||
"stdio",
|
"stdio",
|
||||||
|
"step-timeout",
|
||||||
"store",
|
"store",
|
||||||
"storefront",
|
"storefront",
|
||||||
"storefronts",
|
"storefronts",
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,7 @@ fails without the fix.
|
||||||
|
|
||||||
| # | date | lesson | guard |
|
| # | date | lesson | guard |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
|
| 14 | 2026-10 | `console fill apple-app-privacy` clicked Next onto a real console page it did not recognise and then waited 8 hours without a single log line. | Every wait of the console engine is bounded: a step watchdog (`--step-timeout`, 30 s) writes a sanitized debug dump to `.storebound/console-debug/` and prints the page's buttons and the manual steps; a line a minute while waiting; no progress for 20 min stops the run with exit 1; `--debug-dump` dumps every step (`cli/console/debug.ts`, `tests/console-flow.test.ts`, which also scans the engine for waits without a deadline). |
|
||||||
| 13 | 2026-10 | App Privacy purposes were over-mapped: Play "advertising" became both Third-Party Advertising and Developer's Advertising or Marketing (Device ID, Coarse Location, Product Interaction, Performance Data). | `applePurpose` maps one Play purpose to one Apple purpose (advertising: third-party only); Developer's Advertising only from `appPrivacy.types`; `check` compares `appPrivacy.types` with Info.plist / PrivacyInfo.xcprivacy (`tests/app-privacy.test.ts`). |
|
| 13 | 2026-10 | App Privacy purposes were over-mapped: Play "advertising" became both Third-Party Advertising and Developer's Advertising or Marketing (Device ID, Coarse Location, Product Interaction, Performance Data). | `applePurpose` maps one Play purpose to one Apple purpose (advertising: third-party only); Developer's Advertising only from `appPrivacy.types`; `check` compares `appPrivacy.types` with Info.plist / PrivacyInfo.xcprivacy (`tests/app-privacy.test.ts`). |
|
||||||
| 12 | 2026-10 | A new Play app has no API: Play Console's "Create app" is the only way, its page-level button carries the same words as the form's final submit, and Free cannot become Paid later. | `console fill play-app-record`: `createAppAllowed` lets the opener through only on the app list, never in a form or dialog (EN + TR); declarations never ticked; Free / Paid outlined as an owner check (`tests/console-fill.test.ts`). |
|
| 12 | 2026-10 | A new Play app has no API: Play Console's "Create app" is the only way, its page-level button carries the same words as the form's final submit, and Free cannot become Paid later. | `console fill play-app-record`: `createAppAllowed` lets the opener through only on the app list, never in a form or dialog (EN + TR); declarations never ticked; Free / Paid outlined as an owner check (`tests/console-fill.test.ts`). |
|
||||||
| 11 | 2026-10 | Google Play has no public search API, so there is no Play keyword rank or Play competitor list to read without scraping. | `aso` reads App Store search only (iTunes Search API); `aso audit` covers Play through the listing text (short description, density); the aso-basics skill says so. |
|
| 11 | 2026-10 | Google Play has no public search API, so there is no Play keyword rank or Play competitor list to read without scraping. | `aso` reads App Store search only (iTunes Search API); `aso audit` covers Play through the listing text (short description, density); the aso-basics skill says so. |
|
||||||
|
|
|
||||||
|
|
@ -113,7 +113,14 @@ It is not available over MCP.
|
||||||
(App Privacy: "review the summary, then press Publish yourself"). The
|
(App Privacy: "review the summary, then press Publish yourself"). The
|
||||||
command ends when the owner closes the window (`--json` then prints the result with `filled`, `highlighted`,
|
command ends when the owner closes the window (`--json` then prints the result with `filled`, `highlighted`,
|
||||||
`fallback`, `stoppedAt`).
|
`fallback`, `stoppedAt`).
|
||||||
8. If a field cannot be found or matches twice (for more than a moment: a page that is still loading does not count), the console UI changed: storebound stops filling and prints the
|
8. Nothing waits silently. While storebound waits it logs `still waiting for <what>, <time>` once a minute. When the
|
||||||
|
page after a click (or the form) is not one it knows within `--step-timeout` seconds (default 30), it says so with
|
||||||
|
the page's buttons, writes a debug dump to `.storebound/console-debug/<form>-<time>/` (page.json: headings, dialogs,
|
||||||
|
every visible control with role and name; page.html: the sanitized structure; screen.jpg) and prints the manual
|
||||||
|
steps. After 20 minutes without progress it closes the window and exits 1. `--debug-dump` writes a dump at every
|
||||||
|
step: attach that folder to a bug report after looking at screen.jpg (labels only; no values, cookies or tokens;
|
||||||
|
emails, phone numbers and the account area are replaced).
|
||||||
|
9. If a field cannot be found or matches twice (for more than a moment: a page that is still loading does not count), the console UI changed: storebound stops filling and prints the
|
||||||
step-by-step list ("label: answer") for the owner to copy. That is the expected safe behavior, not an error.
|
step-by-step list ("label: answer") for the owner to copy. That is the expected safe behavior, not an error.
|
||||||
|
|
||||||
## Play Create app (`play-app-record`)
|
## Play Create app (`play-app-record`)
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
---
|
---
|
||||||
name: store-pitfalls
|
name: store-pitfalls
|
||||||
description: Known pitfalls with App Store Connect, Google Play and storebound itself, learned from real releases, and what to do about each - store lists that lag right after a create, dry runs that print a count instead of a plan, App Store names taken on a storefront, keyword limits in bytes, Data safety answers without code evidence, missing font glyphs in screenshots, console sign-in and sessions, Capacitor monorepo plugins, duplicates from retries, re-runs and parallel runs, App Store search ranks that are only a trend, Play without a search API, Play's Create app form (no API, opener and submit share a name, Free is final), App Privacy purposes over-mapped (Play advertising is Third-Party Advertising only). Read it before any store task, and when a store command does something you did not expect.
|
description: Known pitfalls with App Store Connect, Google Play and storebound itself, learned from real releases, and what to do about each - store lists that lag right after a create, dry runs that print a count instead of a plan, App Store names taken on a storefront, keyword limits in bytes, Data safety answers without code evidence, missing font glyphs in screenshots, console sign-in and sessions, Capacitor monorepo plugins, duplicates from retries, re-runs and parallel runs, App Store search ranks that are only a trend, Play without a search API, Play's Create app form (no API, opener and submit share a name, Free is final), App Privacy purposes over-mapped (Play advertising is Third-Party Advertising only), an unknown console page (bounded wait and a debug dump). Read it before any store task, and when a store command does something you did not expect.
|
||||||
---
|
---
|
||||||
|
|
||||||
# Store pitfalls
|
# Store pitfalls
|
||||||
|
|
@ -122,6 +122,19 @@ Each entry: **symptom** → cause → what to do → what guards it now. The ful
|
||||||
- **Guard:** `applePurpose` (cli/lib/declarations.ts), `appPrivacy.types` validation and `appPrivacyMismatches`
|
- **Guard:** `applePurpose` (cli/lib/declarations.ts), `appPrivacy.types` validation and `appPrivacyMismatches`
|
||||||
(cli/lib/app-privacy.ts), `tests/app-privacy.test.ts`.
|
(cli/lib/app-privacy.ts), `tests/app-privacy.test.ts`.
|
||||||
|
|
||||||
|
## 14. An unknown console page: bounded wait and a debug dump
|
||||||
|
- **Symptom:** `console fill` clicked Next (or opened the form) and then nothing happened in the log for a long time.
|
||||||
|
- **Cause:** the console showed a page storebound does not recognise (a changed layout, a new question): no field it
|
||||||
|
can fill and no button it may click.
|
||||||
|
- **Do:** read the warning: it names the page ("the page after "Next""), its buttons, and where the debug dump is.
|
||||||
|
Do that part by hand (the manual steps follow), or stop. To report it, re-run with `--debug-dump` and attach the
|
||||||
|
folder `.storebound/console-debug/<form>-<time>/` after the owner looked at `screen.jpg` (the screenshot shows what
|
||||||
|
the window showed). `page.json` / `page.html` hold labels and structure only: no values, cookies or tokens; emails,
|
||||||
|
phone numbers and the account area are replaced.
|
||||||
|
- **Guard:** the watchdog in `fillSession` (`--step-timeout`, default 30 s; a heartbeat line a minute; 20 min without
|
||||||
|
progress ends the run with exit 1), `cli/console/debug.ts`, `tests/console-flow.test.ts` (unknown-page fixture and a
|
||||||
|
scan for waits without a deadline).
|
||||||
|
|
||||||
## Adding a lesson
|
## Adding a lesson
|
||||||
Every bug found in real use gets an entry in `docs/pitfalls.md` and here, and, where possible, a check or a test
|
Every bug found in real use gets an entry in `docs/pitfalls.md` and here, and, where possible, a check or a test
|
||||||
that fails without the fix (see CONTRIBUTING.md).
|
that fails without the fix (see CONTRIBUTING.md).
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,8 @@
|
||||||
// owner's. Runs fillSession against MODELED pages (tests/fixtures/console) on 127.0.0.1. No network.
|
// owner's. Runs fillSession against MODELED pages (tests/fixtures/console) on 127.0.0.1. No network.
|
||||||
// Guardrail: no log line ever asks the owner to click a navigation control.
|
// Guardrail: no log line ever asks the owner to click a navigation control.
|
||||||
import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
|
import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
|
||||||
|
import { mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import { fillSession } from '../cli/console/fill';
|
import { fillSession } from '../cli/console/fill';
|
||||||
import type { ConsoleBrowser } from '../cli/console/session';
|
import type { ConsoleBrowser } from '../cli/console/session';
|
||||||
|
|
@ -223,3 +225,89 @@ describe.skipIf(!browser)('the other forms: navigation by itself, final buttons
|
||||||
}
|
}
|
||||||
}, TEST_MS);
|
}, TEST_MS);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe.skipIf(!browser)('watchdog: an unknown page after a click never means a silent wait', () => {
|
||||||
|
test('Next leads to a page storebound does not know: heartbeat, a sanitized debug dump, the manual steps, a bounded stop', async () => {
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'sb-console-debug-'));
|
||||||
|
try {
|
||||||
|
const b = await local();
|
||||||
|
const log = logLines();
|
||||||
|
const started = Date.now();
|
||||||
|
const out = await scope.run(fillSession(b, {
|
||||||
|
form: 'apple-app-privacy', config: privacy(), startUrl: base + 'apple-app-privacy-unknown.html', ...fast(log),
|
||||||
|
stepTimeoutMs: 1500, idleLimitMs: 5000, heartbeatMs: 700, debugDir: dir,
|
||||||
|
}));
|
||||||
|
expect(Date.now() - started).toBeLessThan(30_000);
|
||||||
|
expect(out.timedOut).toBe(true);
|
||||||
|
expect(out.debugDir).toBe(dir);
|
||||||
|
expect(b.isClosed()).toBe(true);
|
||||||
|
const said = log.lines.join('\n');
|
||||||
|
expect(said).toContain('clicked "Next" (navigation)');
|
||||||
|
expect(said).toMatch(/still waiting for the page after "Next", \d+ s/);
|
||||||
|
expect(said).toMatch(/the page after "Next" is not a page storebound knows .*Buttons there: .*"Done"/);
|
||||||
|
expect(said).toContain(`Debug saved to ${dir}`);
|
||||||
|
expect(said).toContain('do this part yourself');
|
||||||
|
expect(said).toContain('it stops here');
|
||||||
|
const [sub] = readdirSync(dir);
|
||||||
|
const files = readdirSync(join(dir, sub!)).sort();
|
||||||
|
expect(files).toEqual(['page.html', 'page.json', 'screen.jpg']);
|
||||||
|
const pj = JSON.parse(readFileSync(join(dir, sub!, 'page.json'), 'utf8'));
|
||||||
|
expect(pj.dialogs).toContain('Data Collection');
|
||||||
|
expect(pj.controls).toContainEqual({ role: 'switch', name: 'Contact details', checked: false });
|
||||||
|
expect(pj.url).toBe(`${base}apple-app-privacy-unknown.html`);
|
||||||
|
const all = readFileSync(join(dir, sub!, 'page.html'), 'utf8') + JSON.stringify(pj);
|
||||||
|
for (const leak of ['sb-token-should-not-leak', 'sb-csrf-should-not-leak', 'typed-by-owner-should-not-leak', 'owner@example.com', '010-9999', 'Example Owner']) expect(all).not.toContain(leak);
|
||||||
|
expect(all).toContain('[email]');
|
||||||
|
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||||
|
}, TEST_MS);
|
||||||
|
|
||||||
|
test('--debug-dump: a dump at the start, after each click and after each filled page', async () => {
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'sb-console-debug-'));
|
||||||
|
try {
|
||||||
|
const b = await local();
|
||||||
|
const log = logLines();
|
||||||
|
const run = scope.run(fillSession(b, { form: 'play-target-audience', config: base0, startUrl: base + 'play-target-audience.html', ...fast(log), debugDir: dir, debugEveryStep: true }));
|
||||||
|
await log.wait('the appeal stop', l => l.some(m => m.startsWith('answer needed on "Appeal to children"')));
|
||||||
|
await Bun.sleep(500);
|
||||||
|
const names = readdirSync(dir).sort();
|
||||||
|
expect(names[0]).toBe('01-start');
|
||||||
|
expect(names.some(n => /-filled-target-age$/.test(n))).toBe(true);
|
||||||
|
expect(names.some(n => /-after-next$/.test(n))).toBe(true);
|
||||||
|
await b.context.close();
|
||||||
|
await run;
|
||||||
|
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||||
|
}, TEST_MS);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('every wait of the console engine is bounded (code scan)', () => {
|
||||||
|
const SRC = join(import.meta.dir, '..', 'cli', 'console');
|
||||||
|
const files = readdirSync(SRC).filter(f => f.endsWith('.ts'));
|
||||||
|
/** The text from `open` to its matching `close` (brackets balanced). */
|
||||||
|
const span = (s: string, at: number, open: string, close: string): string => {
|
||||||
|
let d = 0;
|
||||||
|
for (let i = s.indexOf(open, at); i >= 0 && i < s.length; i++) { if (s[i] === open) d++; else if (s[i] === close && --d === 0) return s.slice(at, i + 1); }
|
||||||
|
return s.slice(at);
|
||||||
|
};
|
||||||
|
test('a while loop always checks a deadline (Date.now / end) or the watchdog', () => {
|
||||||
|
const bad: string[] = [];
|
||||||
|
for (const f of files) {
|
||||||
|
const s = readFileSync(join(SRC, f), 'utf8');
|
||||||
|
for (const m of s.matchAll(/\bwhile \(/g)) {
|
||||||
|
const cond = span(s, m.index!, '(', ')'), body = span(s, m.index! + cond.length, '{', '}');
|
||||||
|
if (!/Date\.now\(\)|\bend\b|\bwatch\(/.test(cond + body)) bad.push(`${f}: ${cond.slice(0, 80)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
expect(bad).toEqual([]);
|
||||||
|
});
|
||||||
|
test('no Playwright wait without a timeout, and the window\'s close is awaited only after a bounded wait or a close()', () => {
|
||||||
|
const bad: string[] = [];
|
||||||
|
for (const f of files) {
|
||||||
|
const lines = readFileSync(join(SRC, f), 'utf8').split('\n');
|
||||||
|
lines.forEach((l, i) => {
|
||||||
|
if (/\.waitFor(Selector|URL|Event|LoadState|Function)?\(/.test(l) && !/timeout/.test(l)) bad.push(`${f}:${i + 1} ${l.trim()}`);
|
||||||
|
if (/await [\w.]+\.closed\s*;/.test(l) && !lines.slice(Math.max(0, i - 3), i).some(p => /close\(\)/.test(p))) bad.push(`${f}:${i + 1} ${l.trim()}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
expect(bad).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
|
||||||
33
tests/fixtures/console/apple-app-privacy-unknown.html
vendored
Normal file
33
tests/fixtures/console/apple-app-privacy-unknown.html
vendored
Normal file
|
|
@ -0,0 +1,33 @@
|
||||||
|
<!doctype html>
|
||||||
|
<!-- MODELED, not recorded: App Privacy where the page after "Next" is one storebound does not know (the data types as
|
||||||
|
switches in groups, a "Done" button). The engine must not wait silently: after the step timeout it writes a debug
|
||||||
|
dump and stops after the idle limit. Personal-looking data (the account name in the header, an email, a typed
|
||||||
|
value, a hidden token) must not reach the dump. Placeholder data only. -->
|
||||||
|
<html lang="en"><head><meta charset="utf-8"><title>App Privacy - App Store Connect</title><script src="/_common.js"></script>
|
||||||
|
<script>window.__secret = 'sb-token-should-not-leak';</script></head>
|
||||||
|
<body>
|
||||||
|
<header aria-label="Account menu"><span>Example Owner</span> <button type="button">Example Owner Studio</button></header>
|
||||||
|
<h1>App Privacy</h1>
|
||||||
|
<button type="button" id="publish">Publish</button>
|
||||||
|
<p><button type="button" id="start">Get Started</button></p>
|
||||||
|
<p>Contact: owner@example.com, +1 (555) 010-9999</p>
|
||||||
|
<input type="hidden" name="csrf" value="sb-csrf-should-not-leak">
|
||||||
|
<div role="dialog" aria-label="Data Collection" id="collect" hidden>
|
||||||
|
<div id="c1">
|
||||||
|
<label><input type="radio" name="c"> Yes, we collect data from this app</label>
|
||||||
|
<label><input type="radio" name="c"> No, we do not collect data from this app</label>
|
||||||
|
<button type="button" id="next">Next</button>
|
||||||
|
</div>
|
||||||
|
<div id="c2" hidden>
|
||||||
|
<h2>Which kinds of data do you collect?</h2>
|
||||||
|
<div role="group" aria-label="Contact Info"><span role="switch" aria-checked="false" tabindex="0">Contact details</span></div>
|
||||||
|
<div role="group" aria-label="Identifiers"><span role="switch" aria-checked="false" tabindex="0">Device identifiers</span></div>
|
||||||
|
<label>Notes <input type="text" value="typed-by-owner-should-not-leak"></label>
|
||||||
|
<button type="button">Done</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
document.getElementById('start').addEventListener('click', () => { document.getElementById('collect').hidden = false; });
|
||||||
|
document.getElementById('next').addEventListener('click', () => { document.getElementById('c1').hidden = true; document.getElementById('c2').hidden = false; });
|
||||||
|
</script>
|
||||||
|
</body></html>
|
||||||
Loading…
Add table
Add a link
Reference in a new issue