robotest-mcp 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,250 @@
1
+ import { mkdirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { isAllowedNavigation, parseOrigin, shouldBlockRequest } from './guard.js';
4
+ import { browserEnv } from './browser-env.js';
5
+ /**
6
+ * The browser layer. Playwright is an OPTIONAL peer dependency: it is loaded only when an exploration starts, so the
7
+ * other RoboTest tools stay light. Every request and every click goes through the guard first.
8
+ */
9
+ export const PLAYWRIGHT_MISSING = 'Playwright is not installed. Install it once with: npm install playwright and then npx playwright install chromium (about 90 MB), then try again.';
10
+ const TEXT_LIMIT = 1500;
11
+ const CONTROL_LIMIT = 60;
12
+ // runs inside the page: lists what a person could click or type into, gives each one a stable id, and reads the visible text
13
+ const COLLECT_CONTROLS = `(limit, textLimit) => {
14
+ const sel = 'a[href],button,input:not([type=hidden]),select,textarea,[role=button],[role=link],[role=checkbox],[role=tab],[role=menuitem]';
15
+ for (const old of document.querySelectorAll('[data-rt-id]')) old.removeAttribute('data-rt-id');
16
+ const visible = (el) => { const r = el.getBoundingClientRect(); const s = getComputedStyle(el); return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; };
17
+ const labelOf = (el) => {
18
+ const aria = el.getAttribute('aria-label'); if (aria) return aria.trim();
19
+ const by = el.getAttribute('aria-labelledby'); if (by) { const t = by.split(' ').map((id) => document.getElementById(id)?.textContent || '').join(' ').trim(); if (t) return t; }
20
+ if (el.labels && el.labels.length) { const t = [...el.labels].map((l) => l.textContent || '').join(' ').trim(); if (t) return t; }
21
+ const own = (el.innerText || '').replace(/\\s+/g, ' ').trim(); if (own) return own;
22
+ const img = el.querySelector('img[alt]'); if (img && img.alt.trim()) return img.alt.trim();
23
+ // the value of a button-like input is its name (<input type=submit value=Continue>); the value of a text field is what someone typed, so it is not
24
+ const buttonLike = el.tagName === 'INPUT' && ['submit', 'button', 'reset'].includes(el.type);
25
+ if (buttonLike && el.value) return el.value;
26
+ if (el.tagName === 'INPUT' && el.type === 'image' && el.alt) return el.alt;
27
+ return (el.value && el.tagName !== 'INPUT' ? el.value : '') || el.getAttribute('placeholder') || el.getAttribute('title') || '';
28
+ };
29
+ const out = [];
30
+ let n = 0;
31
+ for (const el of document.querySelectorAll(sel)) {
32
+ if (!visible(el)) continue;
33
+ n += 1; if (n > limit) break;
34
+ const id = 'c' + n;
35
+ el.setAttribute('data-rt-id', id);
36
+ const tag = el.tagName.toLowerCase();
37
+ out.push({
38
+ id, role: el.getAttribute('role') || (tag === 'a' ? 'link' : tag === 'input' ? (el.type || 'text') + ' input' : tag),
39
+ label: labelOf(el).slice(0, 120),
40
+ enabled: !el.disabled && el.getAttribute('aria-disabled') !== 'true',
41
+ type: tag === 'input' ? el.type : undefined,
42
+ });
43
+ }
44
+ return { controls: out, text: (document.body.innerText || '').replace(/\\n{3,}/g, '\\n\\n').trim().slice(0, textLimit) };
45
+ }`;
46
+ export class ExploreBrowser {
47
+ browser;
48
+ page;
49
+ opts;
50
+ startOrigin;
51
+ consoleErrors = [];
52
+ failedRequests = [];
53
+ requestCount = 0;
54
+ shots = 0;
55
+ blockedCount = 0;
56
+ lastGoodUrl;
57
+ constructor(browser, page, opts, startOrigin) {
58
+ this.browser = browser;
59
+ this.page = page;
60
+ this.opts = opts;
61
+ this.startOrigin = startOrigin;
62
+ this.lastGoodUrl = opts.startUrl;
63
+ }
64
+ /** Opens the browser and the first page. Throws PLAYWRIGHT_MISSING (as an Error) when Playwright is not installed. */
65
+ static async launch(opts) {
66
+ const startOrigin = parseOrigin(opts.startUrl);
67
+ if (!startOrigin)
68
+ throw new Error('The url must start with http:// or https://.');
69
+ let playwright;
70
+ try {
71
+ playwright = await import('playwright');
72
+ }
73
+ catch {
74
+ throw new Error(PLAYWRIGHT_MISSING);
75
+ }
76
+ const browser = await playwright.chromium.launch({ headless: opts.headless, env: browserEnv(opts.env ?? process.env) }).catch((e) => {
77
+ throw new Error(/Executable doesn't exist|browserType.launch/i.test(String(e.message)) ? PLAYWRIGHT_MISSING : `Could not start the browser: ${e.message}`);
78
+ });
79
+ const context = await browser.newContext({ viewport: { width: 1280, height: 800 }, acceptDownloads: false, serviceWorkers: 'block' });
80
+ const page = await context.newPage();
81
+ const self = new ExploreBrowser(browser, page, opts, startOrigin);
82
+ // every request passes the guard: the origin lock for page navigations, read-only protection for writes
83
+ await context.route('**/*', async (route) => {
84
+ const req = route.request();
85
+ const url = req.url();
86
+ if (req.isNavigationRequest() && !isAllowedNavigation(startOrigin, url, opts.allowOrigins)) {
87
+ self.blockedCount += 1;
88
+ opts.onBlocked(`navigation outside the start origin: ${url}`);
89
+ return route.abort('blockedbyclient');
90
+ }
91
+ if (shouldBlockRequest(opts.environment, { method: req.method(), url })) {
92
+ self.blockedCount += 1;
93
+ opts.onBlocked(`${req.method()} ${url} (production is read-only)`);
94
+ return route.abort('blockedbyclient');
95
+ }
96
+ self.requestCount += 1;
97
+ return route.continue();
98
+ });
99
+ const trace = opts.trace;
100
+ const levelOf = (type) => (type === 'error' ? 'error' : type === 'warning' ? 'warn' : type === 'info' ? 'info' : type === 'debug' ? 'debug' : 'log');
101
+ const pending = new Map();
102
+ page.on('console', (m) => {
103
+ if (m.type() === 'error')
104
+ self.consoleErrors.push(`console error: ${m.text()}`.slice(0, 400));
105
+ const where = m.location?.()?.url;
106
+ trace?.addConsole(levelOf(m.type()), m.text(), where);
107
+ });
108
+ page.on('pageerror', (e) => {
109
+ self.consoleErrors.push(`page error: ${e.message}`.slice(0, 400));
110
+ trace?.addConsole('error', `Uncaught ${e.message}`);
111
+ });
112
+ page.on('request', (r) => {
113
+ const entry = trace?.startRequest(r.method(), r.url(), r.resourceType());
114
+ if (entry)
115
+ pending.set(r, { entry, startedAt: Date.now() });
116
+ });
117
+ page.on('response', (r) => {
118
+ if (r.status() >= 400)
119
+ self.failedRequests.push(`${r.status()} ${r.request().method()} ${r.url()}`.slice(0, 300));
120
+ const p = pending.get(r.request());
121
+ if (p) {
122
+ p.entry.status = r.status();
123
+ p.entry.ms = Date.now() - p.startedAt;
124
+ const length = Number(r.headers()['content-length']);
125
+ if (Number.isFinite(length) && length >= 0)
126
+ p.entry.size = length;
127
+ }
128
+ });
129
+ page.on('requestfinished', (r) => { pending.delete(r); });
130
+ page.on('requestfailed', (r) => {
131
+ const why = r.failure()?.errorText ?? 'failed';
132
+ const blocked = /blocked_?by_?client/i.test(why);
133
+ if (!blocked)
134
+ self.failedRequests.push(`failed ${r.method()} ${r.url()}: ${why}`.slice(0, 300));
135
+ const p = pending.get(r);
136
+ if (p) {
137
+ p.entry.failed = blocked ? 'refused by the safety layer' : why;
138
+ if (blocked)
139
+ p.entry.blocked = true;
140
+ pending.delete(r);
141
+ }
142
+ });
143
+ await page.goto(opts.startUrl, { waitUntil: 'domcontentloaded', timeout: 20_000 });
144
+ await page.waitForTimeout(300);
145
+ return self;
146
+ }
147
+ /** The page as the explorer sees it: compact, never the whole DOM. Errors are those since the last observation. */
148
+ async observe() {
149
+ const { controls, text } = (await this.page.evaluate(`(${COLLECT_CONTROLS})(${CONTROL_LIMIT}, ${TEXT_LIMIT})`));
150
+ const consoleErrors = this.consoleErrors.splice(0);
151
+ const failedRequests = this.failedRequests.splice(0);
152
+ return { url: this.page.url(), title: await this.page.title(), text, controls, consoleErrors, failedRequests, requestCount: this.requestCount };
153
+ }
154
+ currentUrl() {
155
+ return this.page.url();
156
+ }
157
+ async settle() {
158
+ await this.page.waitForLoadState('domcontentloaded', { timeout: 5000 }).catch(() => undefined);
159
+ await this.page.waitForTimeout(350);
160
+ if (!this.page.url().startsWith('chrome-error:'))
161
+ this.lastGoodUrl = this.page.url();
162
+ }
163
+ /** A refused navigation leaves the browser on an error page: go back to the last good page and say what happened. */
164
+ async recoverIfBlocked(blockedBefore) {
165
+ if (this.blockedCount === blockedBefore && !this.page.url().startsWith('chrome-error:'))
166
+ return null;
167
+ if (this.page.url().startsWith('chrome-error:'))
168
+ await this.page.goto(this.lastGoodUrl, { waitUntil: 'domcontentloaded', timeout: 10_000 }).catch(() => undefined);
169
+ return `The safety layer refused a request (leaving the site or changing data). You are still on ${this.page.url()}.`;
170
+ }
171
+ /** Performs one action on a control from the last observation. Never throws: a failure is reported in the note. */
172
+ async act(action, controlId, text) {
173
+ try {
174
+ if (action === 'back') {
175
+ await this.page.goBack({ timeout: 5000, waitUntil: 'domcontentloaded' });
176
+ await this.settle();
177
+ return { ok: true, note: 'Went back' };
178
+ }
179
+ if (!controlId)
180
+ return { ok: false, note: 'This action needs a controlId from explore_observe.' };
181
+ const target = this.page.locator(`[data-rt-id="${controlId.replace(/[^a-z0-9]/gi, '')}"]`).first();
182
+ if ((await target.count()) === 0)
183
+ return { ok: false, note: 'Unknown control. The page changed: call explore_observe again.' };
184
+ if (!(await target.isEnabled()))
185
+ return { ok: false, note: 'The control is disabled, so it cannot be used.' };
186
+ const blockedBefore = this.blockedCount;
187
+ if (action === 'click')
188
+ await target.click({ timeout: 5000 });
189
+ else if (action === 'type')
190
+ await target.fill(text ?? '', { timeout: 5000 });
191
+ else if (action === 'select')
192
+ await target.selectOption(text ?? '', { timeout: 5000 });
193
+ else if (action === 'press')
194
+ await target.press(text || 'Enter', { timeout: 5000 });
195
+ else
196
+ return { ok: false, note: `Unknown action: ${action}` };
197
+ await this.settle();
198
+ const refused = await this.recoverIfBlocked(blockedBefore);
199
+ return refused ? { ok: false, note: refused } : { ok: true, note: `${action} done` };
200
+ }
201
+ catch (e) {
202
+ return { ok: false, note: `The action failed: ${String(e.message).split('\n')[0].slice(0, 200)}` };
203
+ }
204
+ }
205
+ /** Fills the sign-in form with the credentials from the environment. The values never leave this function. */
206
+ async login(user, pass) {
207
+ try {
208
+ const password = this.page.locator('input[type=password]:visible').first();
209
+ if ((await password.count()) === 0)
210
+ return { ok: false, note: 'No password field on this page. Open the sign-in page first.' };
211
+ const userField = this.page.locator('input[type=email]:visible, input[type=text]:visible, input:not([type]):visible').first();
212
+ if ((await userField.count()) > 0)
213
+ await userField.fill(user, { timeout: 5000 });
214
+ await password.fill(pass, { timeout: 5000 });
215
+ const form = password.locator('xpath=ancestor::form[1]');
216
+ const submit = (await form.count()) > 0 ? form.locator('button[type=submit], input[type=submit], button').first() : this.page.locator('button[type=submit]:visible').first();
217
+ if ((await submit.count()) > 0)
218
+ await submit.click({ timeout: 5000 });
219
+ else
220
+ await password.press('Enter');
221
+ await this.settle();
222
+ return { ok: true, note: 'The sign-in form was filled and submitted.' };
223
+ }
224
+ catch (e) {
225
+ return { ok: false, note: `Sign-in failed: ${String(e.message).split('\n')[0].slice(0, 160)}` };
226
+ }
227
+ }
228
+ /** Saves a screenshot into the run folder and returns its id. */
229
+ async screenshot(runDir) {
230
+ mkdirSync(runDir, { recursive: true });
231
+ this.shots += 1;
232
+ const id = `shot-${this.shots}`;
233
+ await this.page.screenshot({ path: join(runDir, `${id}.png`), fullPage: false });
234
+ return id;
235
+ }
236
+ /** A small JPEG of the page after a step, saved in the run folder. Returns false when the page cannot be captured. */
237
+ async stepShot(runDir, id) {
238
+ try {
239
+ mkdirSync(runDir, { recursive: true });
240
+ await this.page.screenshot({ path: join(runDir, `${id}.jpg`), type: 'jpeg', quality: 55, fullPage: false, timeout: 5000 });
241
+ return true;
242
+ }
243
+ catch {
244
+ return false;
245
+ }
246
+ }
247
+ async close() {
248
+ await this.browser.close().catch(() => undefined);
249
+ }
250
+ }
@@ -0,0 +1,266 @@
1
+ import { existsSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { accountNames, resolveAccount, secretsOf } from './accounts.js';
5
+ import { loginAllowed, loginOriginsFrom } from './credentials.js';
6
+ import { ExploreBrowser } from './browser.js';
7
+ import { clampBudget, createBudget, looksDestructive, parseOrigin, redact } from './guard.js';
8
+ import { ExploreSession } from './session.js';
9
+ import { RunTrace } from './trace.js';
10
+ const fail = (error) => ({ ok: false, error });
11
+ const done = (data) => ({ ok: true, data });
12
+ export const defaultHome = (env = process.env) => env.ROBOTEST_HOME || join(homedir(), '.robotest');
13
+ /** the next run number: one more than the highest numbered folder in <home>/runs */
14
+ export function nextRunNumber(home) {
15
+ const dir = join(home, 'runs');
16
+ if (!existsSync(dir))
17
+ return 1;
18
+ const numbers = readdirSync(dir).map((n) => Number(n)).filter((n) => Number.isInteger(n) && n > 0);
19
+ return numbers.length ? Math.max(...numbers) + 1 : 1;
20
+ }
21
+ const RULES = [
22
+ 'Verify before you report: observe the page and quote what you saw.',
23
+ 'One finding per defect. Evidence must be copied word for word from an observation; invented evidence is rejected.',
24
+ 'Stay on the site you were given. Do not try to leave it.',
25
+ ];
26
+ export class ExploreController {
27
+ session = null;
28
+ /** the first site this explorer opened: the only one a test account is typed into, unless ROBOTEST_LOGIN_ORIGINS says otherwise */
29
+ firstOrigin = null;
30
+ sessionOrigin = '';
31
+ browser = null;
32
+ budget = null;
33
+ runDir = '';
34
+ lastControls = new Map();
35
+ lastControlTypes = new Map();
36
+ trace = null;
37
+ lastShot;
38
+ home;
39
+ env;
40
+ headless;
41
+ constructor(opts = {}) {
42
+ this.env = opts.env ?? process.env;
43
+ this.home = opts.home ?? defaultHome(this.env);
44
+ this.headless = opts.headless ?? true;
45
+ }
46
+ isActive() {
47
+ return this.session !== null;
48
+ }
49
+ requireActive() {
50
+ return this.session && this.browser ? this.session : 'No exploration is open. Call explore_open first.';
51
+ }
52
+ async open(input) {
53
+ if (this.session)
54
+ return fail('An exploration is already open. Call explore_finish first.');
55
+ if (input.permission !== true)
56
+ return fail('Permission is required. Ask the user to confirm that they have permission to test this site, then call explore_open again with permission: true.');
57
+ const origin = parseOrigin(input.url);
58
+ if (!origin)
59
+ return fail('The url must start with http:// or https://.');
60
+ const budget = createBudget(clampBudget(input.budget));
61
+ const allowOrigins = (input.allowOrigins ?? []).map(parseOrigin).filter((o) => !!o);
62
+ const runNumber = nextRunNumber(this.home);
63
+ const runDir = join(this.home, 'runs', String(runNumber));
64
+ mkdirSync(runDir, { recursive: true });
65
+ let session = null;
66
+ let browser;
67
+ // every user name and password of every account: none of them may appear in anything logged or returned
68
+ const secrets = secretsOf(this.env);
69
+ const trace = new RunTrace({ clean: (text) => redact(text, secrets) });
70
+ const openStep = trace.begin('open', `Opening ${input.url}`);
71
+ try {
72
+ browser = await ExploreBrowser.launch({
73
+ startUrl: input.url, environment: input.environment, allowOrigins, headless: this.headless, env: this.env,
74
+ onBlocked: (d) => session?.recordBlocked(d), trace,
75
+ });
76
+ }
77
+ catch (e) {
78
+ return fail(e.message);
79
+ }
80
+ session = new ExploreSession({
81
+ runId: String(runNumber), startUrl: input.url, origin, environment: input.environment, environmentName: input.environmentName?.replace(/\s+/g, ' ').trim().slice(0, 40) || undefined, lens: input.lens, goal: input.goal, budget,
82
+ criteria: (input.criteria ?? []).map((c) => redact(c, secrets)),
83
+ secrets, permissionConfirmedAt: new Date().toISOString(),
84
+ });
85
+ this.session = session;
86
+ this.firstOrigin ??= origin;
87
+ this.sessionOrigin = origin;
88
+ this.browser = browser;
89
+ this.budget = budget;
90
+ this.runDir = runDir;
91
+ this.lastControls = new Map();
92
+ this.lastControlTypes = new Map();
93
+ this.trace = trace;
94
+ this.lastShot = undefined;
95
+ trace.end(openStep, { ok: true, url: browser.currentUrl(), shot: await this.stepShot(openStep) });
96
+ const envLabel = input.environmentName?.replace(/\s+/g, ' ').trim().slice(0, 40) || undefined;
97
+ return done({
98
+ runId: runNumber, origin, environment: input.environment, ...(input.environmentName?.trim() ? { environmentName: input.environmentName.replace(/\s+/g, ' ').trim().slice(0, 40) } : {}), lens: input.lens, goal: input.goal, budget: budget.limits,
99
+ protection: input.environment === 'production'
100
+ ? `${envLabel ? `READ-ONLY (${envLabel})` : 'PRODUCTION'}: requests that change data are refused (sign-in excepted) and controls that look destructive are not clicked. This is a guard, not a guarantee.`
101
+ : `${envLabel ?? 'Staging'}: changes are allowed. The browser still cannot leave the site.`,
102
+ rules: RULES,
103
+ ...(accountNames(this.env).length > 0 ? { accounts: accountNames(this.env), accountsHint: 'Sign in with explore_login, optionally with account set to one of these names. You never see the passwords.' }
104
+ : this.env.ROBOTEST_LOGIN_USER && this.env.ROBOTEST_LOGIN_PASS ? { accountsHint: 'A default test account is set. Sign in with explore_login and no account. You never see the password.' } : {}),
105
+ ...((input.criteria ?? []).length > 0 ? { criteria: (input.criteria ?? []).map((text, i) => ({ n: i + 1, text })) } : {}),
106
+ next: (input.criteria ?? []).length > 0
107
+ ? 'Call explore_observe to see the page. Check every criterion and answer each with explore_verify_criterion (pass, fail or blocked, with evidence you observed).'
108
+ : 'Call explore_observe to see the page.',
109
+ });
110
+ }
111
+ async observe() {
112
+ const s = this.requireActive();
113
+ if (typeof s === 'string')
114
+ return fail(s);
115
+ if (s.observations.length >= this.budget.limits.maxActions * 3)
116
+ return fail('Too many observations for this budget. Call explore_finish.');
117
+ const raw = await this.browser.observe();
118
+ const obs = s.recordObservation(raw);
119
+ this.lastControls = new Map(obs.controls.map((c) => [c.id, c.label]));
120
+ this.lastControlTypes = new Map(obs.controls.map((c) => [c.id, c.type]));
121
+ return done({
122
+ observation: obs.n, url: obs.url, title: obs.title, text: obs.text, controls: obs.controls,
123
+ consoleErrors: obs.consoleErrors, failedRequests: obs.failedRequests, requestCount: obs.requestCount,
124
+ budgetLeft: { actions: this.budget.limits.maxActions - this.budget.actionsUsed() },
125
+ });
126
+ }
127
+ async act(input) {
128
+ const s = this.requireActive();
129
+ if (typeof s === 'string')
130
+ return fail(s);
131
+ const stop = this.budget.exhausted();
132
+ if (stop)
133
+ return fail(`${stop} Stop exploring and call explore_finish.`);
134
+ const label = input.controlId ? this.lastControls.get(input.controlId) : undefined;
135
+ const n = this.trace.begin(input.action, this.describeAction(input, label));
136
+ // production: never click something that looks like it deletes, pays or cancels
137
+ if (s.init.environment === 'production' && input.action === 'click' && looksDestructive(label)) {
138
+ const rec = s.recordAction({ action: input.action, controlId: input.controlId, label, ok: false, note: 'Refused: the control looks destructive and this is production.', url: this.browser.currentUrl() });
139
+ this.trace.end(n, { ok: false, url: rec.url, detail: rec.note });
140
+ return done({ ok: false, note: rec.note, url: rec.url });
141
+ }
142
+ this.budget.recordAction();
143
+ const result = await this.browser.act(input.action, input.controlId, input.text);
144
+ const rec = s.recordAction({ action: input.action, controlId: input.controlId, label, ok: result.ok, note: result.note, url: this.browser.currentUrl() });
145
+ this.trace.end(n, { ok: rec.ok, url: rec.url, detail: rec.ok ? undefined : rec.note, shot: await this.stepShot(n) });
146
+ return done({ ok: rec.ok, note: rec.note, url: rec.url, budgetLeft: { actions: this.budget.limits.maxActions - this.budget.actionsUsed() } });
147
+ }
148
+ /** Signs in with the default account, or with the named one (ROBOTEST_LOGIN_<NAME>_USER and _PASS). The AI only ever names it. */
149
+ async login(account) {
150
+ const s = this.requireActive();
151
+ if (typeof s === 'string')
152
+ return fail(s);
153
+ const found = resolveAccount(this.env, account);
154
+ if (!found.ok)
155
+ return fail(found.error);
156
+ // the account is only typed into the site it belongs to, never into a site opened later on the word of a page
157
+ const where = loginAllowed(this.sessionOrigin, this.firstOrigin, loginOriginsFrom(this.env));
158
+ if (!where.ok)
159
+ return fail(where.error);
160
+ const stop = this.budget.exhausted();
161
+ if (stop)
162
+ return fail(`${stop} Stop exploring and call explore_finish.`);
163
+ this.budget.recordAction();
164
+ const n = this.trace.begin('login', found.name === 'default' ? 'Sign in with the configured account' : `Sign in as ${found.name}`);
165
+ const result = await this.browser.login(found.user, found.pass);
166
+ const rec = s.recordAction({ action: 'login', ok: result.ok, note: result.note, url: this.browser.currentUrl() });
167
+ this.trace.end(n, { ok: rec.ok, url: rec.url, detail: rec.ok ? undefined : rec.note, shot: await this.stepShot(n) });
168
+ return done({ ok: rec.ok, note: rec.note, url: rec.url });
169
+ }
170
+ async screenshot() {
171
+ const s = this.requireActive();
172
+ if (typeof s === 'string')
173
+ return fail(s);
174
+ if (s.screenshots.length >= 12)
175
+ return fail('The limit of 12 screenshots per run is reached.');
176
+ const n = this.trace.begin('screenshot', 'Take a screenshot');
177
+ const id = await this.browser.screenshot(this.runDir);
178
+ s.addScreenshot(id);
179
+ this.trace.end(n, { ok: true, url: this.browser.currentUrl() });
180
+ return done({ screenshotId: id, savedIn: this.runDir });
181
+ }
182
+ reportFinding(input) {
183
+ const s = this.requireActive();
184
+ if (typeof s === 'string')
185
+ return fail(s);
186
+ const url = this.browser.currentUrl();
187
+ const n = this.trace.begin('finding', `Finding: ${input.title}`);
188
+ const result = s.addFinding(input, { step: n, url, shot: this.lastShot });
189
+ this.trace.end(n, { ok: result.ok, url, detail: result.ok ? undefined : result.reason });
190
+ return result.ok ? done({ accepted: true, id: result.finding.id }) : fail(result.reason);
191
+ }
192
+ /**
193
+ * What has been recorded so far, for a person watching the run: the finished steps, the console and the network (already cleaned
194
+ * of secrets), the accepted findings and the folder of the screenshots. Null when no run is open.
195
+ */
196
+ liveView() {
197
+ if (!this.session || !this.trace)
198
+ return null;
199
+ return { runDir: this.runDir, steps: this.trace.steps, console: this.trace.console, network: this.trace.network, findings: this.session.findings };
200
+ }
201
+ async finish() {
202
+ const s = this.requireActive();
203
+ if (typeof s === 'string')
204
+ return fail(s);
205
+ const n = this.trace.begin('finish', 'Finish the exploration');
206
+ this.trace.end(n, { ok: true, url: this.browser.currentUrl() });
207
+ const file = s.toRunFile(undefined, { trace: this.trace.toJSON() });
208
+ writeFileSync(join(this.runDir, 'run.json'), JSON.stringify(file, null, 2), 'utf-8');
209
+ await this.browser.close();
210
+ const result = done({ runFile: join(this.runDir, 'run.json'), narrative: file.narrative, summary: file.summary, findings: file.findings.map((f) => ({ id: f.id, severity: f.severity, title: f.title })), ...(file.criteria ? { criteria: file.criteria } : {}) });
211
+ this.session = null;
212
+ this.browser = null;
213
+ this.budget = null;
214
+ this.trace = null;
215
+ return result;
216
+ }
217
+ /** The answer for one acceptance criterion: pass, fail or blocked, with evidence that was really observed. */
218
+ verifyCriterion(input) {
219
+ const s = this.requireActive();
220
+ if (typeof s === 'string')
221
+ return fail(s);
222
+ const url = this.browser.currentUrl();
223
+ const text = s.init.criteria?.[input.criterion - 1];
224
+ const label = text ? `Criterion ${input.criterion}: ${input.verdict} (${text.length > 70 ? `${text.slice(0, 69)}…` : text})` : `Criterion ${input.criterion}: ${input.verdict}`;
225
+ const n = this.trace.begin('verdict', label);
226
+ const result = s.addVerdict(input, { step: n, url, shot: this.lastShot });
227
+ this.trace.end(n, { ok: result.ok, url, detail: result.ok ? undefined : result.reason });
228
+ if (!result.ok)
229
+ return fail(result.reason);
230
+ const summary = s.criteriaSummary();
231
+ return done({ recorded: true, criterion: input.criterion, verdict: input.verdict, notVerifiedYet: summary.unverified });
232
+ }
233
+ /** One sentence from the model about why it takes the next step; it is shown in the run viewer. */
234
+ annotate(thought) {
235
+ this.trace?.annotate(thought);
236
+ }
237
+ /** the label of a step in the run viewer; a password that was typed is never shown */
238
+ describeAction(input, label) {
239
+ const name = label ? `"${label}"` : input.controlId ?? '';
240
+ if (input.action === 'back')
241
+ return 'Go back';
242
+ if (input.action === 'type') {
243
+ const secret = this.lastControlTypes.get(input.controlId ?? '') === 'password';
244
+ return `Type into ${name}: ${secret ? '••••••' : `"${input.text ?? ''}"`}`;
245
+ }
246
+ if (input.action === 'select')
247
+ return `Select "${input.text ?? ''}" in ${name}`;
248
+ if (input.action === 'press')
249
+ return `Press ${input.text || 'Enter'} on ${name}`;
250
+ return `Click ${name}`;
251
+ }
252
+ /** a small screenshot after a step; the id of the file, or undefined when the limit is reached or the page cannot be captured */
253
+ async stepShot(n) {
254
+ const id = this.trace?.nextShot(n);
255
+ if (!id || !(await this.browser.stepShot(this.runDir, id)))
256
+ return undefined;
257
+ this.lastShot = id;
258
+ return id;
259
+ }
260
+ /** closes the browser without saving, for when the MCP server shuts down */
261
+ async dispose() {
262
+ await this.browser?.close();
263
+ this.session = null;
264
+ this.browser = null;
265
+ }
266
+ }
@@ -0,0 +1,24 @@
1
+ import { parseOrigin } from './guard.js';
2
+ /**
3
+ * Where a test account may be typed in. The explorer fills the sign-in form of whatever page is open, and in MCP mode the page
4
+ * the browser is on is chosen by the connected model, which also reads the page text. Without a rule, text on a hostile page
5
+ * could talk the model into opening another site and signing in there. So the account is only typed into:
6
+ * - an origin listed in ROBOTEST_LOGIN_ORIGINS (comma separated), or
7
+ * - when nothing is listed, the first site this explorer opened (the site the person asked to test).
8
+ */
9
+ export function loginOriginsFrom(env) {
10
+ return (env.ROBOTEST_LOGIN_ORIGINS ?? '')
11
+ .split(',')
12
+ .map((o) => parseOrigin(o.trim()))
13
+ .filter((o) => !!o);
14
+ }
15
+ export function loginAllowed(currentOrigin, firstOrigin, configured) {
16
+ const allowed = configured.length > 0 ? configured : firstOrigin ? [firstOrigin] : [];
17
+ if (allowed.includes(currentOrigin))
18
+ return { ok: true };
19
+ return {
20
+ ok: false,
21
+ error: `The test account is not typed into ${currentOrigin}: it is only used on ${allowed.join(', ') || 'the first site that was opened'}. ` +
22
+ 'If this is the right site, the person running the explorer can list it in ROBOTEST_LOGIN_ORIGINS. Do not open other sites to sign in.',
23
+ };
24
+ }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * The safety layer of the explorer. Everything here is a plain function with no browser in it, so each rule can be tested
3
+ * on its own. The rules are enforced in code (the browser layer asks these functions before it does anything); they are
4
+ * never left to the model's good behaviour.
5
+ *
6
+ * - Origin lock: the browser may only go to the site it was opened on (plus an explicit allow-list).
7
+ * - Production read-only: on `production`, requests that change data are refused, and controls that look destructive
8
+ * are not clicked. This is a guard, not a guarantee: a site can change data with a plain GET.
9
+ * - Budgets: a hard maximum of actions and minutes.
10
+ * - Secrets: credentials come from environment variables and are removed from everything that is logged or returned.
11
+ * - Evidence: a finding may only quote text that really appeared in what the explorer observed.
12
+ */
13
+ // ------------------------------------------------------------------ origin lock
14
+ export function parseOrigin(url) {
15
+ try {
16
+ const u = new URL(url);
17
+ return u.protocol === 'http:' || u.protocol === 'https:' ? u.origin : null;
18
+ }
19
+ catch {
20
+ return null;
21
+ }
22
+ }
23
+ /** Is the browser allowed to go to `target`? Same origin as the start, or an origin on the allow-list. */
24
+ export function isAllowedNavigation(startOrigin, target, allowList = []) {
25
+ const origin = parseOrigin(target);
26
+ if (!origin)
27
+ return false;
28
+ return origin === startOrigin || allowList.map(parseOrigin).includes(origin);
29
+ }
30
+ // ------------------------------------------------------------------ production read-only
31
+ const WRITE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
32
+ export const isWriteMethod = (method) => WRITE_METHODS.has(method.toUpperCase());
33
+ /** Paths that may be written to even on production, so signing in works. Matched against the URL path. */
34
+ export const DEFAULT_LOGIN_PATHS = [/\/(log-?in|sign-?in|auth|session|token|oauth)(\/|$|\?)/i];
35
+ /** Should this request be refused? Only ever true on production, and only for requests that change data. */
36
+ export function shouldBlockRequest(environment, request, loginPaths = DEFAULT_LOGIN_PATHS) {
37
+ if (environment !== 'production' || !isWriteMethod(request.method))
38
+ return false;
39
+ let path = '';
40
+ try {
41
+ path = new URL(request.url).pathname;
42
+ }
43
+ catch {
44
+ return true;
45
+ }
46
+ return !loginPaths.some((re) => re.test(path));
47
+ }
48
+ const DESTRUCTIVE = [
49
+ /\b(delete|remove|erase|destroy|wipe|purge)\b/i,
50
+ /\b(pay|payment|purchase|buy( now)?|checkout now|place (an? )?order|submit (an? )?order|confirm (order|payment|purchase))\b/i,
51
+ /\b(cancel (my |the )?(plan|subscription|account|membership)|unsubscribe|deactivate|close (my )?account|terminate)\b/i,
52
+ /\b(send|publish|post) (to|for) (everyone|all)\b/i,
53
+ /(حذف|مسح|إزالة|دفع|شراء|اشتري|تأكيد الطلب|إلغاء الاشتراك|إغلاق الحساب|تعطيل الحساب)/,
54
+ ];
55
+ /** Does a control's label look like it deletes, pays or cancels something? Checked on production before any click. */
56
+ export function looksDestructive(label) {
57
+ const text = (label ?? '').trim();
58
+ return text.length > 0 && DESTRUCTIVE.some((re) => re.test(text));
59
+ }
60
+ export const DEFAULT_BUDGET = { maxActions: 60, maxMinutes: 15 };
61
+ /** nobody can ask for more than this, whatever the model sends */
62
+ export const HARD_BUDGET_CEILING = { maxActions: 200, maxMinutes: 45 };
63
+ export function clampBudget(requested) {
64
+ const clamp = (value, fallback, ceiling) => typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.min(Math.floor(value), ceiling) : fallback;
65
+ return {
66
+ maxActions: clamp(requested?.maxActions, DEFAULT_BUDGET.maxActions, HARD_BUDGET_CEILING.maxActions),
67
+ maxMinutes: clamp(requested?.maxMinutes, DEFAULT_BUDGET.maxMinutes, HARD_BUDGET_CEILING.maxMinutes),
68
+ };
69
+ }
70
+ export function createBudget(limits, now = Date.now) {
71
+ const startedAt = now();
72
+ let actions = 0;
73
+ const minutes = () => (now() - startedAt) / 60_000;
74
+ return {
75
+ limits,
76
+ exhausted: () => {
77
+ if (actions >= limits.maxActions)
78
+ return `The action budget (${limits.maxActions}) is used up.`;
79
+ if (minutes() >= limits.maxMinutes)
80
+ return `The time budget (${limits.maxMinutes} minutes) is used up.`;
81
+ return null;
82
+ },
83
+ recordAction: () => { actions += 1; },
84
+ actionsUsed: () => actions,
85
+ minutesUsed: () => Math.round(minutes() * 10) / 10,
86
+ };
87
+ }
88
+ // ------------------------------------------------------------------ secrets
89
+ const TOKEN_PATTERNS = [
90
+ /sk-ant-[A-Za-z0-9_-]{10,}/g,
91
+ /sk-(?:proj-)?[A-Za-z0-9_-]{16,}/g,
92
+ /AIza[0-9A-Za-z_-]{20,}/g,
93
+ /gh[pousr]_[A-Za-z0-9]{20,}/g,
94
+ /github_pat_[A-Za-z0-9_]{20,}/g,
95
+ /(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{16,}/gi,
96
+ /eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g, // JSON web tokens
97
+ ];
98
+ /** Removes known secret values (the login credentials) and anything shaped like a token. */
99
+ export function redact(text, secrets = []) {
100
+ let out = text;
101
+ for (const secret of secrets) {
102
+ if (secret && secret.length >= 3)
103
+ out = out.split(secret).join('[redacted]');
104
+ }
105
+ return TOKEN_PATTERNS.reduce((acc, re) => acc.replace(re, '[redacted]'), out);
106
+ }
107
+ // ------------------------------------------------------------------ evidence
108
+ const norm = (value) => value.toLowerCase().replace(/\s+/g, ' ').replace(/^["'`«»“”]+|["'`«»“”]+$/g, '').trim();
109
+ /**
110
+ * A finding's evidence must be text that really appeared in an observation (page text, a control label, a console error,
111
+ * a failed request). If it is not found there, the finding is rejected: this is how invented findings are stopped.
112
+ */
113
+ export function evidenceInLog(evidence, observedTexts) {
114
+ const quote = norm(evidence);
115
+ if (quote.length < 4)
116
+ return false;
117
+ return observedTexts.some((text) => norm(text).includes(quote));
118
+ }