From 81aec02191738b5d65ee6e0eecbd6c770111c218 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 08:32:21 +0100 Subject: [PATCH 1/8] fix(maestro): refuse selector regexes that can stall the daemon --- build/maestro/tsdown.config.ts | 2 +- packages/maestro/package.json | 3 +- .../internal/__tests__/selector-regex.test.ts | 41 +++++ .../internal/runtime-selector-resolution.ts | 4 + .../maestro/src/internal/selector-regex.ts | 158 +++++++++++++++++- pnpm-lock.yaml | 3 + website/docs/docs/error-reasons.md | 6 + website/docs/docs/run-maestro-flows.md | 1 + 8 files changed, 214 insertions(+), 4 deletions(-) diff --git a/build/maestro/tsdown.config.ts b/build/maestro/tsdown.config.ts index a8931fc3cd7..802aa2a5357 100644 --- a/build/maestro/tsdown.config.ts +++ b/build/maestro/tsdown.config.ts @@ -26,7 +26,7 @@ export default defineConfig({ deps: { neverBundle: ['agent-device/plugins'], alwaysBundle: [/^@agent-device\//], - onlyBundle: ['yaml', 'undici', 'ipaddr.js', 'pngjs', 'jpeg-js'], + onlyBundle: ['yaml', 'undici', 'ipaddr.js', 'pngjs', 'jpeg-js', '@eslint-community/regexpp'], }, inputOptions: { onLog(level, log, handler) { diff --git a/packages/maestro/package.json b/packages/maestro/package.json index 29df46f3f31..12bd6ba89ec 100644 --- a/packages/maestro/package.json +++ b/packages/maestro/package.json @@ -44,7 +44,8 @@ "@agent-device/provision-kit": "workspace:*", "@agent-device/selectors": "workspace:*", "agent-device": "workspace:*", - "@agent-device/plugins": "workspace:*" + "@agent-device/plugins": "workspace:*", + "@eslint-community/regexpp": "4.12.2" }, "scripts": { "build": "tsdown --config ../../build/maestro/tsdown.config.ts", diff --git a/packages/maestro/src/internal/__tests__/selector-regex.test.ts b/packages/maestro/src/internal/__tests__/selector-regex.test.ts index ef53e98949b..932f8c7e9c3 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -7,6 +7,47 @@ test('matches Maestro regex as case-insensitive full patterns', () => { expect(matchesMaestroRegex('Item [ready', 'item [ready')).toBe(true); }); +const unsafe = { details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }) }; + +test.each([ + '(a+)+$', + '(a|a)+$', + '(a*)*b', + 'a*b*a*', + 'a+(?:|a)a+b', + String.raw`(\w+)\1`, + '(?=a)a', + '.*a.*b.*', + `${'a?'.repeat(40)}${'a'.repeat(40)}`, +])('refuses catastrophic pattern %s', (pattern) => { + expect(() => matchesMaestroRegex('aaaa', pattern)).toThrowError(expect.objectContaining(unsafe)); +}); + +test.each([ + [String.raw`\d+ of \d+`, '3 of 10'], + [String.raw`\w+ \w+`, 'Hello world'], + [String.raw`\S+ \S+`, 'Hello world'], + ['(Login|Sign in)', 'sign in'], + ['.*ready.*', 'Item is ready now'], +])('accepts common pattern %s', (pattern, value) => { + expect(matchesMaestroRegex(value, pattern)).toBe(true); +}); + +test('refuses regex patterns and values over the length caps', () => { + expect(() => matchesMaestroRegex('a', `${'a'.repeat(256)}.*`)).toThrowError( + expect.objectContaining(unsafe), + ); + expect(() => matchesMaestroRegex('a'.repeat(4097), 'a+')).toThrowError( + expect.objectContaining(unsafe), + ); +}); + +test('compares patterns without regex syntax as literals', () => { + const long = 'x'.repeat(1000); + expect(matchesMaestroRegex(long.toUpperCase(), long)).toBe(true); + expect(matchesMaestroRegex('y', long)).toBe(false); +}); + test('extracts only patterns that are exact literals', () => { expect(literalFromMaestroRegex('checkout-submit')).toBe('checkout-submit'); expect(literalFromMaestroRegex(String.raw`price\.usd`)).toBe('price.usd'); diff --git a/packages/maestro/src/internal/runtime-selector-resolution.ts b/packages/maestro/src/internal/runtime-selector-resolution.ts index c4b14cb9039..8f87f79a3ad 100644 --- a/packages/maestro/src/internal/runtime-selector-resolution.ts +++ b/packages/maestro/src/internal/runtime-selector-resolution.ts @@ -12,6 +12,7 @@ import { type MaestroPositionRelation, } from './runtime-target-position.ts'; import { matchesMaestroTypedSelector } from './runtime-target-policy.ts'; +import { assertMaestroRegexSupported } from './selector-regex.ts'; export type MaestroSelectorResolution = { /** Relation-composed matches in snapshot order, before this selector's own index. */ @@ -166,6 +167,9 @@ function resolveWithoutOwnIndex( containsDescendants, ...leaf } = selector; + for (const pattern of [leaf.id, leaf.text]) { + if (pattern !== undefined) assertMaestroRegexSupported(pattern); + } let matches = hasMaestroLeafSelectorFields(leaf) ? snapshot.nodes.filter((node) => matchesMaestroTypedSelector(node, leaf)) : [...snapshot.nodes]; diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index b03d0982561..c0d9e02431e 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -1,11 +1,165 @@ +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; +import { RegExpParser, visitRegExpAST, type AST } from '@eslint-community/regexpp'; + +export const MAESTRO_SELECTOR_REGEX_REASONS = { + // The selector pattern or the text matched against it exceeds the bounded matcher's limits. + unsafe: { reason: 'maestro_selector_regex_unsafe' }, +} as const satisfies ReasonTable<'maestro selector regex'>; + const REGEX_SYNTAX = new Set(String.raw`^$\.*+?()[]{}|`); +const MAX_PATTERN_LENGTH = 256; +const MAX_VALUE_LENGTH = 4096; +const MAX_PATHS = 32; +const MAX_CACHED_PATTERNS = 128; +const parser = new RegExpParser(); +type Element = AST.Alternative['elements'][number]; +const compiled = new Map(); export function matchesMaestroRegex(value: string, pattern: string): boolean { + const regex = compileMaestroRegex(pattern); + if (!regex) return value.toLocaleLowerCase() === pattern.toLocaleLowerCase(); + if (value.length > MAX_VALUE_LENGTH) unsafeMaestroRegex(); + return regex.test(value); +} + +/** Throws `maestro_selector_regex_unsafe` when the pattern cannot run within the bounded matcher. */ +export function assertMaestroRegexSupported(pattern: string): void { + compileMaestroRegex(pattern); +} + +function compileMaestroRegex(pattern: string): RegExp | undefined { + if (compiled.has(pattern)) return compiled.get(pattern); + let regex: RegExp | undefined; + if (hasRegexSyntax(pattern)) { + try { + regex = new RegExp(`^(?:${pattern})$`, 'ims'); + } catch { + regex = undefined; + } + if (regex) assertBoundedPattern(pattern); + } + if (compiled.size >= MAX_CACHED_PATTERNS) compiled.delete(compiled.keys().next().value!); + compiled.set(pattern, regex); + return regex; +} + +function hasRegexSyntax(pattern: string): boolean { + return [...pattern].some((character) => REGEX_SYNTAX.has(character)); +} + +function assertBoundedPattern(pattern: string): void { + if (pattern.length > MAX_PATTERN_LENGTH) unsafeMaestroRegex(); + let parsed: AST.Pattern; try { - return new RegExp(`^(?:${pattern})$`, 'ims').test(value); + parsed = parser.parsePattern(pattern); } catch { - return value.toLocaleLowerCase() === pattern.toLocaleLowerCase(); + unsafeMaestroRegex(); + } + visitRegExpAST(parsed, { + onBackreferenceEnter: unsafeMaestroRegex, + onAssertionEnter(node) { + if ('alternatives' in node) unsafeMaestroRegex(); + }, + onQuantifierEnter(node) { + if (!isGroup(node.element)) return; + if (node.max > node.min) unsafeMaestroRegex(); + visitRegExpAST(node.element, { + onGroupEnter: refuseAlternatives, + onCapturingGroupEnter: refuseAlternatives, + onQuantifierEnter: unsafeMaestroRegex, + }); + }, + }); + for (const path of expandPaths(parsed.alternatives)) assertDisjointRepetitions(path); +} + +function refuseAlternatives(group: AST.Group | AST.CapturingGroup): void { + if (group.alternatives.length > 1) unsafeMaestroRegex(); +} + +function isGroup(element: AST.Node): boolean { + return element.type === 'Group' || element.type === 'CapturingGroup'; +} + +function expandPaths(alternatives: AST.Alternative[]): Element[][] { + const paths: Element[][] = []; + for (const alternative of alternatives) { + let branches: Element[][] = [[]]; + for (const element of alternative.elements) { + const choices = + element.type === 'Group' || element.type === 'CapturingGroup' + ? expandPaths(element.alternatives) + : [[element]]; + branches = branches.flatMap((prefix) => choices.map((choice) => [...prefix, ...choice])); + if (branches.length > MAX_PATHS) unsafeMaestroRegex(); + } + paths.push(...branches); + } + if (paths.length > MAX_PATHS) unsafeMaestroRegex(); + return paths; +} + +// Two variable repetitions backtrack against each other when the left one can consume everything +// between them and the right atom overlaps the left atom. +function assertDisjointRepetitions(path: Element[]): void { + for (const [index, left] of path.entries()) { + if (!isVariable(left)) continue; + for (const next of path.slice(index + 1)) { + if (next.type === 'Assertion') continue; + const overlaps = atomsOverlap(left.element, next.type === 'Quantifier' ? next.element : next); + if (isVariable(next)) { + if (overlaps && !isTrailingWildcard(path, next)) unsafeMaestroRegex(); + if (next.min === 0 || overlaps) continue; + } else if (overlaps) { + continue; + } + break; + } + } +} + +function isVariable(element: Element): element is AST.Quantifier { + return element.type === 'Quantifier' && element.max > element.min; +} + +function isTrailingWildcard(path: Element[], quantifier: AST.Quantifier): boolean { + return ( + quantifier.element.type === 'CharacterSet' && + quantifier.element.kind === 'any' && + path.slice(path.indexOf(quantifier) + 1).every((element) => element.type === 'Assertion') + ); +} + +function atomsOverlap(left: AST.QuantifiableElement, right: AST.QuantifiableElement): boolean { + if (isGroup(left) || isGroup(right)) return true; + if (!isAsciiOnly(left) && !isAsciiOnly(right)) return true; + const leftMatcher = new RegExp(`^(?:${left.raw})$`, 'is'); + const rightMatcher = new RegExp(`^(?:${right.raw})$`, 'is'); + for (let codePoint = 0; codePoint < 128; codePoint += 1) { + const character = String.fromCharCode(codePoint); + if (leftMatcher.test(character) && rightMatcher.test(character)) return true; } + return false; +} + +function isAsciiOnly(element: AST.QuantifiableElement): boolean { + if (element.type === 'Character') return element.value < 128; + if (element.type === 'CharacterSet') { + return (element.kind === 'digit' || element.kind === 'word') && !element.negate; + } + if (element.type !== 'CharacterClass' || element.negate) return false; + return element.elements.every((part) => { + if (part.type === 'Character') return part.value < 128; + if (part.type === 'CharacterClassRange') return part.max.value < 128; + return part.type === 'CharacterSet' && isAsciiOnly(part); + }); +} + +function unsafeMaestroRegex(): never { + throw new AppError('INVALID_ARGS', 'Maestro selector regular expression is too complex.', { + reason: MAESTRO_SELECTOR_REGEX_REASONS.unsafe.reason, + retriable: false, + }); } export function literalFromMaestroRegex(pattern: string): string | undefined { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 633a1c54e9f..67b50e11861 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -739,6 +739,9 @@ importers: '@agent-device/test-kit': specifier: workspace:* version: link:../test-kit + '@eslint-community/regexpp': + specifier: 4.12.2 + version: 4.12.2 agent-device: specifier: workspace:* version: link:../.. diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 33c3d3f084f..eedf8937e0d 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -1022,6 +1022,12 @@ These reasons can come from more than one command. | `event_creation_failed` | macOS could not create the keyboard or mouse event to post. | | `missing_button` | No button on the alert fits the requested accept or dismiss. | +### Maestro selector regex + +| Reason | Meaning | +| --- | --- | +| `maestro_selector_regex_unsafe` | The selector pattern or the text matched against it exceeds the bounded matcher's limits. | + ### Metro reload | Reason | Meaning | diff --git a/website/docs/docs/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index 5abf91b7802..0eebedfa8da 100644 --- a/website/docs/docs/run-maestro-flows.md +++ b/website/docs/docs/run-maestro-flows.md @@ -42,6 +42,7 @@ Keep the target binding, such as `--platform ios`, on the `replay` or `test` com ## Boundaries +- Selector `id` and `text`: a pattern without regex syntax is a case-insensitive literal. A regex pattern is limited to 256 characters and the matched text to 4096 characters. Backreferences, lookahead, lookbehind, quantified groups with alternatives or repetitions, and overlapping repetitions such as `a*b*a*` fail the step with `maestro_selector_regex_unsafe`. - Permissions: every entry is one `settings permission` call, applied in order with `all` first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so `location: inuse` and `location: never` mean `allow` and `deny` there, while `location: always` and `photos: limited` are Apple-only and fail. On iOS simulators, `grant`, `deny`, or `reset` on `notifications` returns `ios-notification-permission-unsupported`. Answer the notification prompt with the CLI command `alert accept` or `alert dismiss`, which this Maestro subset does not include. For `all`, `simctl privacy` determines which services the runtime can change, and current runtimes leave notifications untouched. - Runtime: iOS and Android only; `launchApp.clearState` and standalone `clearState` support Android and iOS simulators, launch arguments are Apple-only (a map-form argument key gains a leading `-` unless its value is a boolean, as in Maestro), and other standalone device utility/state commands are unsupported. - Expressions: `evalScript` and condition `true:` fields (`runFlow.when` and `repeat.while` share one evaluator) are evaluated as JavaScript (flow `env` and prior `output` leaves are string-typed); a `true:` field that is a boolean, a `maestro.platform` comparison, or plain literal text after `${VAR}` lookups is decided without JavaScript, with the `assertTrue` falsy table for literal text. Other fields stay literal or `${VAR}` lookup-only — `assertTrue` supports literals and bare lookups, and other expression-shaped payloads fail loud. From ea1801102f8bc5348e843f12b85c38b1dcdf14f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 09:05:33 +0100 Subject: [PATCH 2/8] fix(maestro): match selector regexes with linear-time RE2 Replace the ambiguous-quantifier checker with re2js. Each selector value compiles once before the snapshot scan; backreferences, lookaround, and regex patterns over 256 characters fail with maestro_selector_regex_unsafe. The value length cap is gone, so long labels stay matchable. --- build/maestro/tsdown.config.ts | 2 +- packages/maestro/package.json | 2 +- .../__tests__/runtime-target-policy.test.ts | 34 ++-- .../internal/__tests__/selector-regex.test.ts | 78 ++++----- .../maestro/src/internal/facade-execution.ts | 4 +- .../internal/runtime-selector-resolution.ts | 12 +- .../src/internal/runtime-target-policy.ts | 34 ++-- .../maestro/src/internal/selector-regex.ts | 159 +++--------------- pnpm-lock.yaml | 12 +- website/docs/docs/error-reasons.md | 2 +- website/docs/docs/run-maestro-flows.md | 2 +- 11 files changed, 119 insertions(+), 222 deletions(-) diff --git a/build/maestro/tsdown.config.ts b/build/maestro/tsdown.config.ts index 802aa2a5357..bc18f071529 100644 --- a/build/maestro/tsdown.config.ts +++ b/build/maestro/tsdown.config.ts @@ -26,7 +26,7 @@ export default defineConfig({ deps: { neverBundle: ['agent-device/plugins'], alwaysBundle: [/^@agent-device\//], - onlyBundle: ['yaml', 'undici', 'ipaddr.js', 'pngjs', 'jpeg-js', '@eslint-community/regexpp'], + onlyBundle: ['yaml', 'undici', 'ipaddr.js', 'pngjs', 'jpeg-js', 're2js'], }, inputOptions: { onLog(level, log, handler) { diff --git a/packages/maestro/package.json b/packages/maestro/package.json index 12bd6ba89ec..82d852c1116 100644 --- a/packages/maestro/package.json +++ b/packages/maestro/package.json @@ -45,7 +45,7 @@ "@agent-device/selectors": "workspace:*", "agent-device": "workspace:*", "@agent-device/plugins": "workspace:*", - "@eslint-community/regexpp": "4.12.2" + "re2js": "2.10.0" }, "scripts": { "build": "tsdown --config ../../build/maestro/tsdown.config.ts", diff --git a/packages/maestro/src/internal/__tests__/runtime-target-policy.test.ts b/packages/maestro/src/internal/__tests__/runtime-target-policy.test.ts index e2a5972c4d3..a36e982f420 100644 --- a/packages/maestro/src/internal/__tests__/runtime-target-policy.test.ts +++ b/packages/maestro/src/internal/__tests__/runtime-target-policy.test.ts @@ -1,8 +1,14 @@ import { expect, test } from 'vitest'; -import { matchesMaestroTypedSelector } from '../runtime-target-policy.ts'; +import { compileMaestroSelector, matchesMaestroTypedSelector } from '../runtime-target-policy.ts'; +import type { MaestroFlatSelector } from '../runtime-target-policy.ts'; import type { MaestroSelector } from '../program-ir.ts'; import { makeSnapshot } from './runtime-target-fixtures.ts'; +const matches = ( + node: Parameters[0], + selector: MaestroFlatSelector, +) => matchesMaestroTypedSelector(node, compileMaestroSelector(selector)); + test('typed Maestro text selectors match visible text and state without expression strings', () => { const node = makeSnapshot([ { @@ -14,10 +20,8 @@ test('typed Maestro text selectors match visible text and state without expressi }, ]).nodes[0]!; - expect( - matchesMaestroTypedSelector(node, { text: '^Subtotal.*', enabled: true, selected: true }), - ).toBe(true); - expect(matchesMaestroTypedSelector(node, { text: 'Subtotal', selected: false })).toBe(false); + expect(matches(node, { text: '^Subtotal.*', enabled: true, selected: true })).toBe(true); + expect(matches(node, { text: 'Subtotal', selected: false })).toBe(false); }); test('typed Maestro id and text selectors keep their primary field semantics', () => { @@ -30,9 +34,9 @@ test('typed Maestro id and text selectors keep their primary field semantics', ( }, ]).nodes[0]!; - expect(matchesMaestroTypedSelector(node, { id: 'checkout-submit' })).toBe(true); - expect(matchesMaestroTypedSelector(node, { text: 'Submit' })).toBe(false); - expect(matchesMaestroTypedSelector(node, { text: '^Submit.*' })).toBe(true); + expect(matches(node, { id: 'checkout-submit' })).toBe(true); + expect(matches(node, { text: 'Submit' })).toBe(false); + expect(matches(node, { text: '^Submit.*' })).toBe(true); }); test('intersects every field in a compound Maestro selector', () => { @@ -47,15 +51,13 @@ test('intersects every field in a compound Maestro selector', () => { ]).nodes[0]!; expect( - matchesMaestroTypedSelector(node, { + matches(node, { id: 'checkout-submit', text: 'Submit order', enabled: true, }), ).toBe(true); - expect(matchesMaestroTypedSelector(node, { id: 'checkout-submit', text: 'Cancel order' })).toBe( - false, - ); + expect(matches(node, { id: 'checkout-submit', text: 'Cancel order' })).toBe(false); }); test('treats selector values as full Maestro regex without punctuation inference', () => { @@ -67,9 +69,9 @@ test('treats selector values as full Maestro regex without punctuation inference }, ]).nodes[0]!; - expect(matchesMaestroTypedSelector(node, { text: 'item \\d{2} \\[ready' })).toBe(true); - expect(matchesMaestroTypedSelector(node, { text: 'Item 2' })).toBe(false); - expect(matchesMaestroTypedSelector(node, { text: 'Item 22 [ready' })).toBe(true); + expect(matches(node, { text: 'item \\d{2} \\[ready' })).toBe(true); + expect(matches(node, { text: 'Item 2' })).toBe(false); + expect(matches(node, { text: 'Item 22 [ready' })).toBe(true); }); test('the node-only matcher rejects full selectors at the type boundary', () => { @@ -78,7 +80,7 @@ test('the node-only matcher rejects full selectors at the type boundary', () => void (() => { // @ts-expect-error Recursive selectors require snapshot-aware resolution. - matchesMaestroTypedSelector(node, recursiveSelector); + compileMaestroSelector(recursiveSelector); }); expect(node.label).toBe('Save'); }); diff --git a/packages/maestro/src/internal/__tests__/selector-regex.test.ts b/packages/maestro/src/internal/__tests__/selector-regex.test.ts index 932f8c7e9c3..da50d44531e 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -1,52 +1,54 @@ import { expect, test } from 'vitest'; -import { literalFromMaestroRegex, matchesMaestroRegex } from '../selector-regex.ts'; +import { compileMaestroRegex, literalFromMaestroRegex } from '../selector-regex.ts'; -test('matches Maestro regex as case-insensitive full patterns', () => { - expect(matchesMaestroRegex('Item 22\nready', String.raw`item \d{2}.+ready`)).toBe(true); - expect(matchesMaestroRegex('Item 22 ready later', 'Item 22 ready')).toBe(false); - expect(matchesMaestroRegex('Item [ready', 'item [ready')).toBe(true); -}); - -const unsafe = { details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }) }; +const matches = (value: string, pattern: string) => compileMaestroRegex(pattern)(value); test.each([ - '(a+)+$', - '(a|a)+$', - '(a*)*b', - 'a*b*a*', - 'a+(?:|a)a+b', - String.raw`(\w+)\1`, - '(?=a)a', - '.*a.*b.*', - `${'a?'.repeat(40)}${'a'.repeat(40)}`, -])('refuses catastrophic pattern %s', (pattern) => { - expect(() => matchesMaestroRegex('aaaa', pattern)).toThrowError(expect.objectContaining(unsafe)); + [String.raw`item \d{2}.+ready`, 'Item 22\nready'], + [String.raw`Item \d+`, 'header\nItem 22\nfooter'], + ['^item.$', 'ITEM\n'], + ['item 2(2|3)', 'Item 22 ready later'], + [String.raw`caf\u00e9`, 'CAFÉ'], +])('maps %s to the JavaScript ^(?:pattern)$ ims result', (pattern, value) => { + expect(matches(value, pattern)).toBe(new RegExp(`^(?:${pattern})$`, 'ims').test(value)); +}); + +test('compares invalid JavaScript patterns and patterns without regex syntax as literals', () => { + expect(matches('Item [ready', 'item [ready')).toBe(true); + const long = 'x'.repeat(1000); + expect(matches(long.toUpperCase(), long)).toBe(true); + expect(matches('y', long)).toBe(false); }); test.each([ + ['.*Welcome.*back.*', 'Oh, welcome Ann, glad to have you back!'], + ['Welcome( back)?', 'Welcome back'], + ['(Sign in|Log in)', 'log in'], [String.raw`\d+ of \d+`, '3 of 10'], - [String.raw`\w+ \w+`, 'Hello world'], - [String.raw`\S+ \S+`, 'Hello world'], - ['(Login|Sign in)', 'sign in'], - ['.*ready.*', 'Item is ready now'], -])('accepts common pattern %s', (pattern, value) => { - expect(matchesMaestroRegex(value, pattern)).toBe(true); + ['.*ready', `${'x'.repeat(10_000)} ready`], +])('matches %s', (pattern, value) => { + expect(matches(value, pattern)).toBe(true); }); -test('refuses regex patterns and values over the length caps', () => { - expect(() => matchesMaestroRegex('a', `${'a'.repeat(256)}.*`)).toThrowError( - expect.objectContaining(unsafe), - ); - expect(() => matchesMaestroRegex('a'.repeat(4097), 'a+')).toThrowError( - expect.objectContaining(unsafe), - ); -}); +test.each(['(a+)+$', '(a|a)*b'])( + 'matches %s over a non-matching input in linear time', + (pattern) => { + const started = performance.now(); + expect(matches(`${'a'.repeat(30)}!`, pattern)).toBe(false); + expect(performance.now() - started).toBeLessThan(100); + }, +); -test('compares patterns without regex syntax as literals', () => { - const long = 'x'.repeat(1000); - expect(matchesMaestroRegex(long.toUpperCase(), long)).toBe(true); - expect(matchesMaestroRegex('y', long)).toBe(false); -}); +test.each([String.raw`(\w+)\1`, '(?=a)a', '(?<=a)b', `${'a'.repeat(256)}.*`])( + 'refuses %s with the typed reason', + (pattern) => { + expect(() => compileMaestroRegex(pattern)).toThrowError( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); + }, +); test('extracts only patterns that are exact literals', () => { expect(literalFromMaestroRegex('checkout-submit')).toBe('checkout-submit'); diff --git a/packages/maestro/src/internal/facade-execution.ts b/packages/maestro/src/internal/facade-execution.ts index 7295fde20c8..4af0fe4adfd 100644 --- a/packages/maestro/src/internal/facade-execution.ts +++ b/packages/maestro/src/internal/facade-execution.ts @@ -26,7 +26,7 @@ import { resolveMaestroReplayStartIndex, } from './replay-plan.ts'; import type { MaestroReplayPlan } from './replay-plan-types.ts'; -import { matchesMaestroTypedSelector } from './runtime-target-policy.ts'; +import { compileMaestroSelector, matchesMaestroTypedSelector } from './runtime-target-policy.ts'; import { rankMaestroCandidates } from './runtime-target-ranking.ts'; const flowProgram = Symbol('maestroFlowProgram'); @@ -307,7 +307,7 @@ function suggestionBasis( selector.text !== undefined && matchesMaestroTypedSelector( { ...node, label: undefined, value: undefined }, - { text: selector.text }, + compileMaestroSelector({ text: selector.text }), ) ) { return 'id'; diff --git a/packages/maestro/src/internal/runtime-selector-resolution.ts b/packages/maestro/src/internal/runtime-selector-resolution.ts index 8f87f79a3ad..3742268bab9 100644 --- a/packages/maestro/src/internal/runtime-selector-resolution.ts +++ b/packages/maestro/src/internal/runtime-selector-resolution.ts @@ -11,8 +11,7 @@ import { selectMaestroPositionMatches, type MaestroPositionRelation, } from './runtime-target-position.ts'; -import { matchesMaestroTypedSelector } from './runtime-target-policy.ts'; -import { assertMaestroRegexSupported } from './selector-regex.ts'; +import { compileMaestroSelector, matchesMaestroTypedSelector } from './runtime-target-policy.ts'; export type MaestroSelectorResolution = { /** Relation-composed matches in snapshot order, before this selector's own index. */ @@ -167,12 +166,11 @@ function resolveWithoutOwnIndex( containsDescendants, ...leaf } = selector; - for (const pattern of [leaf.id, leaf.text]) { - if (pattern !== undefined) assertMaestroRegexSupported(pattern); + let matches = [...snapshot.nodes]; + if (hasMaestroLeafSelectorFields(leaf)) { + const matcher = compileMaestroSelector(leaf); + matches = matches.filter((node) => matchesMaestroTypedSelector(node, matcher)); } - let matches = hasMaestroLeafSelectorFields(leaf) - ? snapshot.nodes.filter((node) => matchesMaestroTypedSelector(node, leaf)) - : [...snapshot.nodes]; if (childOf) { const parentIndexes = new Set(resolve(childOf).indexed.map((node) => node.index)); diff --git a/packages/maestro/src/internal/runtime-target-policy.ts b/packages/maestro/src/internal/runtime-target-policy.ts index bc025276802..c877ae38a06 100644 --- a/packages/maestro/src/internal/runtime-target-policy.ts +++ b/packages/maestro/src/internal/runtime-target-policy.ts @@ -5,12 +5,26 @@ export type MaestroFlatSelector = MaestroLeafSelector & { }; import type { SnapshotNode } from '@agent-device/kernel/snapshot'; import type { SnapshotVisibility } from '@agent-device/contracts/snapshot'; -import { matchesMaestroRegex } from './selector-regex.ts'; +import { compileMaestroRegex, type MaestroTextMatcher } from './selector-regex.ts'; import { extractNodeText, normalizeText } from './shared.ts'; import { isMaestroNodeVisible } from './snapshot-policy.ts'; export type MaestroRuntimePlatform = 'ios' | 'android'; +export type MaestroSelectorMatcher = Omit & { + id: MaestroTextMatcher | undefined; + text: MaestroTextMatcher | undefined; +}; + +/** Compiles selector values once before a snapshot scan. */ +export function compileMaestroSelector(selector: MaestroFlatSelector): MaestroSelectorMatcher { + return { + ...selector, + id: selector.id === undefined ? undefined : compileMaestroSelectorValue(selector.id), + text: selector.text === undefined ? undefined : compileMaestroSelectorValue(selector.text), + }; +} + /** * Match the source-preserving selector IR directly. In particular, this does * not lower the selector to the legacy `key=value` expression grammar. @@ -23,12 +37,10 @@ export type MaestroRuntimePlatform = 'ios' | 'android'; */ export function matchesMaestroTypedSelector( node: SnapshotNode, - selector: MaestroFlatSelector, + selector: MaestroSelectorMatcher, ): boolean { const textTerms = [ - selector.id === undefined - ? undefined - : matchesMaestroSelectorValue(node.identifier, selector.id), + selector.id?.(node.identifier ?? ''), selector.text === undefined ? undefined : matchesMaestroVisibleText(node, selector.text), ].filter((matched): matched is boolean => matched !== undefined); if (textTerms.length === 0 && selector.enabled === undefined && selector.selected === undefined) { @@ -55,16 +67,14 @@ export function filterVisibleMaestroMatches(params: { ); } -function matchesMaestroSelectorValue(value: string | undefined, query: string): boolean { - const text = value ?? ''; - const normalizedText = normalizeText(text); +function compileMaestroSelectorValue(query: string): MaestroTextMatcher { const normalizedQuery = normalizeText(query); - if (normalizedText === normalizedQuery) return true; - return matchesMaestroRegex(text, query); + const matchesRegex = compileMaestroRegex(query); + return (value) => normalizeText(value) === normalizedQuery || matchesRegex(value); } -function matchesMaestroVisibleText(node: SnapshotNode, query: string): boolean { +function matchesMaestroVisibleText(node: SnapshotNode, matches: MaestroTextMatcher): boolean { return [node.label, extractNodeText(node), node.identifier] .filter((value): value is string => Boolean(value)) - .some((value) => matchesMaestroSelectorValue(value, query)); + .some(matches); } diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index c0d9e02431e..6c9bcc50709 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -1,162 +1,41 @@ import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; -import { RegExpParser, visitRegExpAST, type AST } from '@eslint-community/regexpp'; +import { RE2JS } from 're2js'; export const MAESTRO_SELECTOR_REGEX_REASONS = { - // The selector pattern or the text matched against it exceeds the bounded matcher's limits. + // The selector pattern exceeds 256 characters or needs backreferences or lookaround. unsafe: { reason: 'maestro_selector_regex_unsafe' }, } as const satisfies ReasonTable<'maestro selector regex'>; const REGEX_SYNTAX = new Set(String.raw`^$\.*+?()[]{}|`); const MAX_PATTERN_LENGTH = 256; -const MAX_VALUE_LENGTH = 4096; -const MAX_PATHS = 32; -const MAX_CACHED_PATTERNS = 128; -const parser = new RegExpParser(); -type Element = AST.Alternative['elements'][number]; -const compiled = new Map(); +// Same matches as JavaScript RegExp `^(?:pattern)$` with the `ims` flags. +const MAESTRO_REGEX_FLAGS = RE2JS.CASE_INSENSITIVE | RE2JS.MULTILINE | RE2JS.DOTALL; -export function matchesMaestroRegex(value: string, pattern: string): boolean { - const regex = compileMaestroRegex(pattern); - if (!regex) return value.toLocaleLowerCase() === pattern.toLocaleLowerCase(); - if (value.length > MAX_VALUE_LENGTH) unsafeMaestroRegex(); - return regex.test(value); -} - -/** Throws `maestro_selector_regex_unsafe` when the pattern cannot run within the bounded matcher. */ -export function assertMaestroRegexSupported(pattern: string): void { - compileMaestroRegex(pattern); -} +export type MaestroTextMatcher = (value: string) => boolean; -function compileMaestroRegex(pattern: string): RegExp | undefined { - if (compiled.has(pattern)) return compiled.get(pattern); - let regex: RegExp | undefined; - if (hasRegexSyntax(pattern)) { - try { - regex = new RegExp(`^(?:${pattern})$`, 'ims'); - } catch { - regex = undefined; - } - if (regex) assertBoundedPattern(pattern); +/** Compiles a Maestro selector value to a linear-time matcher, or throws `maestro_selector_regex_unsafe`. */ +export function compileMaestroRegex(pattern: string): MaestroTextMatcher { + const literal = pattern.toLocaleLowerCase(); + const matchesLiteral = (value: string) => value.toLocaleLowerCase() === literal; + const anchored = `^(?:${pattern})$`; + if (![...pattern].some((character) => REGEX_SYNTAX.has(character))) return matchesLiteral; + try { + new RegExp(anchored, 'ims'); + } catch { + return matchesLiteral; } - if (compiled.size >= MAX_CACHED_PATTERNS) compiled.delete(compiled.keys().next().value!); - compiled.set(pattern, regex); - return regex; -} - -function hasRegexSyntax(pattern: string): boolean { - return [...pattern].some((character) => REGEX_SYNTAX.has(character)); -} - -function assertBoundedPattern(pattern: string): void { if (pattern.length > MAX_PATTERN_LENGTH) unsafeMaestroRegex(); - let parsed: AST.Pattern; + let regex: RE2JS; try { - parsed = parser.parsePattern(pattern); + regex = RE2JS.compile(RE2JS.translateRegExp(anchored), MAESTRO_REGEX_FLAGS); } catch { unsafeMaestroRegex(); } - visitRegExpAST(parsed, { - onBackreferenceEnter: unsafeMaestroRegex, - onAssertionEnter(node) { - if ('alternatives' in node) unsafeMaestroRegex(); - }, - onQuantifierEnter(node) { - if (!isGroup(node.element)) return; - if (node.max > node.min) unsafeMaestroRegex(); - visitRegExpAST(node.element, { - onGroupEnter: refuseAlternatives, - onCapturingGroupEnter: refuseAlternatives, - onQuantifierEnter: unsafeMaestroRegex, - }); - }, - }); - for (const path of expandPaths(parsed.alternatives)) assertDisjointRepetitions(path); -} - -function refuseAlternatives(group: AST.Group | AST.CapturingGroup): void { - if (group.alternatives.length > 1) unsafeMaestroRegex(); -} - -function isGroup(element: AST.Node): boolean { - return element.type === 'Group' || element.type === 'CapturingGroup'; -} - -function expandPaths(alternatives: AST.Alternative[]): Element[][] { - const paths: Element[][] = []; - for (const alternative of alternatives) { - let branches: Element[][] = [[]]; - for (const element of alternative.elements) { - const choices = - element.type === 'Group' || element.type === 'CapturingGroup' - ? expandPaths(element.alternatives) - : [[element]]; - branches = branches.flatMap((prefix) => choices.map((choice) => [...prefix, ...choice])); - if (branches.length > MAX_PATHS) unsafeMaestroRegex(); - } - paths.push(...branches); - } - if (paths.length > MAX_PATHS) unsafeMaestroRegex(); - return paths; -} - -// Two variable repetitions backtrack against each other when the left one can consume everything -// between them and the right atom overlaps the left atom. -function assertDisjointRepetitions(path: Element[]): void { - for (const [index, left] of path.entries()) { - if (!isVariable(left)) continue; - for (const next of path.slice(index + 1)) { - if (next.type === 'Assertion') continue; - const overlaps = atomsOverlap(left.element, next.type === 'Quantifier' ? next.element : next); - if (isVariable(next)) { - if (overlaps && !isTrailingWildcard(path, next)) unsafeMaestroRegex(); - if (next.min === 0 || overlaps) continue; - } else if (overlaps) { - continue; - } - break; - } - } -} - -function isVariable(element: Element): element is AST.Quantifier { - return element.type === 'Quantifier' && element.max > element.min; -} - -function isTrailingWildcard(path: Element[], quantifier: AST.Quantifier): boolean { - return ( - quantifier.element.type === 'CharacterSet' && - quantifier.element.kind === 'any' && - path.slice(path.indexOf(quantifier) + 1).every((element) => element.type === 'Assertion') - ); -} - -function atomsOverlap(left: AST.QuantifiableElement, right: AST.QuantifiableElement): boolean { - if (isGroup(left) || isGroup(right)) return true; - if (!isAsciiOnly(left) && !isAsciiOnly(right)) return true; - const leftMatcher = new RegExp(`^(?:${left.raw})$`, 'is'); - const rightMatcher = new RegExp(`^(?:${right.raw})$`, 'is'); - for (let codePoint = 0; codePoint < 128; codePoint += 1) { - const character = String.fromCharCode(codePoint); - if (leftMatcher.test(character) && rightMatcher.test(character)) return true; - } - return false; -} - -function isAsciiOnly(element: AST.QuantifiableElement): boolean { - if (element.type === 'Character') return element.value < 128; - if (element.type === 'CharacterSet') { - return (element.kind === 'digit' || element.kind === 'word') && !element.negate; - } - if (element.type !== 'CharacterClass' || element.negate) return false; - return element.elements.every((part) => { - if (part.type === 'Character') return part.value < 128; - if (part.type === 'CharacterClassRange') return part.max.value < 128; - return part.type === 'CharacterSet' && isAsciiOnly(part); - }); + return (value) => regex.test(value); } function unsafeMaestroRegex(): never { - throw new AppError('INVALID_ARGS', 'Maestro selector regular expression is too complex.', { + throw new AppError('INVALID_ARGS', 'Maestro selector regular expression is not supported.', { reason: MAESTRO_SELECTOR_REGEX_REASONS.unsafe.reason, retriable: false, }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 67b50e11861..780e3b3bf58 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -739,12 +739,12 @@ importers: '@agent-device/test-kit': specifier: workspace:* version: link:../test-kit - '@eslint-community/regexpp': - specifier: 4.12.2 - version: 4.12.2 agent-device: specifier: workspace:* version: link:../.. + re2js: + specifier: 2.10.0 + version: 2.10.0 undici: specifier: 7.30.1 version: 7.30.1 @@ -5291,6 +5291,10 @@ packages: radix3@1.1.2: resolution: {integrity: sha512-b484I/7b8rDEdSDKckSSBA8knMpcdsXudlE/LNL639wFoHKwLbEkQFZHWEYwDC0wa0FKUcCY+GAF73Z7wxNVFA==} + re2js@2.10.0: + resolution: {integrity: sha512-/P6FNnLbHjXJMRF1dPoZoVTyHvFcuVhbDpzml9DPMlbeErYlZ18GueAaG9GhYhAm/9AN7i7Y6crmDrLX0DeJ4Q==} + engines: {node: '>=20.0.0'} + readdirp@5.1.1: resolution: {integrity: sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==} engines: {node: '>= 20.19.0'} @@ -9883,6 +9887,8 @@ snapshots: radix3@1.1.2: {} + re2js@2.10.0: {} + readdirp@5.1.1: {} regex-recursion@6.0.2: diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index eedf8937e0d..4286038623d 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -1026,7 +1026,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | -| `maestro_selector_regex_unsafe` | The selector pattern or the text matched against it exceeds the bounded matcher's limits. | +| `maestro_selector_regex_unsafe` | The selector pattern exceeds 256 characters or needs backreferences or lookaround. | ### Metro reload diff --git a/website/docs/docs/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index 0eebedfa8da..c7ab2547d3e 100644 --- a/website/docs/docs/run-maestro-flows.md +++ b/website/docs/docs/run-maestro-flows.md @@ -42,7 +42,7 @@ Keep the target binding, such as `--platform ios`, on the `replay` or `test` com ## Boundaries -- Selector `id` and `text`: a pattern without regex syntax is a case-insensitive literal. A regex pattern is limited to 256 characters and the matched text to 4096 characters. Backreferences, lookahead, lookbehind, quantified groups with alternatives or repetitions, and overlapping repetitions such as `a*b*a*` fail the step with `maestro_selector_regex_unsafe`. +- Selector `id` and `text`: a pattern without regex syntax is a case-insensitive literal. A regex pattern runs on a linear-time engine and is limited to 256 characters. Backreferences, lookahead, and lookbehind fail the step with `maestro_selector_regex_unsafe`. - Permissions: every entry is one `settings permission` call, applied in order with `all` first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so `location: inuse` and `location: never` mean `allow` and `deny` there, while `location: always` and `photos: limited` are Apple-only and fail. On iOS simulators, `grant`, `deny`, or `reset` on `notifications` returns `ios-notification-permission-unsupported`. Answer the notification prompt with the CLI command `alert accept` or `alert dismiss`, which this Maestro subset does not include. For `all`, `simctl privacy` determines which services the runtime can change, and current runtimes leave notifications untouched. - Runtime: iOS and Android only; `launchApp.clearState` and standalone `clearState` support Android and iOS simulators, launch arguments are Apple-only (a map-form argument key gains a leading `-` unless its value is a boolean, as in Maestro), and other standalone device utility/state commands are unsupported. - Expressions: `evalScript` and condition `true:` fields (`runFlow.when` and `repeat.while` share one evaluator) are evaluated as JavaScript (flow `env` and prior `output` leaves are string-typed); a `true:` field that is a boolean, a `maestro.platform` comparison, or plain literal text after `${VAR}` lookups is decided without JavaScript, with the `assertTrue` falsy table for literal text. Other fields stay literal or `${VAR}` lookup-only — `assertTrue` supports literals and bare lookups, and other expression-shaped payloads fail loud. From 5aa5664ba11ab1fa81f9692ca24998d004815346 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 10:55:20 +0100 Subject: [PATCH 3/8] fix(maestro): keep literal selectors line-matching and failure reports safe on refused regexes --- .../internal/__tests__/selector-regex.test.ts | 17 ++++++ .../maestro/src/internal/facade-execution.ts | 15 ++++-- .../maestro/src/internal/selector-regex.ts | 52 +++++++++++++++---- 3 files changed, 69 insertions(+), 15 deletions(-) diff --git a/packages/maestro/src/internal/__tests__/selector-regex.test.ts b/packages/maestro/src/internal/__tests__/selector-regex.test.ts index da50d44531e..805432da499 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -20,6 +20,12 @@ test('compares invalid JavaScript patterns and patterns without regex syntax as expect(matches('y', long)).toBe(false); }); +test('matches a regex-free pattern against one line of multi-line text', () => { + expect(matches('Item 22\nready', 'item 22')).toBe(true); + expect(matches('header\r\nItem 22', 'ITEM 22')).toBe(true); + expect(matches('Item 223\nready', 'item 22')).toBe(false); +}); + test.each([ ['.*Welcome.*back.*', 'Oh, welcome Ann, glad to have you back!'], ['Welcome( back)?', 'Welcome back'], @@ -50,6 +56,17 @@ test.each([String.raw`(\w+)\1`, '(?=a)a', '(?<=a)b', `${'a'.repeat(256)}.*`])( }, ); +test('reports which limit a refused pattern exceeded', () => { + expect(() => compileMaestroRegex(`${'a'.repeat(300)}.*`)).toThrowError( + expect.objectContaining({ + details: expect.objectContaining({ limit: 'pattern_length', patternLength: 302 }), + }), + ); + expect(() => compileMaestroRegex('(?=a)a')).toThrowError( + expect.objectContaining({ details: expect.objectContaining({ limit: 'syntax' }) }), + ); +}); + test('extracts only patterns that are exact literals', () => { expect(literalFromMaestroRegex('checkout-submit')).toBe('checkout-submit'); expect(literalFromMaestroRegex(String.raw`price\.usd`)).toBe('price.usd'); diff --git a/packages/maestro/src/internal/facade-execution.ts b/packages/maestro/src/internal/facade-execution.ts index 4af0fe4adfd..286b4326031 100644 --- a/packages/maestro/src/internal/facade-execution.ts +++ b/packages/maestro/src/internal/facade-execution.ts @@ -28,6 +28,7 @@ import { import type { MaestroReplayPlan } from './replay-plan-types.ts'; import { compileMaestroSelector, matchesMaestroTypedSelector } from './runtime-target-policy.ts'; import { rankMaestroCandidates } from './runtime-target-ranking.ts'; +import { isUnsafeMaestroRegexError } from './selector-regex.ts'; const flowProgram = Symbol('maestroFlowProgram'); const failureCommand = Symbol('maestroFailureCommand'); @@ -190,10 +191,16 @@ export function collectMaestroFailureSuggestions( const query = suggestionQuery(failure[failureCommand]); const platform = failure[failurePlan].platform; if (!query || (platform !== 'android' && platform !== 'ios')) return []; - return rankMaestroCandidates(snapshot, query.selector, platform).ranked.map((node) => ({ - node, - basis: suggestionBasis(query.selector, node), - })); + try { + return rankMaestroCandidates(snapshot, query.selector, platform).ranked.map((node) => ({ + node, + basis: suggestionBasis(query.selector, node), + })); + } catch (error) { + // The step already failed on this selector. The report keeps that failure and lists no suggestions. + if (isUnsafeMaestroRegexError(error)) return []; + throw error; + } } function createObserver( diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index 6c9bcc50709..aa0f47430d1 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -1,13 +1,14 @@ import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { RE2JS } from 're2js'; -export const MAESTRO_SELECTOR_REGEX_REASONS = { +const MAESTRO_SELECTOR_REGEX_REASONS = { // The selector pattern exceeds 256 characters or needs backreferences or lookaround. unsafe: { reason: 'maestro_selector_regex_unsafe' }, } as const satisfies ReasonTable<'maestro selector regex'>; const REGEX_SYNTAX = new Set(String.raw`^$\.*+?()[]{}|`); const MAX_PATTERN_LENGTH = 256; +const LINE_TERMINATOR = /[\n\r\u2028\u2029]/; // Same matches as JavaScript RegExp `^(?:pattern)$` with the `ims` flags. const MAESTRO_REGEX_FLAGS = RE2JS.CASE_INSENSITIVE | RE2JS.MULTILINE | RE2JS.DOTALL; @@ -16,29 +17,58 @@ export type MaestroTextMatcher = (value: string) => boolean; /** Compiles a Maestro selector value to a linear-time matcher, or throws `maestro_selector_regex_unsafe`. */ export function compileMaestroRegex(pattern: string): MaestroTextMatcher { const literal = pattern.toLocaleLowerCase(); - const matchesLiteral = (value: string) => value.toLocaleLowerCase() === literal; const anchored = `^(?:${pattern})$`; - if (![...pattern].some((character) => REGEX_SYNTAX.has(character))) return matchesLiteral; + if (![...pattern].some((character) => REGEX_SYNTAX.has(character))) { + // Matches a whole line, like `^`/`$` under the multiline flag. + return (value) => { + const lowered = value.toLocaleLowerCase(); + return lowered === literal || lowered.split(LINE_TERMINATOR).includes(literal); + }; + } try { new RegExp(anchored, 'ims'); } catch { - return matchesLiteral; + return (value) => value.toLocaleLowerCase() === literal; + } + if (pattern.length > MAX_PATTERN_LENGTH) { + unsafeMaestroRegex({ + limit: 'pattern_length', + patternLength: pattern.length, + maxPatternLength: MAX_PATTERN_LENGTH, + }); } - if (pattern.length > MAX_PATTERN_LENGTH) unsafeMaestroRegex(); let regex: RE2JS; try { regex = RE2JS.compile(RE2JS.translateRegExp(anchored), MAESTRO_REGEX_FLAGS); } catch { - unsafeMaestroRegex(); + unsafeMaestroRegex({ limit: 'syntax' }); } return (value) => regex.test(value); } -function unsafeMaestroRegex(): never { - throw new AppError('INVALID_ARGS', 'Maestro selector regular expression is not supported.', { - reason: MAESTRO_SELECTOR_REGEX_REASONS.unsafe.reason, - retriable: false, - }); +function unsafeMaestroRegex( + limit: + | { limit: 'pattern_length'; patternLength: number; maxPatternLength: number } + | { limit: 'syntax' }, +): never { + throw new AppError( + 'INVALID_ARGS', + limit.limit === 'syntax' + ? 'Maestro selector regular expression uses unsupported syntax (backreference, lookahead, or lookbehind).' + : `Maestro selector regular expression is longer than ${MAX_PATTERN_LENGTH} characters.`, + { + reason: MAESTRO_SELECTOR_REGEX_REASONS.unsafe.reason, + retriable: false, + ...limit, + }, + ); +} + +export function isUnsafeMaestroRegexError(error: unknown): boolean { + return ( + error instanceof AppError && + error.details?.reason === MAESTRO_SELECTOR_REGEX_REASONS.unsafe.reason + ); } export function literalFromMaestroRegex(pattern: string): string | undefined { From d05fa1fdbdc0903d785b7eba1f5e085faf7f0463 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 11:09:20 +0100 Subject: [PATCH 4/8] fix(maestro): anchor selector regex on every line terminator and compile suggestions once --- .../src/internal/__tests__/selector-regex.test.ts | 7 +++++++ packages/maestro/src/internal/facade-execution.ts | 14 ++++++++------ packages/maestro/src/internal/selector-regex.ts | 4 +++- 3 files changed, 18 insertions(+), 7 deletions(-) diff --git a/packages/maestro/src/internal/__tests__/selector-regex.test.ts b/packages/maestro/src/internal/__tests__/selector-regex.test.ts index 805432da499..8d02f9b482b 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -73,3 +73,10 @@ test('extracts only patterns that are exact literals', () => { expect(literalFromMaestroRegex(String.raw`item \d{2}`)).toBeUndefined(); expect(literalFromMaestroRegex('item [ready')).toBe('item [ready'); }); + +test('anchors on every JavaScript line terminator', () => { + const matches = compileMaestroRegex('^Save$'); + for (const terminator of ['\r\n', '\r', '\u2028', '\u2029']) { + expect(matches(`Save${terminator}Now`)).toBe(true); + } +}); diff --git a/packages/maestro/src/internal/facade-execution.ts b/packages/maestro/src/internal/facade-execution.ts index 286b4326031..b9f08890ecf 100644 --- a/packages/maestro/src/internal/facade-execution.ts +++ b/packages/maestro/src/internal/facade-execution.ts @@ -192,9 +192,13 @@ export function collectMaestroFailureSuggestions( const platform = failure[failurePlan].platform; if (!query || (platform !== 'android' && platform !== 'ios')) return []; try { + const textSelector = + query.selector.id === undefined && query.selector.text !== undefined + ? compileMaestroSelector({ text: query.selector.text }) + : undefined; return rankMaestroCandidates(snapshot, query.selector, platform).ranked.map((node) => ({ node, - basis: suggestionBasis(query.selector, node), + basis: suggestionBasis(query.selector, textSelector, node), })); } catch (error) { // The step already failed on this selector. The report keeps that failure and lists no suggestions. @@ -307,15 +311,13 @@ function suggestionQuery(command: MaestroEngineEvent['command']): SuggestionQuer function suggestionBasis( selector: SuggestionQuery['selector'], + textSelector: ReturnType | undefined, node: SnapshotNode, ): 'id' | 'label' | 'other' { if (selector.id !== undefined) return 'id'; if ( - selector.text !== undefined && - matchesMaestroTypedSelector( - { ...node, label: undefined, value: undefined }, - compileMaestroSelector({ text: selector.text }), - ) + textSelector && + matchesMaestroTypedSelector({ ...node, label: undefined, value: undefined }, textSelector) ) { return 'id'; } diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index aa0f47430d1..ba6fc93ab3a 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -9,6 +9,7 @@ const MAESTRO_SELECTOR_REGEX_REASONS = { const REGEX_SYNTAX = new Set(String.raw`^$\.*+?()[]{}|`); const MAX_PATTERN_LENGTH = 256; const LINE_TERMINATOR = /[\n\r\u2028\u2029]/; +const LINE_TERMINATOR_RUN = /\r\n|[\r\u2028\u2029]/g; // Same matches as JavaScript RegExp `^(?:pattern)$` with the `ims` flags. const MAESTRO_REGEX_FLAGS = RE2JS.CASE_INSENSITIVE | RE2JS.MULTILINE | RE2JS.DOTALL; @@ -43,7 +44,8 @@ export function compileMaestroRegex(pattern: string): MaestroTextMatcher { } catch { unsafeMaestroRegex({ limit: 'syntax' }); } - return (value) => regex.test(value); + // RE2 anchors on `\n` only; JavaScript also breaks lines at `\r`, U+2028, and U+2029. + return (value) => regex.test(value.replace(LINE_TERMINATOR_RUN, '\n')); } function unsafeMaestroRegex( From 6f09604b642ea750257a46421be0e6eeb9958558 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 11:39:00 +0100 Subject: [PATCH 5/8] fix(maestro): normalize line terminators in selector patterns like values --- .../src/internal/__tests__/selector-regex.test.ts | 7 +++++++ packages/maestro/src/internal/selector-regex.ts | 13 ++++++++++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/packages/maestro/src/internal/__tests__/selector-regex.test.ts b/packages/maestro/src/internal/__tests__/selector-regex.test.ts index 8d02f9b482b..f07b97915de 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -80,3 +80,10 @@ test('anchors on every JavaScript line terminator', () => { expect(matches(`Save${terminator}Now`)).toBe(true); } }); + +test('matches patterns that name a line terminator', () => { + expect(matches('Line 1\r\nLine 2', 'Line 1\r\nLine 2')).toBe(true); + expect(matches('Line 1\r\nLine 2', String.raw`Line 1\r\nLine 2`)).toBe(true); + expect(matches('a
b', String.raw`a
b`)).toBe(true); + expect(matches('a\rb', 'a(\r|x)b')).toBe(true); +}); diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index ba6fc93ab3a..05beb42f36d 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -10,6 +10,8 @@ const REGEX_SYNTAX = new Set(String.raw`^$\.*+?()[]{}|`); const MAX_PATTERN_LENGTH = 256; const LINE_TERMINATOR = /[\n\r\u2028\u2029]/; const LINE_TERMINATOR_RUN = /\r\n|[\r\u2028\u2029]/g; +// A pattern names terminators raw or as `\r`/`\u2028` escapes; `\\` keeps an escaped backslash intact. +const PATTERN_TERMINATOR = /\\\\|\\r\\n|\\r|\\u202[89]|\r\n|[\r\u2028\u2029]/g; // Same matches as JavaScript RegExp `^(?:pattern)$` with the `ims` flags. const MAESTRO_REGEX_FLAGS = RE2JS.CASE_INSENSITIVE | RE2JS.MULTILINE | RE2JS.DOTALL; @@ -18,12 +20,17 @@ export type MaestroTextMatcher = (value: string) => boolean; /** Compiles a Maestro selector value to a linear-time matcher, or throws `maestro_selector_regex_unsafe`. */ export function compileMaestroRegex(pattern: string): MaestroTextMatcher { const literal = pattern.toLocaleLowerCase(); - const anchored = `^(?:${pattern})$`; + // Values are normalized to `\n`, so the pattern must name `\n` for its terminators too. + const normalized = pattern.replace(PATTERN_TERMINATOR, (match) => + match === '\\\\' ? match : '\n', + ); + const anchored = `^(?:${normalized})$`; if (![...pattern].some((character) => REGEX_SYNTAX.has(character))) { // Matches a whole line, like `^`/`$` under the multiline flag. + const wanted = normalized.toLocaleLowerCase(); return (value) => { - const lowered = value.toLocaleLowerCase(); - return lowered === literal || lowered.split(LINE_TERMINATOR).includes(literal); + const lowered = value.toLocaleLowerCase().replace(LINE_TERMINATOR_RUN, '\n'); + return lowered === wanted || lowered.split(LINE_TERMINATOR).includes(wanted); }; } try { From 35fdcfd957f2a82b0b50186eee192b6e08ec2211 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 11:45:11 +0100 Subject: [PATCH 6/8] style(maestro): use String.raw for the escaped backslash --- packages/maestro/src/internal/selector-regex.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index 05beb42f36d..42a934f7a1c 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -22,7 +22,7 @@ export function compileMaestroRegex(pattern: string): MaestroTextMatcher { const literal = pattern.toLocaleLowerCase(); // Values are normalized to `\n`, so the pattern must name `\n` for its terminators too. const normalized = pattern.replace(PATTERN_TERMINATOR, (match) => - match === '\\\\' ? match : '\n', + match === String.raw`\\` ? match : '\n', ); const anchored = `^(?:${normalized})$`; if (![...pattern].some((character) => REGEX_SYNTAX.has(character))) { From 2f27af802bda491e37a1c0df8e0be1ad5d184e14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 12:26:27 +0100 Subject: [PATCH 7/8] docs(maestro): document ASCII-only selector whitespace classes --- .../maestro/src/internal/__tests__/selector-regex.test.ts | 7 +++++++ packages/maestro/src/internal/selector-regex.ts | 2 +- website/docs/docs/run-maestro-flows.md | 1 + 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/maestro/src/internal/__tests__/selector-regex.test.ts b/packages/maestro/src/internal/__tests__/selector-regex.test.ts index f07b97915de..5bd6626af0c 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -87,3 +87,10 @@ test('matches patterns that name a line terminator', () => { expect(matches('a
b', String.raw`a
b`)).toBe(true); expect(matches('a\rb', 'a(\r|x)b')).toBe(true); }); + +test('matches whitespace classes against ASCII whitespace only, like Maestro', () => { + expect(matches('Hello World', String.raw`Hello\sWorld`)).toBe(true); + expect(matches('Hello\u00a0World', String.raw`Hello\sWorld`)).toBe(false); + expect(matches('10:30\u202fAM', String.raw`\d+:\d+\sAM`)).toBe(false); + expect(matches('a\u00a0b', String.raw`a\Sb`)).toBe(true); +}); diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index 42a934f7a1c..1bfda08d18a 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -63,7 +63,7 @@ function unsafeMaestroRegex( throw new AppError( 'INVALID_ARGS', limit.limit === 'syntax' - ? 'Maestro selector regular expression uses unsupported syntax (backreference, lookahead, or lookbehind).' + ? 'Maestro selector regular expression uses syntax the linear-time engine does not support (for example backreferences or lookaround).' : `Maestro selector regular expression is longer than ${MAX_PATTERN_LENGTH} characters.`, { reason: MAESTRO_SELECTOR_REGEX_REASONS.unsafe.reason, diff --git a/website/docs/docs/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index c7ab2547d3e..68718110a36 100644 --- a/website/docs/docs/run-maestro-flows.md +++ b/website/docs/docs/run-maestro-flows.md @@ -46,6 +46,7 @@ Keep the target binding, such as `--platform ios`, on the `replay` or `test` com - Permissions: every entry is one `settings permission` call, applied in order with `all` first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so `location: inuse` and `location: never` mean `allow` and `deny` there, while `location: always` and `photos: limited` are Apple-only and fail. On iOS simulators, `grant`, `deny`, or `reset` on `notifications` returns `ios-notification-permission-unsupported`. Answer the notification prompt with the CLI command `alert accept` or `alert dismiss`, which this Maestro subset does not include. For `all`, `simctl privacy` determines which services the runtime can change, and current runtimes leave notifications untouched. - Runtime: iOS and Android only; `launchApp.clearState` and standalone `clearState` support Android and iOS simulators, launch arguments are Apple-only (a map-form argument key gains a leading `-` unless its value is a boolean, as in Maestro), and other standalone device utility/state commands are unsupported. - Expressions: `evalScript` and condition `true:` fields (`runFlow.when` and `repeat.while` share one evaluator) are evaluated as JavaScript (flow `env` and prior `output` leaves are string-typed); a `true:` field that is a boolean, a `maestro.platform` comparison, or plain literal text after `${VAR}` lookups is decided without JavaScript, with the `assertTrue` falsy table for literal text. Other fields stay literal or `${VAR}` lookup-only — `assertTrue` supports literals and bare lookups, and other expression-shaped payloads fail loud. +- Selector regular expressions: `id` and `text` patterns run on a linear-time engine. `\s` and `\S` match ASCII whitespace only, as in Maestro, so a no-break space (U+00A0) or narrow no-break space (U+202F) in app text does not match `\s`. - Environment: flow `env` is the default, `AD_VAR_*` overrides it, and CLI `-e KEY=VALUE` wins over both; override keys follow the flow variable grammar (mixed case and dots allowed), and `AD_*` stays reserved. - Failure diagnostics: resolved targets and `runFlow` paths are rendered, while `inputText` payloads remain hidden; do not place secrets in diagnostic identifiers. - Trust: `runScript`, `evalScript`, and JavaScript condition `true:` fields execute flow scripts via `node:vm`, which is not a security sandbox. `runScript` runs in a daemon child process with a 30 s script budget. It may make `http.post` network requests (30 s each, response bodies up to 8 MiB), and its output keys cannot contain a dot. Remote flows refuse `runScript` before reading its file, including files supplied in the replay bundle, and refuse `evalScript` and `true:` fields that need JavaScript. Run these scripts only in trusted local flows. Local `runScript` paths refer to the daemon filesystem: relative paths resolve from the containing flow, and absolute paths and symlinks are allowed. From 5dbe1b8799c1845a8f9bc7892eb03052926ad83c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 12:51:06 +0100 Subject: [PATCH 8/8] fix(maestro): match multi-line literal selectors on line boundaries --- packages/maestro/src/internal/__tests__/selector-regex.test.ts | 2 ++ packages/maestro/src/internal/selector-regex.ts | 3 +-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/maestro/src/internal/__tests__/selector-regex.test.ts b/packages/maestro/src/internal/__tests__/selector-regex.test.ts index 5bd6626af0c..a0ad8a01425 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -84,6 +84,8 @@ test('anchors on every JavaScript line terminator', () => { test('matches patterns that name a line terminator', () => { expect(matches('Line 1\r\nLine 2', 'Line 1\r\nLine 2')).toBe(true); expect(matches('Line 1\r\nLine 2', String.raw`Line 1\r\nLine 2`)).toBe(true); + expect(matches('Header\nLine 1\nLine 2\nFooter', 'Line 1\nLine 2')).toBe(true); + expect(matches('Header\nLine 1\nLine 2x', 'Line 1\nLine 2')).toBe(false); expect(matches('a
b', String.raw`a
b`)).toBe(true); expect(matches('a\rb', 'a(\r|x)b')).toBe(true); }); diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index 1bfda08d18a..3cf1180e3a3 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -8,7 +8,6 @@ const MAESTRO_SELECTOR_REGEX_REASONS = { const REGEX_SYNTAX = new Set(String.raw`^$\.*+?()[]{}|`); const MAX_PATTERN_LENGTH = 256; -const LINE_TERMINATOR = /[\n\r\u2028\u2029]/; const LINE_TERMINATOR_RUN = /\r\n|[\r\u2028\u2029]/g; // A pattern names terminators raw or as `\r`/`\u2028` escapes; `\\` keeps an escaped backslash intact. const PATTERN_TERMINATOR = /\\\\|\\r\\n|\\r|\\u202[89]|\r\n|[\r\u2028\u2029]/g; @@ -30,7 +29,7 @@ export function compileMaestroRegex(pattern: string): MaestroTextMatcher { const wanted = normalized.toLocaleLowerCase(); return (value) => { const lowered = value.toLocaleLowerCase().replace(LINE_TERMINATOR_RUN, '\n'); - return lowered === wanted || lowered.split(LINE_TERMINATOR).includes(wanted); + return `\n${lowered}\n`.includes(`\n${wanted}\n`); }; } try {