From 1b759e83c73b1bea62bae8fed694c8ea91ea374b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 14:05:41 +0100 Subject: [PATCH 01/55] fix(client): refuse unsafe credential and replay inputs --- docs/adr/0041-credential-transport.md | 2 +- docs/agents/security.md | 2 +- .../contracts/src/credential-transport.ts | 3 +- ...lient-checked-rpc-connect-recovery.test.ts | 7 +- ...emon-client-lifecycle-remote-trust.test.ts | 67 +++++++------ ...ient-remote-health-recovery-budget.test.ts | 7 +- .../daemon-client/src/__tests__/index.test.ts | 4 + .../host-kit/src/credential-admission.test.ts | 94 +++++-------------- packages/host-kit/src/credential-admission.ts | 25 +---- .../__tests__/runtime-target-policy.test.ts | 8 +- .../__tests__/runtime-target-position.test.ts | 2 +- .../internal/__tests__/selector-regex.test.ts | 21 ++++- .../maestro/src/internal/selector-regex.ts | 48 ++++++++++ packages/proxy/README.md | 2 +- .../daemon-proxy-credential-transport.test.ts | 9 +- .../metro/client-metro-auto-companion.test.ts | 58 ++++++------ .../daemon-artifacts-capture.test.ts | 11 ++- packages/remote/src/daemon-artifacts.ts | 31 ++---- .../auth-session-cloud-transport.test.ts | 78 +++++++-------- src/commands/schema/cli-help.ts | 2 +- test/wire-compat/ledger.json | 6 +- website/docs/docs/error-reasons.md | 8 +- website/docs/docs/run-maestro-flows.md | 1 + 23 files changed, 251 insertions(+), 245 deletions(-) diff --git a/docs/adr/0041-credential-transport.md b/docs/adr/0041-credential-transport.md index c37b9a024da..4ea0727eaee 100644 --- a/docs/adr/0041-credential-transport.md +++ b/docs/adr/0041-credential-transport.md @@ -2,7 +2,7 @@ ## Status -Accepted (2026-11-28). Enforcement has not shipped yet; it is tracked in #5182. +Accepted (2026-11-28). Enforcement is implemented by `admitCredentialDestination`. ADR 0006 continues to govern checked RPC. ## Rules at a glance diff --git a/docs/agents/security.md b/docs/agents/security.md index f64ef197f22..711892dcd4d 100644 --- a/docs/agents/security.md +++ b/docs/agents/security.md @@ -2,7 +2,7 @@ The CLI client trusts its caller to choose local destinations. The client trusts a remote daemon for data and validated identifiers. -Scripts and remote record stop reject daemon paths (#4518). Trace and perf take them. +Remote downloads use client paths. Unnamed trace and perf files are unique in the client cwd. The daemon admits its state directory. Nobody trusts the network or other local users. Out of scope: same uid, hostile root, ACLs, mounts, untrusted filesystems. ADR 0041 owns credential transport. diff --git a/packages/contracts/src/credential-transport.ts b/packages/contracts/src/credential-transport.ts index 57fae3bde31..f12139ba57b 100644 --- a/packages/contracts/src/credential-transport.ts +++ b/packages/contracts/src/credential-transport.ts @@ -5,8 +5,7 @@ import { isLoopbackHostname } from './loopback-host.ts'; const CREDENTIAL_TRANSPORT_REASONS = { // A first-party credential would go to a configured URL that is neither https nor plain http to a // loopback host, and the CLI or SDK environment does not set - // AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1 (@agent-device/proxy has no override). agent-device - // 0.21.x warns on stderr instead of failing with it; 0.22 refuses with it before sending anything. + // AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1 (@agent-device/proxy has no override). insecureTransport: { reason: 'insecure_credential_transport' }, } as const satisfies ReasonTable<'remote connection'>; diff --git a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts index ff5455d08d8..67cccbd879e 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts @@ -5,7 +5,7 @@ import assert from 'node:assert/strict'; import http from 'node:http'; import { EventEmitter } from 'node:events'; -import { afterEach, test, vi } from 'vitest'; +import { afterEach, beforeEach, test, vi } from 'vitest'; import { isRequestCanceledError } from '@agent-device/kernel/errors'; import { sendToDaemon } from '../index.ts'; @@ -135,6 +135,10 @@ function driveFakeTime(): () => Promise { const BASE_URL = 'http://remote-mac.example.test:7777/agent-device'; +beforeEach(() => { + vi.stubEnv('AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT', '1'); +}); + let tokenSeq = 0; /** A token of its own per test: the process health cache is keyed by it. */ function freshToken(): string { @@ -152,6 +156,7 @@ function sessionList(daemonRpc?: 'checked') { } afterEach(() => { + vi.unstubAllEnvs(); vi.useRealTimers(); vi.restoreAllMocks(); }); diff --git a/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-trust.test.ts b/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-trust.test.ts index 4e5a0596aaf..543dbd7b872 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-trust.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-trust.test.ts @@ -1,46 +1,35 @@ -// A remote daemon token over plain http off loopback is warned about from the settings the client -// reads, before the first request leaves. - import assert from 'node:assert/strict'; import http from 'node:http'; import { afterEach, test, vi } from 'vitest'; -import { beginStderrCapture, createTestHostEnvironment } from '@agent-device/test-kit'; +import { createTestHostEnvironment } from '@agent-device/test-kit'; import { assertRemoteServesCheckedRpc } from '../index.ts'; +function isTransportRefusal(error: unknown): boolean { + const value = error as { code?: string; details?: { reason?: string } }; + return ( + value?.code === 'INVALID_ARGS' && value.details?.reason === 'insecure_credential_transport' + ); +} + afterEach(() => { vi.restoreAllMocks(); }); -/** The stderr written by the time the first request to `daemonBaseUrl` opens; nothing is sent. */ -async function stderrAtFirstSend( - daemonBaseUrl: string, - env: Record = {}, -): Promise { - const stderr = beginStderrCapture(); - let atSend: string | undefined; - vi.spyOn(http, 'request').mockImplementation(() => { - atSend ??= stderr.read(); - throw new Error('stop at the socket'); - }); - try { - await assert.rejects( - assertRemoteServesCheckedRpc( - { daemonBaseUrl, daemonAuthToken: 'remote-secret' }, - createTestHostEnvironment({ env }), - ), - ); - } finally { - stderr.restore(); - } - assert.ok(atSend !== undefined, 'the client never reached the socket'); - return atSend; -} +test('a plain http daemon off loopback is refused before the token leaves', async () => { + const request = vi.spyOn(http, 'request'); -test('a plain http daemon off loopback is warned about before the token leaves', async () => { - const warning = await stderrAtFirstSend('http://warned.example.test:7777/agent-device'); + await assert.rejects( + assertRemoteServesCheckedRpc( + { + daemonBaseUrl: 'http://fleet.example.test:7777/agent-device', + daemonAuthToken: 'remote-secret', + }, + createTestHostEnvironment({ env: {} }), + ), + isTransportRefusal, + ); - assert.match(warning, /http:\/\/warned\.example\.test:7777 are sent in cleartext/); - assert.doesNotMatch(warning, /remote-secret|agent-device\/health/); + assert.equal(request.mock.calls.length, 0); }); test.each([ @@ -50,6 +39,16 @@ test.each([ 'http://overridden.example.test:7777', { AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT: '1' }, ], -] as const)('%s is not warned about', async (_label, daemonBaseUrl, env) => { - assert.equal(await stderrAtFirstSend(daemonBaseUrl, env), ''); +] as const)('%s reaches the transport', async (_label, daemonBaseUrl, env) => { + const request = vi.spyOn(http, 'request').mockImplementation(() => { + throw new Error('stop at the socket'); + }); + + await assert.rejects( + assertRemoteServesCheckedRpc( + { daemonBaseUrl, daemonAuthToken: 'remote-secret' }, + createTestHostEnvironment({ env }), + ), + ); + assert.ok(request.mock.calls.length > 0); }); diff --git a/packages/daemon-client/src/__tests__/daemon-client-remote-health-recovery-budget.test.ts b/packages/daemon-client/src/__tests__/daemon-client-remote-health-recovery-budget.test.ts index c7b0a32862c..e1567b04b28 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-remote-health-recovery-budget.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-remote-health-recovery-budget.test.ts @@ -5,7 +5,7 @@ import assert from 'node:assert/strict'; import http from 'node:http'; import { EventEmitter } from 'node:events'; -import { afterEach, test, vi } from 'vitest'; +import { afterEach, beforeEach, test, vi } from 'vitest'; import { AppError, isRequestCanceledError } from '@agent-device/kernel/errors'; import { sendToDaemon } from '../index.ts'; @@ -71,7 +71,12 @@ function remoteSessionList() { }; } +beforeEach(() => { + vi.stubEnv('AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT', '1'); +}); + afterEach(() => { + vi.unstubAllEnvs(); vi.useRealTimers(); vi.restoreAllMocks(); }); diff --git a/packages/daemon-client/src/__tests__/index.test.ts b/packages/daemon-client/src/__tests__/index.test.ts index 89964dc5ee5..f4ae61cf8ef 100644 --- a/packages/daemon-client/src/__tests__/index.test.ts +++ b/packages/daemon-client/src/__tests__/index.test.ts @@ -509,6 +509,7 @@ test('sendToDaemon reuses reachable local HTTP daemon metadata with token params }); test('sendToDaemon uses explicit remote daemon base URL and auth token', async () => { + vi.stubEnv('AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT', '1'); let authHeader = ''; let tokenHeader = ''; let rpcRequest: Record | null = null; @@ -606,6 +607,7 @@ test('sendToDaemon uses explicit remote daemon base URL and auth token', async ( assert.equal((rpcRequest as any)?.params?.token, 'remote-secret'); assert.equal((rpcRequest as any)?.params?.flags?.daemonAuthToken, undefined); } finally { + vi.unstubAllEnvs(); (http as unknown as { request: typeof http.request }).request = originalHttpRequest; if (previousBaseUrl === undefined) delete process.env.AGENT_DEVICE_DAEMON_BASE_URL; else process.env.AGENT_DEVICE_DAEMON_BASE_URL = previousBaseUrl; @@ -708,6 +710,7 @@ test.each([ ); test('sendToDaemon sends lease helpers as top-level JSON-RPC methods over HTTP', async () => { + vi.stubEnv('AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT', '1'); const rpcRequests: Record[] = []; const originalHttpRequest = http.request; (http as unknown as { request: typeof http.request }).request = (( @@ -844,6 +847,7 @@ test('sendToDaemon sends lease helpers as top-level JSON-RPC methods over HTTP', leaseId: 'lease-new', }); } finally { + vi.unstubAllEnvs(); (http as unknown as { request: typeof http.request }).request = originalHttpRequest; if (previousBaseUrl === undefined) delete process.env.AGENT_DEVICE_DAEMON_BASE_URL; else process.env.AGENT_DEVICE_DAEMON_BASE_URL = previousBaseUrl; diff --git a/packages/host-kit/src/credential-admission.test.ts b/packages/host-kit/src/credential-admission.test.ts index 17cb41e7b50..fa51d86d9d4 100644 --- a/packages/host-kit/src/credential-admission.test.ts +++ b/packages/host-kit/src/credential-admission.test.ts @@ -1,76 +1,28 @@ -import { afterEach, beforeEach, expect, test, vi } from 'vitest'; +import { expect, test } from 'vitest'; import { admitCredentialDestination } from './credential-admission.ts'; -let stderr: string[] = []; - -beforeEach(() => { - stderr = []; - vi.spyOn(process.stderr, 'write').mockImplementation((chunk: unknown, ...rest: unknown[]) => { - stderr.push(String(chunk)); - const callback = rest.find( - (arg): arg is (error: Error | null) => void => typeof arg === 'function', - ); - // A real stream calls back on a later tick, with null on success. - if (callback) process.nextTick(callback, null); - return true; - }); -}); - -afterEach(() => { - vi.restoreAllMocks(); +test('refuses non-loopback HTTP before a credential can be sent', () => { + const url = 'http://user:hunter2@fleet.example.test:7777/private?token=secret'; + + expect(() => admitCredentialDestination(url, {})).toThrowError( + expect.objectContaining({ + code: 'INVALID_ARGS', + details: expect.objectContaining({ + reason: 'insecure_credential_transport', + origin: 'http://fleet.example.test:7777', + }), + }), + ); }); -test('an insecure destination is warned about once per origin and not refused', () => { - admitCredentialDestination('http://user:hunter2@once.example.test:7777/a?token=secret', {}); - admitCredentialDestination('http://once.example.test:7777/b', {}); - admitCredentialDestination('http://once.example.test:8888', {}); - - expect(stderr).toHaveLength(2); - expect(stderr[0]).toMatch(/^Warning: .*http:\/\/once\.example\.test:7777 .*cleartext/); - expect(stderr[0]).toContain('agent-device 0.22 will refuse this'); - for (const fix of ['https', 'ssh -L', 'Tailscale Serve']) expect(stderr[0]).toContain(fix); - expect(stderr[0]).toContain('AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1'); - expect(stderr.join('')).not.toMatch(/user|hunter2|secret/); - expect(stderr[1]).toContain('http://once.example.test:8888'); -}); - -test('a stderr that throws does not change the outcome or keep a listener', () => { - const listeners = process.stderr.listenerCount('error'); - vi.mocked(process.stderr.write).mockImplementation(() => { - throw new Error('EPIPE'); - }); - - expect(() => admitCredentialDestination('http://broken-stderr.example.test', {})).not.toThrow(); - expect(process.stderr.listenerCount('error')).toBe(listeners); -}); - -test('warnings for 11 origins in one tick leave no error listener behind', async () => { - const listeners = process.stderr.listenerCount('error'); - const warnings: Error[] = []; - const onWarning = (warning: Error) => warnings.push(warning); - process.on('warning', onWarning); - try { - for (let index = 0; index < 11; index += 1) { - admitCredentialDestination(`http://many-${index}.example.test`, {}); - } - // Pending writes share at most one listener on the stream. - expect(process.stderr.listenerCount('error')).toBeLessThanOrEqual(listeners + 1); - await new Promise((resolve) => setImmediate(resolve)); - } finally { - process.off('warning', onWarning); - } - - expect(stderr).toHaveLength(11); - expect(process.stderr.listenerCount('error')).toBe(listeners); - expect(warnings.map((warning) => warning.name)).not.toContain('MaxListenersExceededWarning'); -}); - -test('a secure destination and the override stay silent', () => { - admitCredentialDestination('https://quiet.example.test', {}); - admitCredentialDestination('http://127.0.0.1:4310', {}); - admitCredentialDestination('http://quiet.example.test', { - AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT: '1', - }); - - expect(stderr).toEqual([]); +test.each([ + ['HTTPS', 'https://fleet.example.test', {}], + ['loopback HTTP', 'http://127.0.0.1:4310', {}], + [ + 'operator override', + 'http://fleet.example.test', + { AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT: '1' }, + ], +] as const)('admits %s', (_label, url, env) => { + expect(() => admitCredentialDestination(url, env)).not.toThrow(); }); diff --git a/packages/host-kit/src/credential-admission.ts b/packages/host-kit/src/credential-admission.ts index 39b37dbda6c..f073c2b24e4 100644 --- a/packages/host-kit/src/credential-admission.ts +++ b/packages/host-kit/src/credential-admission.ts @@ -1,33 +1,12 @@ -import { Console } from 'node:console'; import { credentialTransportRefusal } from '@agent-device/contracts/credential-transport'; -import { escapeTerminalText } from '@agent-device/kernel/redaction'; import type { EnvMap } from '@agent-device/kernel/source-value'; -const warnedOrigins = new Set(); -// Node's Console ignores stream errors (sync throws and async EPIPE) without keeping listeners, so -// the optional warning never changes what the command does. -let warningConsole: Console | undefined; - -/** - * The one warn-or-refuse decision for a configured URL that receives a first-party credential. - * 0.21.x warns on stderr, once per origin per loaded package: each published bundle holds its own - * copy of this module. 0.22 throws the refusal instead. - */ +/** Refuse a configured credential destination unless it uses HTTPS or loopback HTTP. */ export function admitCredentialDestination( url: string, env: Readonly, hint?: string, ): void { const refusal = credentialTransportRefusal(url, env, hint); - if (!refusal) return; - const origin = String(refusal.details?.origin); - if (warnedOrigins.has(origin)) return; - warnedOrigins.add(origin); - warningConsole ??= new Console({ stdout: process.stderr, stderr: process.stderr }); - warningConsole.error( - escapeTerminalText( - `Warning: credentials for ${origin} are sent in cleartext. agent-device 0.22 will refuse this. ` + - String(refusal.details?.hint), - ), - ); + if (refusal) throw refusal; } 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..a003e62ecfe 100644 --- a/packages/maestro/src/internal/__tests__/runtime-target-policy.test.ts +++ b/packages/maestro/src/internal/__tests__/runtime-target-policy.test.ts @@ -58,18 +58,18 @@ test('intersects every field in a compound Maestro selector', () => { ); }); -test('treats selector values as full Maestro regex without punctuation inference', () => { +test('treats admitted selector values as full Maestro regex without punctuation inference', () => { const node = makeSnapshot([ { index: 1, type: 'TextView', - label: 'Item 22 [ready', + label: 'Item 22 ready', }, ]).nodes[0]!; - expect(matchesMaestroTypedSelector(node, { text: 'item \\d{2} \\[ready' })).toBe(true); + expect(matchesMaestroTypedSelector(node, { text: 'item \\d\\d ready' })).toBe(true); expect(matchesMaestroTypedSelector(node, { text: 'Item 2' })).toBe(false); - expect(matchesMaestroTypedSelector(node, { text: 'Item 22 [ready' })).toBe(true); + expect(matchesMaestroTypedSelector(node, { text: 'Item 22 ready' })).toBe(true); }); test('the node-only matcher rejects full selectors at the type boundary', () => { diff --git a/packages/maestro/src/internal/__tests__/runtime-target-position.test.ts b/packages/maestro/src/internal/__tests__/runtime-target-position.test.ts index fb8fa02c42d..f56e34db3c3 100644 --- a/packages/maestro/src/internal/__tests__/runtime-target-position.test.ts +++ b/packages/maestro/src/internal/__tests__/runtime-target-position.test.ts @@ -90,7 +90,7 @@ test('applies index after composed positional intersections using y then x', () { index: 3, identifier: 'upper', rect: { x: 0, y: 80, width: 40, height: 30 } }, ]); const selector = { - id: 'candidate-(low|high)', + id: 'candidate-.*', index: 0, below: { id: 'upper' }, above: { id: 'lower' }, diff --git a/packages/maestro/src/internal/__tests__/selector-regex.test.ts b/packages/maestro/src/internal/__tests__/selector-regex.test.ts index ef53e98949b..2e8fa60ffab 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -2,9 +2,26 @@ import { expect, test } from 'vitest'; import { literalFromMaestroRegex, matchesMaestroRegex } 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\nready', String.raw`item \d\d.+ready`)).toBe(true); + expect(() => matchesMaestroRegex('Item 22\nready', String.raw`item \d{2}.+ready`)).toThrow(); expect(matchesMaestroRegex('Item 22 ready later', 'Item 22 ready')).toBe(false); - expect(matchesMaestroRegex('Item [ready', 'item [ready')).toBe(true); + expect(matchesMaestroRegex('Item \\', 'item \\')).toBe(true); +}); + +test.each([ + '(a+)+', + '(a|aa)+', + 'a*a*', + '(a+){2}', + String.raw`(a+)\1`, + '(a|aa)(a|aa)(a|aa)(a|aa)(a|aa)(a|aa)', +])('refuses a backtracking Maestro selector pattern %s', (pattern) => { + expect(() => matchesMaestroRegex(`${'a'.repeat(4096)}X`, pattern)).toThrow( + expect.objectContaining({ + code: 'INVALID_ARGS', + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); }); test('extracts only patterns that are exact literals', () => { diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index b03d0982561..0857ba7f166 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -1,6 +1,21 @@ +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; + +const MAESTRO_SELECTOR_REGEX_REASONS = { + // The selector pattern uses constructs that the bounded matcher cannot safely execute. + 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 = 8192; +const UNSUPPORTED_PATTERN_SYNTAX = new Set(['(', ')', '{', '}', '|', '[', ']']); +const VARIABLE_QUANTIFIERS = new Set(['*', '+', '?']); export function matchesMaestroRegex(value: string, pattern: string): boolean { + if (pattern.length > MAX_PATTERN_LENGTH || value.length > MAX_VALUE_LENGTH) { + unsafeMaestroRegex(); + } + assertBoundedMaestroPattern(pattern); try { return new RegExp(`^(?:${pattern})$`, 'ims').test(value); } catch { @@ -8,6 +23,39 @@ export function matchesMaestroRegex(value: string, pattern: string): boolean { } } +// No groups, alternatives, classes, or counted repeats means one variable quantifier can only +// repeat one atom. The matcher has linear work for this deliberately narrow subset. +function assertBoundedMaestroPattern(pattern: string): void { + if ([...pattern].some((character) => UNSUPPORTED_PATTERN_SYNTAX.has(character))) + unsafeMaestroRegex(); + if (/\\[1-9]/.test(pattern)) unsafeMaestroRegex(); + if (countVariableQuantifiers(pattern) > 1) unsafeMaestroRegex(); +} + +function countVariableQuantifiers(pattern: string): number { + let escaped = false; + let count = 0; + for (const character of pattern) { + if (escaped) { + escaped = false; + continue; + } + if (character === '\\') { + escaped = true; + continue; + } + if (VARIABLE_QUANTIFIERS.has(character)) count += 1; + } + return count; +} + +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 { try { new RegExp(pattern); diff --git a/packages/proxy/README.md b/packages/proxy/README.md index b2f3eef769f..3a373733622 100644 --- a/packages/proxy/README.md +++ b/packages/proxy/README.md @@ -143,7 +143,7 @@ By default, `/rpc`, `/health` and request diagnostics use global `fetch`. The default transport sends `upstreamToken` to `upstreamBaseUrl`, so use https, a loopback upstream (`localhost`, `127.0.0.0/8`, or `::1`), or your own `upstreamFetch`. For any other URL, -0.21.x `createDaemonProxy` warns on stderr, and 0.22 refuses to send the token, with reason +`createDaemonProxy` refuses to send the token, with reason `insecure_credential_transport`. With `upstreamFetch`, the URL is not checked: your transport owns the route. diff --git a/packages/proxy/src/daemon-proxy-credential-transport.test.ts b/packages/proxy/src/daemon-proxy-credential-transport.test.ts index c112b38ddcf..b9da325b3ac 100644 --- a/packages/proxy/src/daemon-proxy-credential-transport.test.ts +++ b/packages/proxy/src/daemon-proxy-credential-transport.test.ts @@ -27,7 +27,7 @@ function proxyFor(upstreamBaseUrl: string, upstreamFetch?: DaemonProxyOptions['u }); } -test('construction warns about a plain http upstream off loopback, ahead of any send', async () => { +test('plain http upstream off loopback is refused ahead of any send', async () => { const atSend: string[] = []; vi.spyOn(globalThis, 'fetch').mockImplementation(async () => { atSend.push(stderr); @@ -35,12 +35,9 @@ test('construction warns about a plain http upstream off loopback, ahead of any }); const proxy = proxyFor('http://upstream.example.test:4310'); - await vi.waitFor(() => expect(stderr).toContain('http://upstream.example.test:4310')); + const response = await proxy.handle(health()); + expect(response.status).toBe(400); expect(atSend).toEqual([]); - - await proxy.handle(health()); - expect(atSend).toEqual([stderr]); - expect(stderr).toContain('Use https, a loopback upstream, or your own upstreamFetch.'); expect(stderr).not.toMatch(/daemon-secret|AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT/); }); diff --git a/packages/react-native/src/metro/client-metro-auto-companion.test.ts b/packages/react-native/src/metro/client-metro-auto-companion.test.ts index 7ff03dc7253..30633acbfca 100644 --- a/packages/react-native/src/metro/client-metro-auto-companion.test.ts +++ b/packages/react-native/src/metro/client-metro-auto-companion.test.ts @@ -2,11 +2,7 @@ import { afterEach, test, vi } from 'vitest'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; -import { - beginStderrCapture, - createTestHostEnvironment, - mkdtempForTestSync, -} from '@agent-device/test-kit'; +import { createTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; import { AppError } from '@agent-device/kernel/errors'; vi.mock('../companion/client-metro-companion.ts', () => ({ @@ -556,56 +552,58 @@ test('prepareMetroRuntime retries malformed retryable bridge responses after com }); test.each([ - ['warns before', 'http://bridge.example.test', {}, /http:\/\/bridge\.example\.test are sent/], + ['refuses', 'http://bridge.example.test', {}, false], [ - 'honors the host override for', + 'admits with the host override', 'http://allowed-bridge.example.test', { AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT: '1' }, - /^$/, + true, ], ] as const)( 'prepareMetroRuntime %s a plain http bridge that gets the bearer', - async (_label, proxyBaseUrl, env, expected) => { + async (_label, proxyBaseUrl, env, admitted) => { const projectRoot = mkdtempForTestSync('agent-device-metro-transport-'); fs.writeFileSync( path.join(projectRoot, 'package.json'), JSON.stringify({ name: 'metro-transport-test', dependencies: { 'react-native': '0' } }), ); - const stderr = beginStderrCapture(); - const atBridgeSend: Array<{ authorization: string | null; stderr: string }> = []; + const atBridgeSend: Array<{ authorization: string | null }> = []; vi.stubGlobal( 'fetch', vi.fn(async (url: string, init?: RequestInit) => { if (url.endsWith('/status')) return new Response('packager-status:running'); const authorization = new Headers(init?.headers).get('authorization'); - atBridgeSend.push({ authorization, stderr: stderr.read() }); + atBridgeSend.push({ authorization }); return new Response('{}', { status: 401 }); }), ); try { - await assert.rejects( - prepareMetroRuntime( - { - projectRoot, - proxyBaseUrl, - proxyBearerToken: 'shared-token', - bridgeScope: TEST_BRIDGE_SCOPE, - reuseExisting: true, - installDependenciesIfNeeded: false, - }, - createTestHostEnvironment({ env }), - ), - /401/, + const request = prepareMetroRuntime( + { + projectRoot, + proxyBaseUrl, + proxyBearerToken: 'shared-token', + bridgeScope: TEST_BRIDGE_SCOPE, + reuseExisting: true, + installDependenciesIfNeeded: false, + }, + createTestHostEnvironment({ env }), ); + if (admitted) await assert.rejects(request, /401/); + else + await assert.rejects(request, (error: unknown) => { + const value = error as AppError; + return ( + value.code === 'INVALID_ARGS' && + value.details?.reason === 'insecure_credential_transport' + ); + }); } finally { - stderr.restore(); vi.unstubAllGlobals(); } - assert.equal(atBridgeSend.length, 1); - assert.equal(atBridgeSend[0]!.authorization, 'Bearer shared-token'); - assert.match(atBridgeSend[0]!.stderr, expected); - assert.doesNotMatch(atBridgeSend[0]!.stderr, /shared-token/); + assert.equal(atBridgeSend.length, admitted ? 1 : 0); + if (admitted) assert.equal(atBridgeSend[0]!.authorization, 'Bearer shared-token'); }, ); diff --git a/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts b/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts index 4698ce5a51b..58e5371fd24 100644 --- a/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts +++ b/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts @@ -83,6 +83,7 @@ type MaterializationCase = { fileName?: string; expected?: string; generatedName?: RegExp; + protectedPath?: string; }; const posixNameCases: MaterializationCase[] = [ @@ -140,18 +141,23 @@ test.for([ expected: 'cwd/clip.mp4', }, { - name: 'a perf cpu profile stop accepts the echo of its start destination', + name: 'a perf cpu profile stop ignores the daemon echo of its start destination', command: 'perf', positionals: ['cpu', 'profile', 'stop'], localPath: 'client/cpu.trace', fileName: 'cpu.trace', - expected: 'client/cpu.trace', + generatedName: /^cpu-[0-9a-f-]{36}\.trace$/, + protectedPath: 'cwd/cpu.trace', }, ...(process.platform === 'win32' ? [] : posixNameCases), ])('remote artifact materialization: $name', async (c, t) => { if (await skipWhenLoopbackUnavailable(t, 'remote artifact download')) return; const root = mkdtempForTestSync('agent-device-remote-artifact-path-'); const inRoot = (relative: string) => path.join(root, relative); + if (c.protectedPath) { + fs.mkdirSync(path.dirname(inRoot(c.protectedPath)), { recursive: true }); + fs.writeFileSync(inRoot(c.protectedPath), 'protected'); + } const field = c.field ?? 'path'; const server = http.createServer((_req, res) => res.end('artifact-bytes')); try { @@ -193,6 +199,7 @@ test.for([ expect(path.basename(String(saved))).toMatch(c.generatedName ?? /^path-\d+$/); } expect(fs.readFileSync(String(saved), 'utf8')).toBe('artifact-bytes'); + if (c.protectedPath) expect(fs.readFileSync(inRoot(c.protectedPath), 'utf8')).toBe('protected'); expect(fs.existsSync(inRoot('outside'))).toBe(false); } finally { await closeLoopbackServer(server); diff --git a/packages/remote/src/daemon-artifacts.ts b/packages/remote/src/daemon-artifacts.ts index 8d6d546aed8..0a2f5bb9f17 100644 --- a/packages/remote/src/daemon-artifacts.ts +++ b/packages/remote/src/daemon-artifacts.ts @@ -722,29 +722,12 @@ function withoutScriptFieldOwner( return kept; } -/** - * Whether this request finishes a trace or perf capture whose destination the daemon echoes - * from an earlier request. The finishing actions mirror `request-finalization.ts`. - */ -function finishesEarlierClientCapture(req: DaemonWireRequest): boolean { - const [first, second, third] = (req.positionals ?? []).map((value) => value.toLowerCase()); - switch (req.command) { - case 'trace': - return first === 'stop'; - case 'perf': - return third === 'stop' || third === 'report' || (first === 'trace' && second === 'stop'); - default: - return false; - } -} - function isRecordStop(req: DaemonWireRequest): boolean { return req.command === 'record' && req.positionals?.[0]?.toLowerCase() === 'stop'; } /** * A path from this request wins. A record stop without one can use only a plain name in cwd. - * Trace and perf stop or report can still use an echoed destination from an earlier request. * A NUL in a response file name cannot provide a fallback destination. */ function resolveMaterializedArtifactPath( @@ -763,11 +746,17 @@ function resolveMaterializedArtifactPath( const fileName = localFileName(artifact.fileName) ?? `recording-${crypto.randomUUID()}`; return { path: path.resolve(req.meta?.cwd ?? host.cwd, fileName), fallback: true }; } - if (hasNonEmptyString(artifact.localPath) && finishesEarlierClientCapture(req)) { - return { path: artifact.localPath, fallback: false }; - } const fallbackPath = resolveOrdinaryArtifactFallbackPath(artifact, req.meta?.cwd ?? host.cwd); - return fallbackPath ? { path: fallbackPath, fallback: false } : undefined; + if (!fallbackPath) return undefined; + if (req.command === 'trace' || req.command === 'perf') { + const extension = path.extname(fallbackPath); + const stem = path.basename(fallbackPath, extension); + return { + path: path.join(path.dirname(fallbackPath), `${stem}-${crypto.randomUUID()}${extension}`), + fallback: false, + }; + } + return { path: fallbackPath, fallback: false }; } function resolveOrdinaryArtifactFallbackPath( diff --git a/src/cli/__tests__/auth-session-cloud-transport.test.ts b/src/cli/__tests__/auth-session-cloud-transport.test.ts index bb19f45a570..6dea22893c3 100644 --- a/src/cli/__tests__/auth-session-cloud-transport.test.ts +++ b/src/cli/__tests__/auth-session-cloud-transport.test.ts @@ -1,9 +1,8 @@ -// Cloud login, refresh and profile requests warn before a credential goes over plain http to a host -// that is not loopback. The stored issuer is judged too, and the override covers it. +// Cloud login, refresh and profile requests refuse cleartext before sending a credential. import assert from 'node:assert/strict'; -import { afterEach, test } from 'vitest'; -import { beginStderrCapture, mkdtempForTestSync, type StreamCapture } from '@agent-device/test-kit'; +import { test } from 'vitest'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; import { loginWithDeviceAuth, resolveRemoteAuth, writeCliSession } from '../auth-session.ts'; import { CLI_SESSION_FORMAT_VERSION } from '../cli-session-format.ts'; import { resolveCloudConnectProfile } from '../connection/cloud-profile.ts'; @@ -15,17 +14,18 @@ const flags = { daemonBaseUrl: 'https://bridge.agent-device.dev', }; -let stderr: StreamCapture | undefined; -afterEach(() => { - stderr?.restore(); -}); +function isTransportRefusal(error: unknown): boolean { + const value = error as { code?: string; details?: { reason?: string } }; + return ( + value?.code === 'INVALID_ARGS' && value.details?.reason === 'insecure_credential_transport' + ); +} -/** A cloud that records the stderr written by the time each request reaches it. */ +/** A cloud that records requests that reach the transport. */ function recordingCloud(answer: (url: string) => unknown) { - stderr = beginStderrCapture(); const atSend: string[] = []; const fetch = async (url: URL | RequestInfo): Promise => { - atSend.push(stderr!.read()); + atSend.push(String(url)); return Response.json(answer(String(url))); }; return { atSend, fetch }; @@ -46,7 +46,7 @@ function storeSession(cloudBaseUrl: string): string { return stateDir; } -test('login warns before the first request to a plain http cloud', async () => { +test('login refuses a plain http cloud before its first request', async () => { const cloud = recordingCloud((url) => url.endsWith('/start') ? { @@ -61,36 +61,37 @@ test('login warns before the first request to a plain http cloud', async () => { }, ); - await loginWithDeviceAuth({ - stateDir: mkdtempForTestSync('agent-device-cloud-transport-login-'), - flags, - env: { AGENT_DEVICE_CLOUD_BASE_URL: 'http://login.example.test' }, - io: { - stdinIsTTY: true, - stdoutIsTTY: true, - stderr: { write: () => true }, - openBrowser: async () => {}, - fetch: cloud.fetch, - }, - }); + await assert.rejects( + loginWithDeviceAuth({ + stateDir: mkdtempForTestSync('agent-device-cloud-transport-login-'), + flags, + env: { AGENT_DEVICE_CLOUD_BASE_URL: 'http://login.example.test' }, + io: { + stdinIsTTY: true, + stdoutIsTTY: true, + stderr: { write: () => true }, + openBrowser: async () => {}, + fetch: cloud.fetch, + }, + }), + isTransportRefusal, + ); - assert.equal(cloud.atSend.length, 2); - assert.match(cloud.atSend[0]!, /http:\/\/login\.example\.test are sent in cleartext/); - assert.equal(cloud.atSend[1], cloud.atSend[0], 'one warning per origin'); + assert.equal(cloud.atSend.length, 0); }); test.each([ - ['warns about', 'http://issuer.example.test', {}, /issuer\.example\.test are sent in cleartext/], + ['refuses', 'http://issuer.example.test', {}, false], [ - 'honors the override for', + 'admits with the override', 'http://allowed-issuer.example.test', { AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT: '1' }, - /^$/, + true, ], -] as const)('a refresh %s the stored plain http issuer', async (_label, issuer, env, expected) => { +] as const)('a refresh %s the stored plain http issuer', async (_label, issuer, env, admitted) => { const cloud = recordingCloud(() => ({ accessToken: 'adc_agent_fresh' })); - await resolveRemoteAuth({ + const request = resolveRemoteAuth({ command: 'snapshot', flags, stateDir: storeSession(issuer), @@ -99,11 +100,12 @@ test.each([ io: { fetch: cloud.fetch }, }); - assert.equal(cloud.atSend.length, 1); - assert.match(cloud.atSend[0]!, expected); + if (admitted) await request; + else await assert.rejects(request, isTransportRefusal); + assert.equal(cloud.atSend.length, admitted ? 1 : 0); }); -test('the profile request warns before it sends the access token', async () => { +test('the profile request refuses before it sends the access token', async () => { const cloud = recordingCloud(() => ({})); await assert.rejects( @@ -117,10 +119,8 @@ test('the profile request warns before it sends the access token', async () => { }, fetchImpl: cloud.fetch, }), - /missing profile/, + isTransportRefusal, ); - assert.equal(cloud.atSend.length, 1); - assert.match(cloud.atSend[0]!, /http:\/\/profile\.example\.test are sent in cleartext/); - assert.doesNotMatch(cloud.atSend[0]!, /adc_live_secret/); + assert.equal(cloud.atSend.length, 0); }); diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 1bb3c10473a..69c488f6389 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -480,7 +480,7 @@ Remote connection providers use the same lifecycle: Providers: Cloud: agent-device connect or agent-device connect cloud discovers the agent-device cloud profile. Remote config: agent-device connect --remote-config ./remote-config.json uses a local profile. - Direct proxy: agent-device connect proxy --daemon-base-url stores the shared proxy profile and client identity. Use https, or a loopback http URL such as an ssh -L forward: for other plain http URLs, 0.21.x warns that the token travels in cleartext and 0.22 refuses (reason insecure_credential_transport). To allow plain http, set AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1 in the process that sends the credential: here the client, not the proxy host. + Direct proxy: agent-device connect proxy --daemon-base-url stores the shared proxy profile and client identity. Use https, or a loopback http URL such as an ssh -L forward: other plain http URLs are refused before the token is sent (reason insecure_credential_transport). To allow plain http, set AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1 in the process that sends the credential: here the client, not the proxy host. BrowserStack: agent-device connect browserstack verifies credentials, the exact device, and a bs:// app reference, then stores a local provider profile. It does not create an App Automate session. AWS Device Farm: agent-device connect aws-device-farm verifies credentials and the exact project, device, and optional app upload, then stores a local provider profile. It does not create a remote access session. TestMu AI (plugin, install separately): agent-device connect testmu verifies credentials and the exact virtual device (emulator or simulator) or, with --provider-device-type real, real device and OS version, then stores a local provider profile. --provider-app takes an lt:// app reference, an https URL, or a local path: connect looks an lt:// id up among your uploads for that device pool, while URL and local sources are uploaded and validated when open creates the session. It does not create a hub session. diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 4b09ff1ba14..08d1d3f2605 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -160,7 +160,7 @@ "packages/remote/src/daemon-artifacts.ts#downloadRemoteArtifact": "sha256:3f3b6c01601c54ab2c76c8cb0946de623da4d24ba32254c75ae8a3993f66adcf", "packages/remote/src/daemon-artifacts.ts#isRemoteDaemon": "sha256:0f6a714c5f60ce4e8548d811b516d8b6241eca9f7e5414733732da395b8a00e7", "packages/remote/src/daemon-artifacts.ts#materializeRemoteArtifacts": "sha256:6d9aba219e6fafbdbcef76d30ed99fbb4f61dcc525242a0a76c3dc1bdacd24e2", - "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath": "sha256:06dc215c06a9d2ea5a3821faf31b297a2e2f63928672c08c637b132beee726be", + "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath": "sha256:847b619e378503cfa8a42884534e2947b9f4d2503cf0bdfbd3db101c274c069e", "packages/remote/src/daemon-artifacts.ts#resolveOrdinaryArtifactFallbackPath": "sha256:e8b1cb5243194e1d4fc7e376979ca5aae3aaf55cfdd33102e1410b2033fb3a4f", "packages/remote/src/remote-request-diagnostics.ts#RemoteDaemonErrorPayload": "sha256:8fbcbcdf4bae7b66a08e465a72593794f36364759f18f1a814cd39dfdb76f309", "packages/remote/src/remote-request-diagnostics.ts#RemoteDiagnosticsEndpoint": "sha256:c1d5fe2fe90c425502cf8b7c87d6606374d6af65b4e9faf942a416f683930bdc", @@ -539,8 +539,8 @@ }, { "declaration": "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath", - "digest": "sha256:06dc215c06a9d2ea5a3821faf31b297a2e2f63928672c08c637b132beee726be", - "rationale": "#4518 and #4661 change client-side destination selection. Authorized destinations keep precedence. Fallbacks reject NUL names, and ordinary captures reject explicit non-string names and Windows drive-qualified basenames under Windows path rules. Daemons send the same artifact fields with the same framing." + "digest": "sha256:847b619e378503cfa8a42884534e2947b9f4d2503cf0bdfbd3db101c274c069e", + "rationale": "Client-side trace and perf completion no longer trusts an artifact.localPath echoed by the daemon. Without a caller path, the client chooses a new random-suffixed destination under its fallback directory. Daemons send the same artifact fields with the same framing, and older peers can ignore this client's destination choice." }, { "declaration": "packages/daemon/src/server/http/http-server.ts#MAX_HTTP_RPC_BODY_BYTES", diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 2c391391f6d..075d6b707f6 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -873,6 +873,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 uses constructs that the bounded matcher cannot safely execute. | + ### Metro reload | Reason | Meaning | @@ -935,7 +941,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | -| `insecure_credential_transport` | A first-party credential would go to a configured URL that is neither https nor plain http to a loopback host, and the CLI or SDK environment does not set AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1 (@agent-device/proxy has no override). agent-device 0.21.x warns on stderr instead of failing with it; 0.22 refuses with it before sending anything. | +| `insecure_credential_transport` | A first-party credential would go to a configured URL that is neither https nor plain http to a loopback host, and the CLI or SDK environment does not set AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1 (@agent-device/proxy has no override). | | `remote_instance_mismatch` | The daemon or proxy behind the remote URL was replaced since the client last read its health, so it refused a request addressed to the earlier instance. The client refreshes health and resends at most once; this reaches the caller when that resend is refused too. | | `remote_rpc_protocol_missing` | The checked RPC call named no RPC protocol. An intermediary that strips request headers causes this. | | `remote_rpc_protocol_mismatch` | The daemon or proxy speaks a different RPC protocol from the caller. After authentication, `details.service`, `details.version` and `details.rpcProtocolVersion` name the side that refused. | diff --git a/website/docs/docs/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index fdf4e5d7606..559b5cf4179 100644 --- a/website/docs/docs/run-maestro-flows.md +++ b/website/docs/docs/run-maestro-flows.md @@ -30,6 +30,7 @@ Keep the target binding, such as `--platform ios`, on the `replay` or `test` com ## Boundaries +- Selector `id` and `text` patterns allow at most one `*`, `+`, or `?` repetition on a single character or escaped character class such as `\d`. Groups, alternatives, bracket classes, counted repeats, backreferences, patterns over 256 characters, and values over 8192 characters fail with `maestro_selector_regex_unsafe` to keep matching bounded. - 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 22f9adca7bb1428622f2497467569eb7c4905ff2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 14:10:07 +0100 Subject: [PATCH 02/55] test(provider): match daemon restart hint without case sensitivity --- .../provider-scenarios/provider-device-runtime.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/integration/provider-scenarios/provider-device-runtime.test.ts b/test/integration/provider-scenarios/provider-device-runtime.test.ts index 98443f6abde..eaf6874ece8 100644 --- a/test/integration/provider-scenarios/provider-device-runtime.test.ts +++ b/test/integration/provider-scenarios/provider-device-runtime.test.ts @@ -154,7 +154,7 @@ test('provider lease allocation is refused when no registered runtime claims the assert.equal(details.reason, 'provider-not-registered'); assert.equal(details.provider, 'testmu'); assert.deepEqual(details.registeredProviders, [FAKE_PROVIDER]); - assert.match(String(error.hint), /Restart the daemon/); + assert.match(String(error.hint), /restart the daemon/i); const retried = await daemon.callCommand( 'lease_allocate', [], From 1ee9fd11a9d149f5145941d31f2738c834064ba2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 14:17:52 +0100 Subject: [PATCH 03/55] test(remote): prove trace stop ignores daemon paths --- .../src/__tests__/daemon-artifacts-capture.test.ts | 9 +++++++++ website/docs/docs/remote-proxy.md | 4 ++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts b/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts index 58e5371fd24..2e9d8ec523c 100644 --- a/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts +++ b/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts @@ -149,6 +149,15 @@ test.for([ generatedName: /^cpu-[0-9a-f-]{36}\.trace$/, protectedPath: 'cwd/cpu.trace', }, + { + name: 'a trace stop ignores a daemon-selected client path', + command: 'trace', + positionals: ['stop'], + localPath: 'cwd/private.log', + fileName: 'trace.log', + generatedName: /^trace-[0-9a-f-]{36}\.log$/, + protectedPath: 'cwd/private.log', + }, ...(process.platform === 'win32' ? [] : posixNameCases), ])('remote artifact materialization: $name', async (c, t) => { if (await skipWhenLoopbackUnavailable(t, 'remote artifact download')) return; diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 0a71f2c0a50..63497fe8c9c 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -100,8 +100,8 @@ destination on your machine. A recording is different: it downloads to the path `GET /artifacts/` using the same authentication. For trace and performance stop or report, a destination on the current request wins. Without one, -the client uses a path the daemon echoes from an earlier start request when present. If neither -path is present, it downloads to the working directory using the artifact file name. +the client chooses a unique file in its working directory from the artifact file name. A path +echoed by the daemon from an earlier request cannot select the client destination. By default, artifacts leave the inventory after download or after 15 minutes. `AGENT_DEVICE_RETAIN_ARTIFACTS` keeps downloaded artifacts in inventory until expiry. Downloads already in progress From 99552c055e04d779fe547493156d1eb70d619224 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 14:39:58 +0100 Subject: [PATCH 04/55] fix: keep Maestro selectors usable with long labels and escaped literals --- .../internal/__tests__/selector-regex.test.ts | 11 ++++++++++ .../maestro/src/internal/selector-regex.ts | 21 +++++++++++++------ 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/packages/maestro/src/internal/__tests__/selector-regex.test.ts b/packages/maestro/src/internal/__tests__/selector-regex.test.ts index 2e8fa60ffab..8365410818e 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -30,3 +30,14 @@ test('extracts only patterns that are exact literals', () => { expect(literalFromMaestroRegex(String.raw`item \d{2}`)).toBeUndefined(); expect(literalFromMaestroRegex('item [ready')).toBe('item [ready'); }); + +test('long device labels do not invalidate a bounded selector', () => { + expect(matchesMaestroRegex('a'.repeat(8193), 'item')).toBe(false); + expect(matchesMaestroRegex('item', 'item')).toBe(true); +}); + +test('escaped brackets and braces match literal node text', () => { + expect(matchesMaestroRegex('a(b', String.raw`a\(b`)).toBe(true); + expect(matchesMaestroRegex('price {2}', String.raw`price \{2\}`)).toBe(true); + expect(() => matchesMaestroRegex('price 22', String.raw`price {2}`)).toThrow(); +}); diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index 0857ba7f166..7514032752d 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -12,10 +12,9 @@ const UNSUPPORTED_PATTERN_SYNTAX = new Set(['(', ')', '{', '}', '|', '[', ']']); const VARIABLE_QUANTIFIERS = new Set(['*', '+', '?']); export function matchesMaestroRegex(value: string, pattern: string): boolean { - if (pattern.length > MAX_PATTERN_LENGTH || value.length > MAX_VALUE_LENGTH) { - unsafeMaestroRegex(); - } + if (pattern.length > MAX_PATTERN_LENGTH) unsafeMaestroRegex(); assertBoundedMaestroPattern(pattern); + if (value.length > MAX_VALUE_LENGTH) return false; try { return new RegExp(`^(?:${pattern})$`, 'ims').test(value); } catch { @@ -26,9 +25,19 @@ export function matchesMaestroRegex(value: string, pattern: string): boolean { // No groups, alternatives, classes, or counted repeats means one variable quantifier can only // repeat one atom. The matcher has linear work for this deliberately narrow subset. function assertBoundedMaestroPattern(pattern: string): void { - if ([...pattern].some((character) => UNSUPPORTED_PATTERN_SYNTAX.has(character))) - unsafeMaestroRegex(); - if (/\\[1-9]/.test(pattern)) unsafeMaestroRegex(); + let escaped = false; + for (const character of pattern) { + if (escaped) { + if (/[1-9]/.test(character)) unsafeMaestroRegex(); + escaped = false; + continue; + } + if (character === '\\') { + escaped = true; + continue; + } + if (UNSUPPORTED_PATTERN_SYNTAX.has(character)) unsafeMaestroRegex(); + } if (countVariableQuantifiers(pattern) > 1) unsafeMaestroRegex(); } From ba1adca85f33a43ff83d19cf303039fd21af5eef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 15:10:46 +0100 Subject: [PATCH 05/55] fix: validate Maestro selectors before normalized matching --- .../internal/__tests__/runtime-target-policy.test.ts | 9 +++++++++ .../src/internal/__tests__/selector-regex.test.ts | 10 ++++++++++ packages/maestro/src/internal/runtime-target-policy.ts | 8 ++------ packages/maestro/src/internal/selector-regex.ts | 2 ++ 4 files changed, 23 insertions(+), 6 deletions(-) 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 a003e62ecfe..664e4071c4d 100644 --- a/packages/maestro/src/internal/__tests__/runtime-target-policy.test.ts +++ b/packages/maestro/src/internal/__tests__/runtime-target-policy.test.ts @@ -82,3 +82,12 @@ test('the node-only matcher rejects full selectors at the type boundary', () => }); expect(node.label).toBe('Save'); }); + +test('typed selectors validate even when node text equals the unsafe pattern', () => { + const node = makeSnapshot([{ index: 1, label: 'a*a*' }]).nodes[0]!; + expect(() => matchesMaestroTypedSelector(node, { text: 'a*a*' })).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); +}); diff --git a/packages/maestro/src/internal/__tests__/selector-regex.test.ts b/packages/maestro/src/internal/__tests__/selector-regex.test.ts index 8365410818e..8237aa0dba2 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -41,3 +41,13 @@ test('escaped brackets and braces match literal node text', () => { expect(matchesMaestroRegex('price {2}', String.raw`price \{2\}`)).toBe(true); expect(() => matchesMaestroRegex('price 22', String.raw`price {2}`)).toThrow(); }); + +test('validates the pattern before normalized literal matching', () => { + expect(matchesMaestroRegex(' Save now ', 'save now')).toBe(true); + expect(() => matchesMaestroRegex('a'.repeat(257), 'a'.repeat(257))).toThrow(); + expect(() => matchesMaestroRegex('a*a*', 'a*a*')).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); +}); diff --git a/packages/maestro/src/internal/runtime-target-policy.ts b/packages/maestro/src/internal/runtime-target-policy.ts index bc025276802..a898d8be12b 100644 --- a/packages/maestro/src/internal/runtime-target-policy.ts +++ b/packages/maestro/src/internal/runtime-target-policy.ts @@ -6,7 +6,7 @@ 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 { extractNodeText, normalizeText } from './shared.ts'; +import { extractNodeText } from './shared.ts'; import { isMaestroNodeVisible } from './snapshot-policy.ts'; export type MaestroRuntimePlatform = 'ios' | 'android'; @@ -56,11 +56,7 @@ export function filterVisibleMaestroMatches(params: { } function matchesMaestroSelectorValue(value: string | undefined, query: string): boolean { - const text = value ?? ''; - const normalizedText = normalizeText(text); - const normalizedQuery = normalizeText(query); - if (normalizedText === normalizedQuery) return true; - return matchesMaestroRegex(text, query); + return matchesMaestroRegex(value ?? '', query); } function matchesMaestroVisibleText(node: SnapshotNode, query: string): boolean { diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index 7514032752d..7065066fa38 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -1,4 +1,5 @@ import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; +import { normalizeText } from './shared.ts'; const MAESTRO_SELECTOR_REGEX_REASONS = { // The selector pattern uses constructs that the bounded matcher cannot safely execute. @@ -15,6 +16,7 @@ export function matchesMaestroRegex(value: string, pattern: string): boolean { if (pattern.length > MAX_PATTERN_LENGTH) unsafeMaestroRegex(); assertBoundedMaestroPattern(pattern); if (value.length > MAX_VALUE_LENGTH) return false; + if (normalizeText(value) === normalizeText(pattern)) return true; try { return new RegExp(`^(?:${pattern})$`, 'ims').test(value); } catch { From 07e3043cf1f531e53e962c555fd26ab3ad436ed0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 15:10:58 +0100 Subject: [PATCH 06/55] chore(gates): keep Maestro regex construction in bounded owner --- .../maestro/src/internal/engine-context.ts | 3 +- test/repo-guards/maestro-regex-owner.test.ts | 90 +++++++++++++++++++ 2 files changed, 91 insertions(+), 2 deletions(-) create mode 100644 test/repo-guards/maestro-regex-owner.test.ts diff --git a/packages/maestro/src/internal/engine-context.ts b/packages/maestro/src/internal/engine-context.ts index 2cd000efe74..c869754115c 100644 --- a/packages/maestro/src/internal/engine-context.ts +++ b/packages/maestro/src/internal/engine-context.ts @@ -140,8 +140,7 @@ function resolveValue( } function assertNoUnsupportedInterpolation(value: string): void { - const interpolation = /\$\{[^{}]*\}/g; - for (const match of value.matchAll(interpolation)) { + for (const match of value.matchAll(/\$\{[^{}]*\}/g)) { if (isMaestroPlatformExpression(match[0])) continue; throw new AppError( 'INVALID_ARGS', diff --git a/test/repo-guards/maestro-regex-owner.test.ts b/test/repo-guards/maestro-regex-owner.test.ts new file mode 100644 index 00000000000..1e146718f0e --- /dev/null +++ b/test/repo-guards/maestro-regex-owner.test.ts @@ -0,0 +1,90 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { parseSync } from 'oxc-parser'; +import { test } from 'vitest'; + +const SOURCE_ROOT = path.join( + path.dirname(fileURLToPath(import.meta.url)), + '../../packages/maestro/src', +); +const REGEX_OWNER = path.join(SOURCE_ROOT, 'internal/selector-regex.ts'); + +function sourceFiles(directory: string): string[] { + return fs.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { + if (entry.name === '__tests__' || entry.name === 'test-utils') return []; + const entryPath = path.join(directory, entry.name); + if (entry.isDirectory()) return sourceFiles(entryPath); + if (!entry.name.endsWith('.ts') || entry.name.endsWith('.test.ts')) return []; + return [entryPath]; + }); +} + +function regexBypassViolations(source: string, filePath: string): string[] { + const parsed = parseSync(filePath, source); + assert.deepEqual(parsed.errors, []); + const violations: string[] = []; + type Node = { + type?: string; + name?: string; + value?: unknown; + regex?: unknown; + start?: number; + callee?: Node; + property?: Node; + arguments?: Node[]; + [key: string]: unknown; + }; + function visit(value: unknown): void { + if (!value || typeof value !== 'object') return; + if (Array.isArray(value)) { + for (const item of value) visit(item); + return; + } + const node = value as Node; + if (node.type === 'NewExpression' || node.type === 'CallExpression') { + const callee = node.callee; + const name = callee?.type === 'Identifier' + ? callee.name + : callee?.type === 'MemberExpression' + ? (callee.property?.name ?? callee.property?.value) + : undefined; + const implicitRegex = + node.type === 'CallExpression' && + callee?.type === 'MemberExpression' && + (name === 'match' || name === 'matchAll' || name === 'search') && + node.arguments?.[0]?.regex === undefined; + if (name === 'RegExp' || implicitRegex) { + const line = source.slice(0, node.start).split('\n').length; + violations.push(`${path.relative(SOURCE_ROOT, filePath)}:${line}`); + } + } + for (const child of Object.values(node)) visit(child); + } + visit(parsed.program); + return violations; +} + +test('Maestro regex construction stays behind the bounded selector owner', () => { + const files = sourceFiles(SOURCE_ROOT).filter((file) => file !== REGEX_OWNER); + assert.ok(files.length > 0, 'guard must scan Maestro production files'); + assert.deepEqual( + files.flatMap((file) => regexBypassViolations(fs.readFileSync(file, 'utf8'), file)), + [], + 'Route authored selector patterns through internal/selector-regex.ts.', + ); +}); + +test('Maestro regex guard catches direct and implicit construction', () => { + const source = [ + 'new RegExp(query)', + 'RegExp(query)', + 'value.match(query)', + 'value.matchAll(query)', + 'value.search(query)', + "value['match'](query)", + ].join(';'); + assert.equal(regexBypassViolations(source, 'fixture.ts').length, 6); + assert.deepEqual(regexBypassViolations('value.matchAll(/fixed/g)', 'fixture.ts'), []); +}); From b5402c7929f775fc4c893d497039ac1b1e84ed1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 15:22:29 +0100 Subject: [PATCH 07/55] fix: reserve unique client paths for unnamed remote artifacts --- .../daemon-artifacts-capture.test.ts | 23 +++++++++----- .../daemon-artifacts-record-download.test.ts | 31 ++++++++++++------- packages/remote/src/daemon-artifacts.ts | 29 ++++++++++------- website/docs/docs/remote-proxy.md | 16 +++++----- 4 files changed, 62 insertions(+), 37 deletions(-) diff --git a/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts b/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts index 2e9d8ec523c..0261e01f23d 100644 --- a/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts +++ b/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts @@ -92,7 +92,7 @@ const posixNameCases: MaterializationCase[] = [ command: 'snapshot', localPath: 'outside/shot.png', fileName: 'C:shot.png', - expected: 'cwd/C:shot.png', + generatedName: /^C:shot-[0-9a-f-]{36}\.png$/, }, { name: 'POSIX keeps a colon in the generated basename', @@ -100,7 +100,7 @@ const posixNameCases: MaterializationCase[] = [ localPath: 'outside/shot.png', field: 'subdir/c:path', fileName: '', - generatedName: /^c:path-\d+$/, + generatedName: /^c:path-\d+-[0-9a-f-]{36}$/, }, ]; @@ -114,11 +114,19 @@ test.for([ expected: 'client/shot.png', }, { - name: 'an unregistered response localPath and file name stay in cwd', + name: 'an unregistered response name cannot replace an existing cwd file', command: 'snapshot', localPath: 'outside/x', fileName: '../../x', - expected: 'cwd/x', + generatedName: /^x-[0-9a-f-]{36}$/, + protectedPath: 'cwd/x', + }, + { + name: 'a long response name leaves room for the client suffix', + command: 'snapshot', + localPath: 'outside/long.mp4', + fileName: `${'a'.repeat(220)}.mp4`, + generatedName: /^a+-[0-9a-f-]{36}\.mp4$/, }, { name: 'an omitted file name generates a destination in cwd', @@ -130,7 +138,7 @@ test.for([ command: 'close', localPath: 'outside/shot.png', fileName: 'shot.png', - expected: 'cwd/shot.png', + generatedName: /^shot-[0-9a-f-]{36}\.png$/, }, { name: 'a record start refuses a response localPath', @@ -138,7 +146,7 @@ test.for([ positionals: ['start'], localPath: 'outside/clip.mp4', fileName: 'clip.mp4', - expected: 'cwd/clip.mp4', + generatedName: /^clip-[0-9a-f-]{36}\.mp4$/, }, { name: 'a perf cpu profile stop ignores the daemon echo of its start destination', @@ -205,7 +213,8 @@ test.for([ expect(saved).toEqual(c.expected ? inRoot(c.expected) : expect.any(String)); if (!c.expected) { expect(path.dirname(String(saved))).toBe(inRoot('cwd')); - expect(path.basename(String(saved))).toMatch(c.generatedName ?? /^path-\d+$/); + expect(path.basename(String(saved))).toMatch(c.generatedName ?? /^path-\d+-[0-9a-f-]{36}$/); + expect(Buffer.byteLength(path.basename(String(saved)))).toBeLessThanOrEqual(255); } expect(fs.readFileSync(String(saved), 'utf8')).toBe('artifact-bytes'); if (c.protectedPath) expect(fs.readFileSync(inRoot(c.protectedPath), 'utf8')).toBe('protected'); diff --git a/packages/remote/src/__tests__/daemon-artifacts-record-download.test.ts b/packages/remote/src/__tests__/daemon-artifacts-record-download.test.ts index f0304edc06a..4d7824e6046 100644 --- a/packages/remote/src/__tests__/daemon-artifacts-record-download.test.ts +++ b/packages/remote/src/__tests__/daemon-artifacts-record-download.test.ts @@ -75,7 +75,9 @@ test('record stop ignores the daemon localPath and warns about the cwd download' await withRecordingServer(t, async (cwd, stop) => { const hostile = path.resolve(cwd, '../hostile.mp4'); const data = await stop([{ ...video, localPath: hostile }]); - const fallback = path.join(cwd, 'clip.mp4'); + const fallback = String(data?.outPath); + expect(path.dirname(fallback)).toBe(cwd); + expect(path.basename(fallback)).toMatch(/^clip-[0-9a-f-]{36}\.mp4$/); expect(fs.existsSync(hostile)).toBe(false); expect(fs.readFileSync(fallback, 'utf8')).toBe('video'); expect(data).toMatchObject({ @@ -103,17 +105,19 @@ test('record stop uses the destination named in the current request', async (t) }); }); -test('record stop replaces a destination symlink without writing through it', async (t) => { +test('unnamed record stop leaves an existing destination symlink untouched', async (t) => { await withRecordingServer(t, async (cwd, stop) => { const destination = path.join(cwd, 'clip.mp4'); const target = path.resolve(cwd, '../target'); fs.writeFileSync(target, 'original'); fs.symlinkSync(target, destination); - await stop([video]); + const data = await stop([video]); + const saved = String(data?.outPath); expect(fs.readFileSync(target, 'utf8')).toBe('original'); - expect(fs.lstatSync(destination).isFile()).toBe(true); - expect(fs.readFileSync(destination, 'utf8')).toBe('video'); - expect(fs.readdirSync(cwd)).toEqual(['clip.mp4']); + expect(fs.lstatSync(destination).isSymbolicLink()).toBe(true); + expect(path.basename(saved)).toMatch(/^clip-[0-9a-f-]{36}\.mp4$/); + expect(fs.readFileSync(saved, 'utf8')).toBe('video'); + expect(fs.readdirSync(cwd)).toHaveLength(2); }); }); @@ -125,6 +129,7 @@ test.for([ 'nested/clip.mp4', String.raw`x\clip.mp4`, 'x\n.mp4', + `${'a'.repeat(250)}.mp4`, ])('record stop generates a name in cwd for %j', async (fileName, t) => { await withRecordingServer(t, async (cwd, stop) => { const data = await stop([{ ...video, fileName }]); @@ -190,21 +195,25 @@ test('record stop downloads each chunk and telemetry to cwd', async (t) => { { index: 1, path: '/daemon/second.mp4' }, ], ); - const second = path.join(cwd, 'second.mp4'); - const telemetry = path.join(cwd, 'telemetry.json'); - expect(fs.readFileSync(path.join(cwd, 'clip.mp4'), 'utf8')).toBe('video'); + const first = String(data?.outPath); + const second = String((data?.chunks as Array<{ path: string }> | undefined)?.[1]?.path); + const telemetry = String(data?.telemetryPath); + expect(path.basename(first)).toMatch(/^clip-[0-9a-f-]{36}\.mp4$/); + expect(path.basename(second)).toMatch(/^second-[0-9a-f-]{36}\.mp4$/); + expect(path.basename(telemetry)).toMatch(/^telemetry-[0-9a-f-]{36}\.json$/); + expect(fs.readFileSync(first, 'utf8')).toBe('video'); expect(fs.readFileSync(second, 'utf8')).toBe('chunk'); expect(fs.readFileSync(telemetry, 'utf8')).toBe('telemetry'); expect(fs.existsSync(path.resolve(cwd, '../second.mp4'))).toBe(false); expect(fs.existsSync(path.resolve(cwd, '../telemetry.json'))).toBe(false); expect(data).toMatchObject({ chunks: [ - { index: 0, path: path.join(cwd, 'clip.mp4') }, + { index: 0, path: first }, { index: 1, path: second }, ], telemetryPath: telemetry, recordingDestinationWarnings: [ - { field: 'outPath', path: path.join(cwd, 'clip.mp4') }, + { field: 'outPath', path: first }, { field: 'chunkPath', path: second }, { field: 'telemetryPath', path: telemetry }, ], diff --git a/packages/remote/src/daemon-artifacts.ts b/packages/remote/src/daemon-artifacts.ts index 0a2f5bb9f17..5b57f2bae9b 100644 --- a/packages/remote/src/daemon-artifacts.ts +++ b/packages/remote/src/daemon-artifacts.ts @@ -727,7 +727,7 @@ function isRecordStop(req: DaemonWireRequest): boolean { } /** - * A path from this request wins. A record stop without one can use only a plain name in cwd. + * A path from this request wins. Every unnamed artifact gets a unique client file in cwd. * A NUL in a response file name cannot provide a fallback destination. */ function resolveMaterializedArtifactPath( @@ -744,19 +744,26 @@ function resolveMaterializedArtifactPath( } if (typeof artifact.fileName === 'string' && artifact.fileName.includes('\0')) return undefined; const fileName = localFileName(artifact.fileName) ?? `recording-${crypto.randomUUID()}`; - return { path: path.resolve(req.meta?.cwd ?? host.cwd, fileName), fallback: true }; + return { path: uniqueClientArtifactPath(path.resolve(req.meta?.cwd ?? host.cwd, fileName)), fallback: true }; } const fallbackPath = resolveOrdinaryArtifactFallbackPath(artifact, req.meta?.cwd ?? host.cwd); - if (!fallbackPath) return undefined; - if (req.command === 'trace' || req.command === 'perf') { - const extension = path.extname(fallbackPath); - const stem = path.basename(fallbackPath, extension); - return { - path: path.join(path.dirname(fallbackPath), `${stem}-${crypto.randomUUID()}${extension}`), - fallback: false, - }; + return fallbackPath ? { path: uniqueClientArtifactPath(fallbackPath), fallback: false } : undefined; +} + +function uniqueClientArtifactPath(candidate: string): string { + const rawExtension = path.extname(candidate); + const extension = Buffer.byteLength(rawExtension) <= 64 ? rawExtension : ''; + const suffix = `-${crypto.randomUUID()}${extension}`; + const stemBudget = 255 - Buffer.byteLength(suffix); + let stem = ''; + let stemBytes = 0; + for (const character of path.basename(candidate, rawExtension)) { + const nextBytes = Buffer.byteLength(character); + if (stemBytes + nextBytes > stemBudget) break; + stem += character; + stemBytes += nextBytes; } - return { path: fallbackPath, fallback: false }; + return path.join(path.dirname(candidate), `${stem || 'artifact'}${suffix}`); } function resolveOrdinaryArtifactFallbackPath( diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 63497fe8c9c..f7980ab9fff 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -94,14 +94,14 @@ The daemon itself cannot pick a device by these keys, so it refuses a named key Remote screenshots, recordings, performance captures, and trace logs use generated output paths on the daemon. When you specify an output path through the CLI, SDK, or MCP, it selects the download -destination on your machine. A recording is different: it downloads to the path named by the -`record stop` request, or otherwise to the working directory with a warning. The directory of a -`record start` path does not carry over; the working-directory fallback keeps only its file name. Direct RPC callers receive artifact IDs and download each result with -`GET /artifacts/` using the same authentication. - -For trace and performance stop or report, a destination on the current request wins. Without one, -the client chooses a unique file in its working directory from the artifact file name. A path -echoed by the daemon from an earlier request cannot select the client destination. +destination on your machine. A recording downloads to the path named by the `record stop` +request. Without one, it downloads to a unique file in the working directory with a warning. +The directory of a `record start` path does not carry over. Direct RPC callers receive artifact IDs +and download each result with `GET /artifacts/` using the same authentication. + +For every artifact without a destination on the current request, the client appends a unique suffix +to the artifact file name in its working directory. A daemon-provided name or path cannot select an +existing client file, including for trace and performance stop or report. By default, artifacts leave the inventory after download or after 15 minutes. `AGENT_DEVICE_RETAIN_ARTIFACTS` keeps downloaded artifacts in inventory until expiry. Downloads already in progress From 04c5bd29f88c4ec495978a7af4c2b89cfd769626 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 15:27:08 +0100 Subject: [PATCH 08/55] chore(gates): format security boundary changes --- packages/remote/src/daemon-artifacts.ts | 9 +++++++-- test/repo-guards/maestro-regex-owner.test.ts | 11 ++++++----- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/packages/remote/src/daemon-artifacts.ts b/packages/remote/src/daemon-artifacts.ts index 5b57f2bae9b..5470a92fc03 100644 --- a/packages/remote/src/daemon-artifacts.ts +++ b/packages/remote/src/daemon-artifacts.ts @@ -744,10 +744,15 @@ function resolveMaterializedArtifactPath( } if (typeof artifact.fileName === 'string' && artifact.fileName.includes('\0')) return undefined; const fileName = localFileName(artifact.fileName) ?? `recording-${crypto.randomUUID()}`; - return { path: uniqueClientArtifactPath(path.resolve(req.meta?.cwd ?? host.cwd, fileName)), fallback: true }; + return { + path: uniqueClientArtifactPath(path.resolve(req.meta?.cwd ?? host.cwd, fileName)), + fallback: true, + }; } const fallbackPath = resolveOrdinaryArtifactFallbackPath(artifact, req.meta?.cwd ?? host.cwd); - return fallbackPath ? { path: uniqueClientArtifactPath(fallbackPath), fallback: false } : undefined; + return fallbackPath + ? { path: uniqueClientArtifactPath(fallbackPath), fallback: false } + : undefined; } function uniqueClientArtifactPath(candidate: string): string { diff --git a/test/repo-guards/maestro-regex-owner.test.ts b/test/repo-guards/maestro-regex-owner.test.ts index 1e146718f0e..26fe0a7df35 100644 --- a/test/repo-guards/maestro-regex-owner.test.ts +++ b/test/repo-guards/maestro-regex-owner.test.ts @@ -45,11 +45,12 @@ function regexBypassViolations(source: string, filePath: string): string[] { const node = value as Node; if (node.type === 'NewExpression' || node.type === 'CallExpression') { const callee = node.callee; - const name = callee?.type === 'Identifier' - ? callee.name - : callee?.type === 'MemberExpression' - ? (callee.property?.name ?? callee.property?.value) - : undefined; + const name = + callee?.type === 'Identifier' + ? callee.name + : callee?.type === 'MemberExpression' + ? (callee.property?.name ?? callee.property?.value) + : undefined; const implicitRegex = node.type === 'CallExpression' && callee?.type === 'MemberExpression' && From d10bbc35a5d00c002c9254eebd0bedb7f5f30aa8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 16:15:38 +0100 Subject: [PATCH 09/55] test(remote): record unique artifact destinations in compatibility checks --- .../provider-scenarios/remote-daemon-client.test.ts | 7 ++++--- test/wire-compat/ledger.json | 6 +++--- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/test/integration/provider-scenarios/remote-daemon-client.test.ts b/test/integration/provider-scenarios/remote-daemon-client.test.ts index ca2e0a2d1f4..78b4aed2973 100644 --- a/test/integration/provider-scenarios/remote-daemon-client.test.ts +++ b/test/integration/provider-scenarios/remote-daemon-client.test.ts @@ -549,11 +549,12 @@ async function assertRecordingArtifactRoundTrip( assert.equal(fs.existsSync(paths.recordingPath), false); // #4518: a remote stop never writes to the daemon's localPath echo. It lands in the client cwd - // under the daemon's file name and reports that fallback. + // under a unique client filename and reports that fallback. const stop = await client.recording.record({ action: 'stop' }); assert.equal(stop.recording, 'stopped'); - const landed = path.join(paths.cwd, 'remote-recording.mp4'); - assert.equal(stop.outPath, landed); + const landed = stop.outPath; + assert.equal(path.dirname(landed), paths.cwd); + assert.match(path.basename(landed), /^remote-recording-[0-9a-f-]{36}\.mp4$/); assert.deepEqual(fs.readFileSync(landed), RECORDING_BYTES); assert.equal(fs.existsSync(paths.recordingPath), false); assert.deepEqual( diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 08d1d3f2605..4d320331ce6 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -160,7 +160,7 @@ "packages/remote/src/daemon-artifacts.ts#downloadRemoteArtifact": "sha256:3f3b6c01601c54ab2c76c8cb0946de623da4d24ba32254c75ae8a3993f66adcf", "packages/remote/src/daemon-artifacts.ts#isRemoteDaemon": "sha256:0f6a714c5f60ce4e8548d811b516d8b6241eca9f7e5414733732da395b8a00e7", "packages/remote/src/daemon-artifacts.ts#materializeRemoteArtifacts": "sha256:6d9aba219e6fafbdbcef76d30ed99fbb4f61dcc525242a0a76c3dc1bdacd24e2", - "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath": "sha256:847b619e378503cfa8a42884534e2947b9f4d2503cf0bdfbd3db101c274c069e", + "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath": "sha256:0495174ab15a8c5a7c159eb957d3fc463a856b151c47a77cf0d567eb9843ee21", "packages/remote/src/daemon-artifacts.ts#resolveOrdinaryArtifactFallbackPath": "sha256:e8b1cb5243194e1d4fc7e376979ca5aae3aaf55cfdd33102e1410b2033fb3a4f", "packages/remote/src/remote-request-diagnostics.ts#RemoteDaemonErrorPayload": "sha256:8fbcbcdf4bae7b66a08e465a72593794f36364759f18f1a814cd39dfdb76f309", "packages/remote/src/remote-request-diagnostics.ts#RemoteDiagnosticsEndpoint": "sha256:c1d5fe2fe90c425502cf8b7c87d6606374d6af65b4e9faf942a416f683930bdc", @@ -539,8 +539,8 @@ }, { "declaration": "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath", - "digest": "sha256:847b619e378503cfa8a42884534e2947b9f4d2503cf0bdfbd3db101c274c069e", - "rationale": "Client-side trace and perf completion no longer trusts an artifact.localPath echoed by the daemon. Without a caller path, the client chooses a new random-suffixed destination under its fallback directory. Daemons send the same artifact fields with the same framing, and older peers can ignore this client's destination choice." + "digest": "sha256:0495174ab15a8c5a7c159eb957d3fc463a856b151c47a77cf0d567eb9843ee21", + "rationale": "Client-side materialization now chooses a unique filename for every unnamed remote artifact, including recordings, and still honors an explicit caller path. It ignores daemon-provided localPath as a destination and uses the daemon filename only as a sanitized stem. The daemon sends the same fields and framing, and an older peer can ignore this client's local destination choice." }, { "declaration": "packages/daemon/src/server/http/http-server.ts#MAX_HTTP_RPC_BODY_BYTES", From 015c9496acdef05d5c034caa072ef656e1cce3b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 16:30:27 +0100 Subject: [PATCH 10/55] refactor(gates): keep Maestro regex guard traversal focused --- test/repo-guards/maestro-regex-owner.test.ts | 36 +++++++++++--------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/test/repo-guards/maestro-regex-owner.test.ts b/test/repo-guards/maestro-regex-owner.test.ts index 26fe0a7df35..8061eff84b5 100644 --- a/test/repo-guards/maestro-regex-owner.test.ts +++ b/test/repo-guards/maestro-regex-owner.test.ts @@ -36,6 +36,22 @@ function regexBypassViolations(source: string, filePath: string): string[] { arguments?: Node[]; [key: string]: unknown; }; + function calledName(callee: Node | undefined): unknown { + if (callee?.type === 'Identifier') return callee.name; + if (callee?.type === 'MemberExpression') return callee.property?.name ?? callee.property?.value; + return undefined; + } + function isRegexBypass(node: Node): boolean { + if (node.type !== 'NewExpression' && node.type !== 'CallExpression') return false; + const name = calledName(node.callee); + if (name === 'RegExp') return true; + return ( + node.type === 'CallExpression' && + node.callee?.type === 'MemberExpression' && + (name === 'match' || name === 'matchAll' || name === 'search') && + node.arguments?.[0]?.regex === undefined + ); + } function visit(value: unknown): void { if (!value || typeof value !== 'object') return; if (Array.isArray(value)) { @@ -43,23 +59,9 @@ function regexBypassViolations(source: string, filePath: string): string[] { return; } const node = value as Node; - if (node.type === 'NewExpression' || node.type === 'CallExpression') { - const callee = node.callee; - const name = - callee?.type === 'Identifier' - ? callee.name - : callee?.type === 'MemberExpression' - ? (callee.property?.name ?? callee.property?.value) - : undefined; - const implicitRegex = - node.type === 'CallExpression' && - callee?.type === 'MemberExpression' && - (name === 'match' || name === 'matchAll' || name === 'search') && - node.arguments?.[0]?.regex === undefined; - if (name === 'RegExp' || implicitRegex) { - const line = source.slice(0, node.start).split('\n').length; - violations.push(`${path.relative(SOURCE_ROOT, filePath)}:${line}`); - } + if (isRegexBypass(node)) { + const line = source.slice(0, node.start).split('\n').length; + violations.push(`${path.relative(SOURCE_ROOT, filePath)}:${line}`); } for (const child of Object.values(node)) visit(child); } From 7b429868b5f05aea47bd592b3523ab8180ccc511 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 17:41:43 +0100 Subject: [PATCH 11/55] fix: retain overlong artifact extension in bounded client name Clarify Maestro selector value length behavior. --- .../remote/src/__tests__/daemon-artifacts-capture.test.ts | 7 +++++++ packages/remote/src/daemon-artifacts.ts | 6 ++++-- website/docs/docs/run-maestro-flows.md | 2 +- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts b/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts index 0261e01f23d..a335ee4b223 100644 --- a/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts +++ b/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts @@ -128,6 +128,13 @@ test.for([ fileName: `${'a'.repeat(220)}.mp4`, generatedName: /^a+-[0-9a-f-]{36}\.mp4$/, }, + { + name: 'a long extension stays in the truncated response name', + command: 'snapshot', + localPath: 'outside/long', + fileName: `a.${'b'.repeat(230)}`, + generatedName: /^a\.b+-[0-9a-f-]{36}$/, + }, { name: 'an omitted file name generates a destination in cwd', command: 'snapshot', diff --git a/packages/remote/src/daemon-artifacts.ts b/packages/remote/src/daemon-artifacts.ts index 5470a92fc03..24afd889b48 100644 --- a/packages/remote/src/daemon-artifacts.ts +++ b/packages/remote/src/daemon-artifacts.ts @@ -757,12 +757,14 @@ function resolveMaterializedArtifactPath( function uniqueClientArtifactPath(candidate: string): string { const rawExtension = path.extname(candidate); - const extension = Buffer.byteLength(rawExtension) <= 64 ? rawExtension : ''; + const keepExtension = Buffer.byteLength(rawExtension) <= 64; + const extension = keepExtension ? rawExtension : ''; const suffix = `-${crypto.randomUUID()}${extension}`; const stemBudget = 255 - Buffer.byteLength(suffix); let stem = ''; let stemBytes = 0; - for (const character of path.basename(candidate, rawExtension)) { + const rawStem = keepExtension ? path.basename(candidate, rawExtension) : path.basename(candidate); + for (const character of rawStem) { const nextBytes = Buffer.byteLength(character); if (stemBytes + nextBytes > stemBudget) break; stem += character; diff --git a/website/docs/docs/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index 559b5cf4179..de2d0bc6686 100644 --- a/website/docs/docs/run-maestro-flows.md +++ b/website/docs/docs/run-maestro-flows.md @@ -30,7 +30,7 @@ Keep the target binding, such as `--platform ios`, on the `replay` or `test` com ## Boundaries -- Selector `id` and `text` patterns allow at most one `*`, `+`, or `?` repetition on a single character or escaped character class such as `\d`. Groups, alternatives, bracket classes, counted repeats, backreferences, patterns over 256 characters, and values over 8192 characters fail with `maestro_selector_regex_unsafe` to keep matching bounded. +- Selector `id` and `text` patterns allow at most one `*`, `+`, or `?` repetition on a single character or escaped character class such as `\d`. Groups, alternatives, bracket classes, counted repeats, backreferences, and patterns over 256 characters fail with `maestro_selector_regex_unsafe`. A node value over 8192 characters never matches. These limits keep matching bounded. - 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 1413a2d0fd9426e2e3422e89a95b6788c2dd20ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 18:06:15 +0100 Subject: [PATCH 12/55] fix: restrict remote artifact extraction and Windows names --- .../daemon-artifacts-capture.test.ts | 23 ++++++++++++++++++- packages/remote/src/daemon-artifacts.ts | 14 ++++++----- 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts b/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts index a335ee4b223..6937762fbed 100644 --- a/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts +++ b/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts @@ -81,6 +81,7 @@ type MaterializationCase = { localPath: string; field?: string; fileName?: string; + artifactType?: string; expected?: string; generatedName?: RegExp; protectedPath?: string; @@ -135,6 +136,14 @@ test.for([ fileName: `a.${'b'.repeat(230)}`, generatedName: /^a\.b+-[0-9a-f-]{36}$/, }, + { + name: 'a snapshot response cannot select directory extraction', + command: 'snapshot', + localPath: 'outside/archive.tar', + fileName: 'archive.tar', + artifactType: 'test-artifacts', + generatedName: /^archive-[0-9a-f-]{36}\.tar$/, + }, { name: 'an omitted file name generates a destination in cwd', command: 'snapshot', @@ -205,7 +214,7 @@ test.for([ { artifactId: 'a1', field, - artifactType: 'screenshot', + artifactType: c.artifactType ?? 'screenshot', path: '/daemon/x', localPath: inRoot(c.localPath), ...(c.fileName === undefined ? {} : { fileName: c.fileName }), @@ -254,6 +263,18 @@ test.for([ fileName: '', platform: 'win32', }, + { + name: 'a Windows alternate data stream in the response basename', + field: 'path', + fileName: 'report.txt:trace.log', + platform: 'win32', + }, + { + name: 'a Windows alternate data stream in the generated basename', + field: 'report.txt:trace.log', + fileName: '', + platform: 'win32', + }, ])('a remote artifact with $name is dropped and the action result is kept', async (c, t) => { if (await skipWhenLoopbackUnavailable(t, 'remote artifact download')) return; const root = mkdtempForTestSync('agent-device-remote-artifact-invalid-name-'); diff --git a/packages/remote/src/daemon-artifacts.ts b/packages/remote/src/daemon-artifacts.ts index 24afd889b48..fb3f91431b9 100644 --- a/packages/remote/src/daemon-artifacts.ts +++ b/packages/remote/src/daemon-artifacts.ts @@ -604,11 +604,13 @@ async function downloadOneArtifact( artifactId: artifact.artifactId, destinationPath: destination.path, requestScope: req.meta, - // #2246: `test-artifacts` is the one directory-shaped artifact type today — known from the - // response, before any bytes arrive, so cleanup-on-error can be decided up front instead of - // racing the response headers (a directory destination must never be `rm`'d wholesale; see - // `downloadRemoteArtifact`). - isDirectory: recording === undefined && artifact.artifactType === 'test-artifacts', + // #2246: Only a test request's artifactsDir may select directory extraction. Decide before + // bytes arrive so cleanup-on-error cannot remove a directory destination wholesale. + isDirectory: + recording === undefined && + req.command === 'test' && + artifact.field === 'artifactsDir' && + artifact.artifactType === 'test-artifacts', stagedFile: recording !== undefined, }); recording?.add(artifact.field, materializedPath, destination.fallback); @@ -785,7 +787,7 @@ function resolveOrdinaryArtifactFallbackPath( responseName && responseName !== '.' && responseName !== '..' ? responseName : `${pathRules.basename(artifact.field)}-${Date.now()}`; - if (pathRules === path.win32 && /^[a-z]:/i.test(fileName)) return undefined; + if (pathRules === path.win32 && fileName.includes(':')) return undefined; return pathRules.resolve(cwd, fileName); } From fa4f1bb48681cdf21a8fd938c18a339bd1fc8853 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 18:06:25 +0100 Subject: [PATCH 13/55] fix: admit safe Maestro patterns with a bounded matcher --- packages/maestro/package.json | 1 + .../internal/__tests__/selector-regex.test.ts | 58 +++++++- .../maestro/src/internal/selector-regex.ts | 125 ++++++++++++------ pnpm-lock.yaml | 3 + website/docs/docs/run-maestro-flows.md | 2 +- 5 files changed, 143 insertions(+), 46 deletions(-) diff --git a/packages/maestro/package.json b/packages/maestro/package.json index e21431628e5..60ffbec8a38 100644 --- a/packages/maestro/package.json +++ b/packages/maestro/package.json @@ -6,6 +6,7 @@ "type": "module", "description": "Private Maestro compatibility engine for agent-device.", "dependencies": { + "@eslint-community/regexpp": "4.12.2", "@agent-device/ad-script": "workspace:*", "@agent-device/capture-kit": "workspace:*", "@agent-device/contracts": "workspace:*", diff --git a/packages/maestro/src/internal/__tests__/selector-regex.test.ts b/packages/maestro/src/internal/__tests__/selector-regex.test.ts index 8237aa0dba2..152b05c4735 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -1,17 +1,24 @@ -import { expect, test } from 'vitest'; +import { RegExpParser } from '@eslint-community/regexpp'; +import { expect, test, vi } from 'vitest'; import { literalFromMaestroRegex, matchesMaestroRegex } from '../selector-regex.ts'; test('matches Maestro regex as case-insensitive full patterns', () => { expect(matchesMaestroRegex('Item 22\nready', String.raw`item \d\d.+ready`)).toBe(true); - expect(() => matchesMaestroRegex('Item 22\nready', String.raw`item \d{2}.+ready`)).toThrow(); + 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 \\', 'item \\')).toBe(true); + expect(matchesMaestroRegex('Sign in', '.*Sign in.*')).toBe(true); + expect(matchesMaestroRegex('candidate-low', 'candidate-(low|high)')).toBe(true); + expect(matchesMaestroRegex('item 22', String.raw`item [0-9]+`)).toBe(true); + expect(matchesMaestroRegex('Item 22 ready', String.raw`Item \d+\s+ready`)).toBe(true); + expect(matchesMaestroRegex('Item 8', String.raw`Item \8`)).toBe(true); }); test.each([ '(a+)+', '(a|aa)+', 'a*a*', + 'a*b*a*', '(a+){2}', String.raw`(a+)\1`, '(a|aa)(a|aa)(a|aa)(a|aa)(a|aa)(a|aa)', @@ -31,23 +38,60 @@ test('extracts only patterns that are exact literals', () => { expect(literalFromMaestroRegex('item [ready')).toBe('item [ready'); }); -test('long device labels do not invalidate a bounded selector', () => { +test('long device labels keep literal matches but cannot silently pass regex absence', () => { expect(matchesMaestroRegex('a'.repeat(8193), 'item')).toBe(false); + expect(matchesMaestroRegex('a'.repeat(8193), 'a'.repeat(8193))).toBe(true); + expect(() => matchesMaestroRegex(`Details: ${'x'.repeat(8300)} End`, 'Details: x+ End')).toThrow( + expect.objectContaining({ + code: 'INVALID_ARGS', + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); expect(matchesMaestroRegex('item', 'item')).toBe(true); }); test('escaped brackets and braces match literal node text', () => { expect(matchesMaestroRegex('a(b', String.raw`a\(b`)).toBe(true); expect(matchesMaestroRegex('price {2}', String.raw`price \{2\}`)).toBe(true); - expect(() => matchesMaestroRegex('price 22', String.raw`price {2}`)).toThrow(); + expect(matchesMaestroRegex('price 22', String.raw`price {2}`)).toBe(false); }); -test('validates the pattern before normalized literal matching', () => { +test('literal matches do not run the regex guard', () => { expect(matchesMaestroRegex(' Save now ', 'save now')).toBe(true); - expect(() => matchesMaestroRegex('a'.repeat(257), 'a'.repeat(257))).toThrow(); - expect(() => matchesMaestroRegex('a*a*', 'a*a*')).toThrow( + expect(matchesMaestroRegex('a'.repeat(257), 'a'.repeat(257))).toBe(true); + expect(matchesMaestroRegex('a*a*', 'a*a*')).toBe(true); + expect(matchesMaestroRegex('Item 22 [ready', 'Item 22 [ready')).toBe(true); + expect(matchesMaestroRegex('Terms | Privacy', 'Terms | Privacy')).toBe(true); + expect(() => matchesMaestroRegex('a'.repeat(256), 'a'.repeat(257))).toThrow( expect.objectContaining({ details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), }), ); }); + +test('reuses a parsed selector pattern across node values', () => { + const parse = vi.spyOn(RegExpParser.prototype, 'parsePattern'); + try { + expect(matchesMaestroRegex('memoized-123', 'memoized-[0-9]+')).toBe(true); + expect(matchesMaestroRegex('memoized-abc', 'memoized-[0-9]+')).toBe(false); + expect(parse).toHaveBeenCalledTimes(1); + } finally { + parse.mockRestore(); + } +}); + +test('reports a parser failure through the typed selector reason', () => { + const parse = vi.spyOn(RegExpParser.prototype, 'parsePattern').mockImplementationOnce(() => { + throw new SyntaxError('unsupported parser syntax'); + }); + try { + expect(() => matchesMaestroRegex('parser-error-123', 'parser-error-[0-9]+')).toThrow( + expect.objectContaining({ + code: 'INVALID_ARGS', + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); + } finally { + parse.mockRestore(); + } +}); diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index 7065066fa38..f5adc370e02 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -1,4 +1,5 @@ import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; +import { RegExpParser, visitRegExpAST, type AST } from '@eslint-community/regexpp'; import { normalizeText } from './shared.ts'; const MAESTRO_SELECTOR_REGEX_REASONS = { @@ -9,55 +10,103 @@ const MAESTRO_SELECTOR_REGEX_REASONS = { const REGEX_SYNTAX = new Set(String.raw`^$\.*+?()[]{}|`); const MAX_PATTERN_LENGTH = 256; const MAX_VALUE_LENGTH = 8192; -const UNSUPPORTED_PATTERN_SYNTAX = new Set(['(', ')', '{', '}', '|', '[', ']']); -const VARIABLE_QUANTIFIERS = new Set(['*', '+', '?']); +const MAX_CACHED_PATTERNS = 128; +const parser = new RegExpParser(); +const matcherCache = new Map(); export function matchesMaestroRegex(value: string, pattern: string): boolean { - if (pattern.length > MAX_PATTERN_LENGTH) unsafeMaestroRegex(); - assertBoundedMaestroPattern(pattern); - if (value.length > MAX_VALUE_LENGTH) return false; if (normalizeText(value) === normalizeText(pattern)) return true; - try { - return new RegExp(`^(?:${pattern})$`, 'ims').test(value); - } catch { - return value.toLocaleLowerCase() === pattern.toLocaleLowerCase(); + const matcher = matcherForPattern(pattern); + if ('literal' in matcher) + return value.toLocaleLowerCase() === matcher.literal.toLocaleLowerCase(); + if (value.length > MAX_VALUE_LENGTH) unsafeMaestroRegex(); + return matcher.regex.test(value); +} + +function matcherForPattern(pattern: string): { literal: string } | { regex: RegExp } { + if (pattern.length > MAX_PATTERN_LENGTH) unsafeMaestroRegex(); + const cached = matcherCache.get(pattern); + if (cached) return cached; + const literal = literalFromMaestroRegex(pattern); + let matcher: { literal: string } | { regex: RegExp }; + if (literal !== undefined) { + matcher = { literal }; + } else { + assertBoundedMaestroPattern(pattern); + try { + matcher = { regex: new RegExp(`^(?:${pattern})$`, 'ims') }; + } catch { + unsafeMaestroRegex(); + } + } + if (matcherCache.size >= MAX_CACHED_PATTERNS) { + matcherCache.delete(matcherCache.keys().next().value!); } + matcherCache.set(pattern, matcher); + return matcher; } -// No groups, alternatives, classes, or counted repeats means one variable quantifier can only -// repeat one atom. The matcher has linear work for this deliberately narrow subset. function assertBoundedMaestroPattern(pattern: string): void { - let escaped = false; - for (const character of pattern) { - if (escaped) { - if (/[1-9]/.test(character)) unsafeMaestroRegex(); - escaped = false; - continue; - } - if (character === '\\') { - escaped = true; - continue; - } - if (UNSUPPORTED_PATTERN_SYNTAX.has(character)) unsafeMaestroRegex(); + let parsed: AST.Pattern; + try { + parsed = parser.parsePattern(pattern); + } catch { + unsafeMaestroRegex(); } - if (countVariableQuantifiers(pattern) > 1) unsafeMaestroRegex(); + let ambiguousGroups = 0; + const countAlternatives = (count: number): void => { + if (count > 1 && ++ambiguousGroups > 4) unsafeMaestroRegex(); + }; + visitRegExpAST(parsed, { + onBackreferenceEnter: unsafeMaestroRegex, + onGroupEnter(node) { + countAlternatives(node.alternatives.length); + }, + onCapturingGroupEnter(node) { + countAlternatives(node.alternatives.length); + }, + onQuantifierEnter(node) { + if (node.element.type !== 'Group' && node.element.type !== 'CapturingGroup') return; + if (node.element.alternatives.length > 1) unsafeMaestroRegex(); + visitRegExpAST(node.element, { onQuantifierEnter: unsafeMaestroRegex }); + }, + onAlternativeEnter(node) { + for (let index = 0; index < node.elements.length; index += 1) { + const first = node.elements[index]; + if (first?.type !== 'Quantifier' || first.max === first.min) continue; + for (let next = index + 1; next < node.elements.length; next += 1) { + const element = node.elements[next]; + if (element?.type === 'Assertion') continue; + if (element?.type === 'Quantifier') { + if ( + element.max > element.min && + !quantifiedAtomsAreDisjoint(first.element, element.element) + ) { + unsafeMaestroRegex(); + } + if (element.min === 0) continue; + } + break; + } + } + }, + }); } -function countVariableQuantifiers(pattern: string): number { - let escaped = false; - let count = 0; - for (const character of pattern) { - if (escaped) { - escaped = false; - continue; - } - if (character === '\\') { - escaped = true; - continue; - } - if (VARIABLE_QUANTIFIERS.has(character)) count += 1; +function quantifiedAtomsAreDisjoint( + left: AST.QuantifiableElement, + right: AST.QuantifiableElement, +): boolean { + if (left.type === 'Character' && right.type === 'Character') { + return ( + String.fromCodePoint(left.value).toLocaleLowerCase() !== + String.fromCodePoint(right.value).toLocaleLowerCase() + ); } - return count; + return ( + (left.raw === String.raw`\d` && right.raw === String.raw`\s`) || + (left.raw === String.raw`\s` && right.raw === String.raw`\d`) + ); } function unsafeMaestroRegex(): never { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 311e223d79e..25d7755d6ed 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -713,6 +713,9 @@ importers: packages/maestro: dependencies: + '@eslint-community/regexpp': + specifier: 4.12.2 + version: 4.12.2 '@agent-device/ad-script': specifier: workspace:* version: link:../ad-script diff --git a/website/docs/docs/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index de2d0bc6686..c82b034d73a 100644 --- a/website/docs/docs/run-maestro-flows.md +++ b/website/docs/docs/run-maestro-flows.md @@ -30,7 +30,7 @@ Keep the target binding, such as `--platform ios`, on the `replay` or `test` com ## Boundaries -- Selector `id` and `text` patterns allow at most one `*`, `+`, or `?` repetition on a single character or escaped character class such as `\d`. Groups, alternatives, bracket classes, counted repeats, backreferences, and patterns over 256 characters fail with `maestro_selector_regex_unsafe`. A node value over 8192 characters never matches. These limits keep matching bounded. +- Selector `id` and `text` match exact text before interpreting a pattern as a regular expression. Regex patterns can use groups, alternatives, character classes, and counted or disjoint repetitions. Backreferences, overlapping repetitions, quantified groups with alternatives or repetitions, excessive ambiguous groups, and regex patterns over 256 characters fail with `maestro_selector_regex_unsafe`. A regex against a node value over 8192 characters also fails with that reason; an exact text match remains available. These limits keep matching bounded. - 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 3c9ae22b52dda4706fbefa336883eaeaca5a56ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 18:06:31 +0100 Subject: [PATCH 14/55] docs: align transport guidance with refusal behavior --- website/docs/docs/remote-proxy.md | 2 +- website/docs/docs/security-trust.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index f7980ab9fff..f8684f936e7 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -29,7 +29,7 @@ The command prints the local proxy URL and a `daemon auth token`. Keep the token By default the proxy binds `127.0.0.1`. Use `--host 0.0.0.0` only when you want the proxy reachable from the host network. -Reach the proxy from another machine over an `https://` tunnel URL, or forward a local port with `ssh -L 4310:127.0.0.1:4310 ` and connect to `http://127.0.0.1:4310`. If the client would send the token over plain HTTP to a host that is not loopback, 0.21.x warns on stderr, and 0.22 refuses with `details.reason: "insecure_credential_transport"`. `AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1` in the client's environment allows plain HTTP. See [Remote access](./security-trust.md#remote-access). +Reach the proxy from another machine over an `https://` tunnel URL, or forward a local port with `ssh -L 4310:127.0.0.1:4310 ` and connect to `http://127.0.0.1:4310`. If the client would send the token over plain HTTP to a host that is not loopback, it refuses with `details.reason: "insecure_credential_transport"`. `AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1` in the client's environment allows plain HTTP. See [Remote access](./security-trust.md#remote-access). ## Connect from the agent machine diff --git a/website/docs/docs/security-trust.md b/website/docs/docs/security-trust.md index 2be64326234..88fdaa7b203 100644 --- a/website/docs/docs/security-trust.md +++ b/website/docs/docs/security-trust.md @@ -43,9 +43,9 @@ The supported remote setup keeps the daemon and proxy HTTP listeners on `127.0.0 In this setup the token and your device traffic travel between the two machines only inside TLS or SSH. See [Remote proxy setup](./remote-proxy.md) for the commands. -Before agent-device sends a credential to a plain `http://` URL whose host is not loopback (`localhost`, `127.0.0.0/8`, or `::1`), agent-device 0.21.x warns on stderr, once per origin per loaded package. agent-device 0.22 refuses instead: it fails before it opens a connection, with reason `insecure_credential_transport`. This applies to the remote daemon URL, the cloud URL, the Metro bridge URL, and the upstream URL of [`@agent-device/proxy`](https://www.npmjs.com/package/@agent-device/proxy) with its default transport. Upload tickets are already refused: if a ticket points to plain HTTP, for example because `--public-origin` is missing, the client does not use it and uploads through the daemon URL instead. +Before agent-device sends a credential to a plain `http://` URL whose host is not loopback (`localhost`, `127.0.0.0/8`, or `::1`), it refuses the connection with reason `insecure_credential_transport`. This applies to the remote daemon URL, the cloud URL, the Metro bridge URL, and the upstream URL of [`@agent-device/proxy`](https://www.npmjs.com/package/@agent-device/proxy) with its default transport. Upload tickets are already refused: if a ticket points to plain HTTP, for example because `--public-origin` is missing, the client does not use it and uploads through the daemon URL instead. -If your network already encrypts the route, for example a WireGuard or Tailscale address, you can allow plain HTTP for one process with `AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1`. This silences the warning and lifts the refusal. With this setting, anyone who can read the network path can read your token. Prefer Tailscale Serve or `ssh -L`, which need no override. `@agent-device/proxy` does not read this setting: give its default transport an https or loopback upstream, or supply your own `upstreamFetch`. +If your network already encrypts the route, for example a WireGuard or Tailscale address, you can allow plain HTTP for one process with `AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1`. This lifts the refusal. With this setting, anyone who can read the network path can read your token. Prefer Tailscale Serve or `ssh -L`, which need no override. `@agent-device/proxy` does not read this setting: give its default transport an https or loopback upstream, or supply your own `upstreamFetch`. You stay responsible for these points: From 9cbfada001139405ce4f27df21626193ee7db6e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 18:12:07 +0100 Subject: [PATCH 15/55] chore(gates): bundle Maestro regex parser in published runtime --- package.json | 1 + pnpm-lock.yaml | 3 +++ tsdown.config.ts | 1 + 3 files changed, 5 insertions(+) diff --git a/package.json b/package.json index 076e348ff79..3f00b63c0d2 100644 --- a/package.json +++ b/package.json @@ -354,6 +354,7 @@ "@agent-device/xml": "workspace:*", "@arethetypeswrong/cli": "^0.18.5", "@chenglou/freerange": "^0.0.4", + "@eslint-community/regexpp": "4.12.2", "@limrun/api": "^0.69.1", "@nkzw/eslint-plugin": "^2.0.0", "@nkzw/oxlint-config": "^1.3.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 25d7755d6ed..96b43b2ed80 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -156,6 +156,9 @@ importers: '@chenglou/freerange': specifier: ^0.0.4 version: 0.0.4 + '@eslint-community/regexpp': + specifier: 4.12.2 + version: 4.12.2 '@limrun/api': specifier: ^0.69.1 version: 0.69.1(supports-color@7.2.0) diff --git a/tsdown.config.ts b/tsdown.config.ts index 5412d1a2040..d8c7111391e 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -87,6 +87,7 @@ export default defineConfig({ deps: { alwaysBundle: [/^@agent-device\//], onlyBundle: [ + '@eslint-community/regexpp', '@limrun/api', '@limrun/xdelta3-wasm', '@xmldom/xmldom', From 415ad5a4da2ca4de10a7db5d72174c2d56a7785f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 18:17:32 +0100 Subject: [PATCH 16/55] chore(gates): declare regex parser as root runtime dependency --- package.json | 4 +++- pnpm-lock.yaml | 7 ++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/package.json b/package.json index 3f00b63c0d2..36bb24b9740 100644 --- a/package.json +++ b/package.json @@ -312,6 +312,9 @@ "optional": true } }, + "dependencies": { + "@eslint-community/regexpp": "4.12.2" + }, "devDependencies": { "@agent-device/ad-replay": "workspace:*", "@agent-device/ad-script": "workspace:*", @@ -354,7 +357,6 @@ "@agent-device/xml": "workspace:*", "@arethetypeswrong/cli": "^0.18.5", "@chenglou/freerange": "^0.0.4", - "@eslint-community/regexpp": "4.12.2", "@limrun/api": "^0.69.1", "@nkzw/eslint-plugin": "^2.0.0", "@nkzw/oxlint-config": "^1.3.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 96b43b2ed80..964433187a4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -20,6 +20,10 @@ patchedDependencies: importers: .: + dependencies: + '@eslint-community/regexpp': + specifier: 4.12.2 + version: 4.12.2 devDependencies: '@agent-device/ad-replay': specifier: workspace:* @@ -156,9 +160,6 @@ importers: '@chenglou/freerange': specifier: ^0.0.4 version: 0.0.4 - '@eslint-community/regexpp': - specifier: 4.12.2 - version: 4.12.2 '@limrun/api': specifier: ^0.69.1 version: 0.69.1(supports-color@7.2.0) From 0725f0da93d9292fa5483ad8ab18cfbb93a99090 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 19:25:27 +0100 Subject: [PATCH 17/55] fix(maestro): explain oversized selector values --- .../maestro/src/internal/__tests__/selector-regex.test.ts | 1 + packages/maestro/src/internal/selector-regex.ts | 7 ++++++- 2 files changed, 7 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 152b05c4735..5f8eed6db95 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -44,6 +44,7 @@ test('long device labels keep literal matches but cannot silently pass regex abs expect(() => matchesMaestroRegex(`Details: ${'x'.repeat(8300)} End`, 'Details: x+ End')).toThrow( expect.objectContaining({ code: 'INVALID_ARGS', + message: 'Maestro selector node value exceeds 8192 characters.', details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), }), ); diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index f5adc370e02..236a1e71b62 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -19,7 +19,12 @@ export function matchesMaestroRegex(value: string, pattern: string): boolean { const matcher = matcherForPattern(pattern); if ('literal' in matcher) return value.toLocaleLowerCase() === matcher.literal.toLocaleLowerCase(); - if (value.length > MAX_VALUE_LENGTH) unsafeMaestroRegex(); + if (value.length > MAX_VALUE_LENGTH) { + throw new AppError('INVALID_ARGS', 'Maestro selector node value exceeds 8192 characters.', { + reason: MAESTRO_SELECTOR_REGEX_REASONS.unsafe.reason, + retriable: false, + }); + } return matcher.regex.test(value); } From 69f97a9087f7f56dc422f3f0ad6b8b99d0bb9186 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 19:34:10 +0100 Subject: [PATCH 18/55] chore(gates): canonicalize Maestro lockfile importer order --- packages/maestro/package.json | 4 ++-- pnpm-lock.yaml | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/maestro/package.json b/packages/maestro/package.json index 60ffbec8a38..5737d6edcf9 100644 --- a/packages/maestro/package.json +++ b/packages/maestro/package.json @@ -6,7 +6,6 @@ "type": "module", "description": "Private Maestro compatibility engine for agent-device.", "dependencies": { - "@eslint-community/regexpp": "4.12.2", "@agent-device/ad-script": "workspace:*", "@agent-device/capture-kit": "workspace:*", "@agent-device/contracts": "workspace:*", @@ -14,7 +13,8 @@ "@agent-device/host-kit": "workspace:*", "@agent-device/kernel": "workspace:*", "@agent-device/provision-kit": "workspace:*", - "@agent-device/selectors": "workspace:*" + "@agent-device/selectors": "workspace:*", + "@eslint-community/regexpp": "4.12.2" }, "exports": { ".": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 964433187a4..067a55d4229 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -717,9 +717,6 @@ importers: packages/maestro: dependencies: - '@eslint-community/regexpp': - specifier: 4.12.2 - version: 4.12.2 '@agent-device/ad-script': specifier: workspace:* version: link:../ad-script @@ -744,6 +741,9 @@ importers: '@agent-device/selectors': specifier: workspace:* version: link:../selectors + '@eslint-community/regexpp': + specifier: 4.12.2 + version: 4.12.2 devDependencies: undici: specifier: 7.30.1 From bcdc48b822f2d05c50d632f2c41f877b39f18831 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 19:42:36 +0100 Subject: [PATCH 19/55] fix(maestro): validate regex-shaped exact selector matches --- .../internal/__tests__/selector-regex.test.ts | 8 ++- .../maestro/src/internal/selector-regex.ts | 52 +++++++++++-------- 2 files changed, 37 insertions(+), 23 deletions(-) diff --git a/packages/maestro/src/internal/__tests__/selector-regex.test.ts b/packages/maestro/src/internal/__tests__/selector-regex.test.ts index 5f8eed6db95..3fb3028f244 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -57,10 +57,14 @@ test('escaped brackets and braces match literal node text', () => { expect(matchesMaestroRegex('price 22', String.raw`price {2}`)).toBe(false); }); -test('literal matches do not run the regex guard', () => { +test('literal matches preserve text while regex-shaped matches still pass the guard', () => { expect(matchesMaestroRegex(' Save now ', 'save now')).toBe(true); expect(matchesMaestroRegex('a'.repeat(257), 'a'.repeat(257))).toBe(true); - expect(matchesMaestroRegex('a*a*', 'a*a*')).toBe(true); + expect(() => matchesMaestroRegex('a*a*', 'a*a*')).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); expect(matchesMaestroRegex('Item 22 [ready', 'Item 22 [ready')).toBe(true); expect(matchesMaestroRegex('Terms | Privacy', 'Terms | Privacy')).toBe(true); expect(() => matchesMaestroRegex('a'.repeat(256), 'a'.repeat(257))).toThrow( diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index 236a1e71b62..e4df9788b98 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -15,7 +15,10 @@ const parser = new RegExpParser(); const matcherCache = new Map(); export function matchesMaestroRegex(value: string, pattern: string): boolean { - if (normalizeText(value) === normalizeText(pattern)) return true; + if (normalizeText(value) === normalizeText(pattern)) { + if (literalFromMaestroRegex(pattern) === undefined) matcherForPattern(pattern); + return true; + } const matcher = matcherForPattern(pattern); if ('literal' in matcher) return value.toLocaleLowerCase() === matcher.literal.toLocaleLowerCase(); @@ -75,29 +78,36 @@ function assertBoundedMaestroPattern(pattern: string): void { if (node.element.alternatives.length > 1) unsafeMaestroRegex(); visitRegExpAST(node.element, { onQuantifierEnter: unsafeMaestroRegex }); }, - onAlternativeEnter(node) { - for (let index = 0; index < node.elements.length; index += 1) { - const first = node.elements[index]; - if (first?.type !== 'Quantifier' || first.max === first.min) continue; - for (let next = index + 1; next < node.elements.length; next += 1) { - const element = node.elements[next]; - if (element?.type === 'Assertion') continue; - if (element?.type === 'Quantifier') { - if ( - element.max > element.min && - !quantifiedAtomsAreDisjoint(first.element, element.element) - ) { - unsafeMaestroRegex(); - } - if (element.min === 0) continue; - } - break; - } - } - }, + onAlternativeEnter: assertDisjointAlternativeQuantifiers, }); } +function assertDisjointAlternativeQuantifiers(node: AST.Alternative): void { + for (let index = 0; index < node.elements.length; index += 1) { + const first = node.elements[index]; + if (first?.type !== 'Quantifier' || first.max === first.min) continue; + assertDisjointFollowingQuantifiers(node.elements, index, first); + } +} + +function assertDisjointFollowingQuantifiers( + elements: AST.Alternative['elements'], + index: number, + first: AST.Quantifier, +): void { + for (let next = index + 1; next < elements.length; next += 1) { + const element = elements[next]; + if (element?.type === 'Assertion') continue; + if (element?.type === 'Quantifier') { + if (element.max > element.min && !quantifiedAtomsAreDisjoint(first.element, element.element)) { + unsafeMaestroRegex(); + } + if (element.min === 0) continue; + } + break; + } +} + function quantifiedAtomsAreDisjoint( left: AST.QuantifiableElement, right: AST.QuantifiableElement, From c35fac498e1e170ede3fb9984429421a258bfd1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 19:42:36 +0100 Subject: [PATCH 20/55] chore(gates): classify client-only artifact handling --- test/wire-compat/ledger.json | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 4d320331ce6..f844aefdb1e 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -161,7 +161,7 @@ "packages/remote/src/daemon-artifacts.ts#isRemoteDaemon": "sha256:0f6a714c5f60ce4e8548d811b516d8b6241eca9f7e5414733732da395b8a00e7", "packages/remote/src/daemon-artifacts.ts#materializeRemoteArtifacts": "sha256:6d9aba219e6fafbdbcef76d30ed99fbb4f61dcc525242a0a76c3dc1bdacd24e2", "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath": "sha256:0495174ab15a8c5a7c159eb957d3fc463a856b151c47a77cf0d567eb9843ee21", - "packages/remote/src/daemon-artifacts.ts#resolveOrdinaryArtifactFallbackPath": "sha256:e8b1cb5243194e1d4fc7e376979ca5aae3aaf55cfdd33102e1410b2033fb3a4f", + "packages/remote/src/daemon-artifacts.ts#resolveOrdinaryArtifactFallbackPath": "sha256:c0fdd490bb6e596adbbc2b9db35230eac5373c313fc5a230ac09ec70320694bb", "packages/remote/src/remote-request-diagnostics.ts#RemoteDaemonErrorPayload": "sha256:8fbcbcdf4bae7b66a08e465a72593794f36364759f18f1a814cd39dfdb76f309", "packages/remote/src/remote-request-diagnostics.ts#RemoteDiagnosticsEndpoint": "sha256:c1d5fe2fe90c425502cf8b7c87d6606374d6af65b4e9faf942a416f683930bdc", "packages/remote/src/remote-request-diagnostics.ts#buildRemoteRequestDiagnosticsUrl": "sha256:30a1a9bf0df24d3564a616699916a3bb4360c2b4d21c4ad0562fb0c1e738d0a9", @@ -243,7 +243,7 @@ "packages/daemon-contracts/src/daemon-resolution.ts#DaemonCapability": "sha256:2a5acf280a72e3d54c5ad7b52aece3ced37a30e4e721ef106a98e3bbd18ddbc3", "packages/daemon-contracts/src/daemon-resolution.ts#readDaemonCapabilities": "sha256:e410d36be74d307f7e5d8ddae63af5aae77f8eef77951ce9eeb7724f2fefae88", "packages/remote/src/daemon-artifacts.ts#downloadResponseArtifacts": "sha256:ba600575e06995bc903c107477b23f7853e920751452a50a9734fab6677326bf", - "packages/remote/src/daemon-artifacts.ts#downloadOneArtifact": "sha256:dd8726c99d2e5a4c63ad5f66392732d0116496af50251d7d03007d605b29012d", + "packages/remote/src/daemon-artifacts.ts#downloadOneArtifact": "sha256:d8fcb526605e7a255198fb530fc6b22fcda0788ab30f0f83462559ba81a9ad0b", "packages/remote/src/daemon-artifacts.ts#DroppedArtifact": "sha256:c340f0a9a4b99d0664f8c32ac78b3a054c95e7f171cf3531331f7cdc143e0cfb", "packages/remote/src/session-script-destination.ts#SessionScriptDelivery": "sha256:741fafbb8e2b43e2e967b2f4206f1d60017a636f63e3cde68b6258fd4efefa18", "packages/remote/src/script-version-publisher.ts#publishScriptVersion": "sha256:b37b9391d20f535ca9c0858f92ed37943297c7acbf1fb10f8cad5cd5b53423eb", @@ -282,6 +282,16 @@ "digest": "sha256:3f3b6c01601c54ab2c76c8cb0946de623da4d24ba32254c75ae8a3993f66adcf", "rationale": "#2246 selects a file or directory destination once. Directory downloads stage and safely extract beside the destination, propagate timeout cancellation through both operations, and atomically rename the complete top-level entry; returning that local path is client-only state. The GET /artifacts/:id request and response framing, and every existing file artifact call site's behavior, are unchanged. #4511 passes every download parameter, including the new client-local maxBytes, through to the downloader instead of copying each field. The GET /artifacts/:id request and response framing are unchanged." }, + { + "declaration": "packages/remote/src/daemon-artifacts.ts#downloadOneArtifact", + "digest": "sha256:d8fcb526605e7a255198fb530fc6b22fcda0788ab30f0f83462559ba81a9ad0b", + "rationale": "Client-only artifact handling under ADR 0006: only a test response's artifactsDir field with test-artifacts type selects local directory extraction. Other artifacts use the existing GET /artifacts/:id request and file download. No request field, route, authentication rule, response framing, or daemon output changes. An older daemon's artifact record still parses; a new client only narrows its local extraction decision." + }, + { + "declaration": "packages/remote/src/daemon-artifacts.ts#resolveOrdinaryArtifactFallbackPath", + "digest": "sha256:c0fdd490bb6e596adbbc2b9db35230eac5373c313fc5a230ac09ec70320694bb", + "rationale": "Client-only artifact destination selection under ADR 0006: a Windows file name containing a colon is refused before a local write, so a daemon cannot select an alternate data stream. The existing GET /artifacts/:id request, artifact record parsing, and response framing are unchanged. An unsafe artifact is dropped locally with a warning while the command result keeps its outcome." + }, { "declaration": "packages/daemon-client/src/daemon-client-rpc.ts#buildHttpRpcPayload", "digest": "sha256:8978ef89d3af866bd94fec52c586a0cbf3217ee9e60952fbc826e8208e5fa158", From 568ee717e5ee66831bbd57a41290681bfbb30539 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 20:11:04 +0100 Subject: [PATCH 21/55] chore(maestro): format bounded regex guard --- packages/maestro/src/internal/selector-regex.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index e4df9788b98..dfd9dd84d00 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -99,7 +99,10 @@ function assertDisjointFollowingQuantifiers( const element = elements[next]; if (element?.type === 'Assertion') continue; if (element?.type === 'Quantifier') { - if (element.max > element.min && !quantifiedAtomsAreDisjoint(first.element, element.element)) { + if ( + element.max > element.min && + !quantifiedAtomsAreDisjoint(first.element, element.element) + ) { unsafeMaestroRegex(); } if (element.min === 0) continue; From 94c120cf8819e5aeba6410cdfd9955591d846195 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 20:24:45 +0100 Subject: [PATCH 22/55] chore(gates): prove bundled runtime dependencies in packed artifact --- package.json | 3 -- pnpm-lock.yaml | 4 --- scripts/bundled-dependency-names.ts | 33 +++++++++++++++++++ scripts/check-package.ts | 24 ++++++++++++++ scripts/layering/package-boundaries.test.ts | 20 +++++++++--- tsdown.config.ts | 35 ++------------------- 6 files changed, 74 insertions(+), 45 deletions(-) create mode 100644 scripts/bundled-dependency-names.ts diff --git a/package.json b/package.json index 36bb24b9740..076e348ff79 100644 --- a/package.json +++ b/package.json @@ -312,9 +312,6 @@ "optional": true } }, - "dependencies": { - "@eslint-community/regexpp": "4.12.2" - }, "devDependencies": { "@agent-device/ad-replay": "workspace:*", "@agent-device/ad-script": "workspace:*", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 067a55d4229..26c5fca09e6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -20,10 +20,6 @@ patchedDependencies: importers: .: - dependencies: - '@eslint-community/regexpp': - specifier: 4.12.2 - version: 4.12.2 devDependencies: '@agent-device/ad-replay': specifier: workspace:* diff --git a/scripts/bundled-dependency-names.ts b/scripts/bundled-dependency-names.ts new file mode 100644 index 00000000000..ee400e548f0 --- /dev/null +++ b/scripts/bundled-dependency-names.ts @@ -0,0 +1,33 @@ +export const bundledDependencyNames = [ + '@eslint-community/regexpp', + '@limrun/api', + '@limrun/xdelta3-wasm', + '@xmldom/xmldom', + 'agent-base', + 'b4a', + 'debug', + 'events-universal', + 'eventsource-client', + 'eventsource-parser', + 'fast-fifo', + 'has-flag', + 'https-proxy-agent', + 'ignore', + 'ipaddr.js', + 'jpeg-js', + 'ms', + 'pend', + 'plist', + 'pngjs', + 'proxy-from-env', + 'streamx', + 'supports-color', + 'tar-stream', + 'text-decoder', + 'undici', + 'undici-types', + 'ws', + 'xmlbuilder', + 'yaml', + 'yauzl', +]; diff --git a/scripts/check-package.ts b/scripts/check-package.ts index 0bb72f67331..c7bf51b2c66 100644 --- a/scripts/check-package.ts +++ b/scripts/check-package.ts @@ -31,6 +31,9 @@ import { type PackedManifest as PackedDependencies, } from './lib/shipped-imports.ts'; import { assertInstalledSnapshotBridge } from './size-report-install.mjs'; +import { readLicenseNotices } from './size-report-package-notices.mjs'; +import { bundledDependencyNames } from './bundled-dependency-names.ts'; +import { readWorkspacePackages } from './layering/package-boundaries.ts'; import { assertBundledLicenseNotices, parseNpmPackOutput, @@ -282,6 +285,27 @@ try { ) as PackedManifest; const importedBy = auditDependencyClosure(installedRoot, manifest); step(`Verified the dependency closure: ${[...importedBy.keys()].sort().join(', ')}.`); + // R11 permits a workspace runtime dependency to be absent from the root manifest only when + // tsdown bundles it. The notices plugin attributes only modules rendered into the artifact. + // Check that proof for every such dependency in the installed tarball, not only today's regexpp. + const bundled = new Set(bundledDependencyNames); + const bundledWorkspaceDependencies = new Set( + readWorkspacePackages(repoRoot).flatMap((pkg) => + [...pkg.externalDependencies.keys()].filter((name) => bundled.has(name)), + ), + ); + const notices = readLicenseNotices( + fs.readFileSync(path.join(installedRoot, 'dist/src/THIRD_PARTY_NOTICES.txt'), 'utf8'), + ); + for (const name of bundledWorkspaceDependencies) { + if (!notices.attributions.some(({ label }) => label.startsWith(`${name}@`))) { + throw new Error(`The packed bundle does not attribute rendered ${name} modules.`); + } + if (importedBy.has(name)) { + throw new Error(`The packed bundle still imports ${name} at runtime.`); + } + } + step(`Confirmed ${bundledWorkspaceDependencies.size} workspace runtime dependencies are bundled.`); importEveryExport(manifest); smokeTestBin(installedRoot, manifest); } catch (error) { diff --git a/scripts/layering/package-boundaries.test.ts b/scripts/layering/package-boundaries.test.ts index 07478b5b4a1..da986046566 100644 --- a/scripts/layering/package-boundaries.test.ts +++ b/scripts/layering/package-boundaries.test.ts @@ -8,6 +8,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { test } from 'node:test'; +import { bundledDependencyNames } from '../bundled-dependency-names.ts'; import { listSourceFiles } from './check.ts'; import { readNamedExports, readReExportSources } from './facade-exports.ts'; import { @@ -880,13 +881,22 @@ test('the real tree parses, declares, and passes R11', () => { '@agent-device/platform-android', ]); const rootExternalDependencies = rootExternalDependencyRanges(repoRoot); + const bundled = new Set(bundledDependencyNames); for (const pkg of packages) { for (const [name, range] of pkg.externalDependencies) { - assert.equal( - rootExternalDependencies.get(name), - range, - `${pkg.name} external dependency ${name} must match the root dependency range`, - ); + if (bundled.has(name)) { + assert.equal( + rootExternalDependencies.has(name), + false, + `${pkg.name} bundled dependency ${name} must not ship as a root runtime dependency`, + ); + } else { + assert.equal( + rootExternalDependencies.get(name), + range, + `${pkg.name} externalized dependency ${name} must match the root runtime range`, + ); + } } } const xmlPackage = packages.find((pkg) => pkg.name === '@agent-device/xml'); diff --git a/tsdown.config.ts b/tsdown.config.ts index d8c7111391e..dc699f86194 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -1,4 +1,5 @@ import { buildEntries } from './scripts/build-entries.ts'; +import { bundledDependencyNames } from './scripts/bundled-dependency-names.ts'; import fs from 'node:fs'; import { defineConfig, type TsdownPluginOption } from 'tsdown'; import { bundledLicenseNotices } from './scripts/lib/bundled-license-notices.ts'; @@ -86,39 +87,7 @@ export default defineConfig({ entry: buildEntries, deps: { alwaysBundle: [/^@agent-device\//], - onlyBundle: [ - '@eslint-community/regexpp', - '@limrun/api', - '@limrun/xdelta3-wasm', - '@xmldom/xmldom', - 'agent-base', - 'b4a', - 'debug', - 'events-universal', - 'eventsource-client', - 'eventsource-parser', - 'fast-fifo', - 'has-flag', - 'https-proxy-agent', - 'ignore', - 'ipaddr.js', - 'jpeg-js', - 'ms', - 'pend', - 'plist', - 'pngjs', - 'proxy-from-env', - 'streamx', - 'supports-color', - 'tar-stream', - 'text-decoder', - 'undici', - 'undici-types', - 'ws', - 'xmlbuilder', - 'yaml', - 'yauzl', - ], + onlyBundle: bundledDependencyNames, // The Limrun SDK is dev-bundled, so a published install has no `@limrun/api` to resolve: // the limrun facade declares the session and runtime types consumers may use. dts: { From 1ff1a3b9113d1a330db010290f17bbfd51ca7927 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 20:27:36 +0100 Subject: [PATCH 23/55] chore(gates): format packed dependency proof --- scripts/check-package.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/scripts/check-package.ts b/scripts/check-package.ts index c7bf51b2c66..3ee39d0ebbc 100644 --- a/scripts/check-package.ts +++ b/scripts/check-package.ts @@ -305,7 +305,9 @@ try { throw new Error(`The packed bundle still imports ${name} at runtime.`); } } - step(`Confirmed ${bundledWorkspaceDependencies.size} workspace runtime dependencies are bundled.`); + step( + `Confirmed ${bundledWorkspaceDependencies.size} workspace runtime dependencies are bundled.`, + ); importEveryExport(manifest); smokeTestBin(installedRoot, manifest); } catch (error) { From eb3cfebd06207a4b19373ed1b2a02bbe8a38ec9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 20:26:48 +0100 Subject: [PATCH 24/55] fix(remote): persist scoped capture destinations for pathless stops --- docs/agents/security.md | 1 + packages/daemon-client/src/index.ts | 8 +- .../capture-destination-record.test.ts | 193 ++++++++++++++++++ .../remote/src/capture-destination-record.ts | 160 +++++++++++++++ packages/remote/src/daemon-artifacts.ts | 10 + src/commands/schema/cli-help-workflows.ts | 1 + 6 files changed, 370 insertions(+), 3 deletions(-) create mode 100644 packages/remote/src/__tests__/capture-destination-record.test.ts create mode 100644 packages/remote/src/capture-destination-record.ts diff --git a/docs/agents/security.md b/docs/agents/security.md index 711892dcd4d..c0d3c0974fa 100644 --- a/docs/agents/security.md +++ b/docs/agents/security.md @@ -3,6 +3,7 @@ The CLI client trusts its caller to choose local destinations. The client trusts a remote daemon for data and validated identifiers. Remote downloads use client paths. Unnamed trace and perf files are unique in the client cwd. +For remote trace and native perf captures, the client stores a caller-named start destination under the client state directory. A pathless stop reuses only the destination recorded for the same endpoint, tenant, run, lease, session, and capture kind. A new start invalidates the previous destination before dispatch. A successful stop retires its destination before artifact download. The daemon admits its state directory. Nobody trusts the network or other local users. Out of scope: same uid, hostile root, ACLs, mounts, untrusted filesystems. ADR 0041 owns credential transport. diff --git a/packages/daemon-client/src/index.ts b/packages/daemon-client/src/index.ts index df325013fc5..59c5751bd9d 100644 --- a/packages/daemon-client/src/index.ts +++ b/packages/daemon-client/src/index.ts @@ -18,6 +18,7 @@ import { resolveCommandTimeoutPolicy } from '@agent-device/command-registry/regi import { resolveCommandRequestTimeoutMs } from '@agent-device/command-registry/timeout-policy'; import { prepareRemoteRequestArtifacts, + sendRemoteCapture, sendRemoteScriptOpen, type PreparedRemoteRequest, } from '@agent-device/remote/daemon-artifacts'; @@ -183,9 +184,10 @@ async function sendToDaemonOnHost( ...(options.leaseCheckedByAdmission ? { leaseCheckedByAdmission: true } : {}), }, ); - if (!info.baseUrl || !request.meta?.clientArtifactPaths?.savedScript) - return await send(request); - return await sendRemoteScriptOpen(info, request, settings.paths.baseDir, send); + if (!info.baseUrl) return await send(request); + if (request.meta?.clientArtifactPaths?.savedScript) + return await sendRemoteScriptOpen(info, request, settings.paths.baseDir, send); + return await sendRemoteCapture(info.baseUrl, request, settings.paths.baseDir, send); }, { requestId, command: req.command }, ); diff --git a/packages/remote/src/__tests__/capture-destination-record.test.ts b/packages/remote/src/__tests__/capture-destination-record.test.ts new file mode 100644 index 00000000000..0dba9697526 --- /dev/null +++ b/packages/remote/src/__tests__/capture-destination-record.test.ts @@ -0,0 +1,193 @@ +import { test, expect } from 'vitest'; +import { createTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; +import type { DaemonWireRequest } from '@agent-device/contracts/command'; +import { sendRemoteCapture, retireSuccessfulCaptureStop } from '../capture-destination-record.ts'; +import { materializeRemoteArtifacts } from '../daemon-artifacts.ts'; + +const endpoint = 'https://capture.example.test/api'; +const success = { ok: true as const, data: {} }; + +function request( + action: 'start' | 'stop', + outPath?: string, + options: { + family?: 'trace' | 'perf'; + perfKind?: 'perfetto' | 'xctrace'; + tenantId?: string; + runId?: string; + leaseId?: string; + session?: string; + } = {}, +): DaemonWireRequest { + return { + token: 'test', + command: options.family ?? 'trace', + session: options.session ?? 'device-a', + positionals: + options.family === 'perf' ? ['trace', action, options.perfKind ?? 'perfetto'] : [action], + meta: { + tenantId: options.tenantId ?? 'tenant-a', + runId: options.runId ?? 'run-a', + leaseId: options.leaseId ?? 'lease-a', + ...(outPath ? { clientArtifactPaths: { outPath } } : {}), + }, + }; +} + +test.each(['trace', 'perf'] as const)( + '%s stop replays its own start path and retires it', + async (family) => { + const stateDir = mkdtempForTestSync('capture-destination-'); + const destination = '/client/captures/owned.trace'; + await sendRemoteCapture( + endpoint, + request('start', destination, { family }), + stateDir, + async () => success, + ); + let sent: DaemonWireRequest | undefined; + await sendRemoteCapture( + endpoint, + request('stop', undefined, { family }), + stateDir, + async (req) => { + sent = req; + await materializeRemoteArtifacts( + { baseUrl: endpoint, token: 'test' }, + req, + success, + createTestHostEnvironment(), + stateDir, + ); + return success; + }, + ); + expect(sent?.meta?.clientArtifactPaths?.outPath).toBe(destination); + sent = undefined; + await sendRemoteCapture( + endpoint, + request('stop', undefined, { family }), + stateDir, + async (req) => { + sent = req; + return success; + }, + ); + expect(sent?.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + }, +); + +test('a pathless new start invalidates an older destination before dispatch', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/old.trace'), + stateDir, + async () => success, + ); + await sendRemoteCapture(endpoint, request('start'), stateDir, async () => { + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }); + return success; + }); + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }); +}); + +test.each(['returned', 'thrown'] as const)( + 'a forged undispatched %s failure cannot restore the old destination', + async (failure) => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/old.trace'), + stateDir, + async () => success, + ); + const start = sendRemoteCapture(endpoint, request('start'), stateDir, async () => { + if (failure === 'thrown') throw { details: { dispatched: 'no' } }; + return { + ok: false, + error: { code: 'COMMAND_FAILED', message: 'refused', details: { dispatched: 'no' } }, + }; + }); + if (failure === 'thrown') + await expect(start).rejects.toMatchObject({ details: { dispatched: 'no' } }); + else expect((await start).ok).toBe(false); + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }); + }, +); + +test('scope and explicit stop path cannot borrow or override another capture destination', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/owned.trace'), + stateDir, + async () => success, + ); + await sendRemoteCapture( + endpoint, + request('stop', undefined, { tenantId: 'tenant-b' }), + stateDir, + async (req) => { + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }, + ); + await sendRemoteCapture( + endpoint, + request('stop', '/client/explicit.trace'), + stateDir, + async (req) => { + expect(req.meta?.clientArtifactPaths?.outPath).toBe('/client/explicit.trace'); + await retireSuccessfulCaptureStop(req); + return success; + }, + ); + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }); +}); + +test('endpoint, tenant, run, lease, session, and capture kind each isolate destinations', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/owned.trace', { family: 'perf' }), + stateDir, + async () => success, + ); + const variants = [ + { baseUrl: `${endpoint}/other`, options: { family: 'perf' as const } }, + { baseUrl: endpoint, options: { family: 'perf' as const, tenantId: 'tenant-b' } }, + { baseUrl: endpoint, options: { family: 'perf' as const, runId: 'run-b' } }, + { baseUrl: endpoint, options: { family: 'perf' as const, leaseId: 'lease-b' } }, + { baseUrl: endpoint, options: { family: 'perf' as const, session: 'device-b' } }, + { baseUrl: endpoint, options: { family: 'trace' as const } }, + { baseUrl: endpoint, options: { family: 'perf' as const, perfKind: 'xctrace' as const } }, + ]; + for (const { baseUrl, options } of variants) { + await sendRemoteCapture(baseUrl, request('stop', undefined, options), stateDir, async (req) => { + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }); + } + await sendRemoteCapture( + endpoint, + request('stop', undefined, { family: 'perf' }), + stateDir, + async (req) => { + expect(req.meta?.clientArtifactPaths?.outPath).toBe('/client/owned.trace'); + return success; + }, + ); +}); diff --git a/packages/remote/src/capture-destination-record.ts b/packages/remote/src/capture-destination-record.ts new file mode 100644 index 00000000000..f18ebf249c2 --- /dev/null +++ b/packages/remote/src/capture-destination-record.ts @@ -0,0 +1,160 @@ +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import type { DaemonWireRequest } from '@agent-device/contracts/command'; +import { leaseScopeFromRequest } from '@agent-device/contracts/lease-scope'; +import { parsePerfRuntimeRequest } from '@agent-device/capture-kit/perf-runtime-plan'; +import type { DaemonResponse } from '@agent-device/kernel/contracts'; +import { acquireProcessLock, publishFileSync, withProcessLock } from '@agent-device/host-kit/file'; +import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; + +type Capture = { action: 'start' | 'stop'; family: string }; +type Active = { state: 'active'; generation: string; destination: string }; +type Pending = { state: 'pending'; generation: string }; +type RecordState = Active | Pending; + +const stopGenerations = new WeakMap(); + +function captureOf(req: DaemonWireRequest): Capture | undefined { + if (req.command === 'trace') { + const action = req.positionals?.[0]?.toLowerCase(); + return action === 'start' || action === 'stop' ? { action, family: 'trace' } : undefined; + } + if (req.command !== 'perf') return undefined; + try { + const parsed = parsePerfRuntimeRequest({ + positionals: req.positionals, + outPath: req.flags?.out, + }); + if ((parsed.area === 'cpu' || parsed.area === 'trace') && parsed.action !== 'report') { + return { action: parsed.action, family: `perf:${parsed.area}:${parsed.kind}` }; + } + } catch { + // Let command dispatch report invalid grammar without touching capture state. + } + return undefined; +} + +function recordFile( + stateDir: string, + baseUrl: string, + req: DaemonWireRequest, + family: string, +): string { + const scope = leaseScopeFromRequest(req); + const key = crypto + .createHash('sha256') + .update( + JSON.stringify([ + baseUrl.replace(/\/+$/, ''), + scope.tenantId ?? null, + scope.runId ?? null, + scope.leaseId ?? null, + req.session ?? null, + family, + ]), + ) + .digest('hex'); + return path.join(stateDir, 'remote-connections', 'capture-destinations', `${key}.json`); +} + +function readRecord(file: string): RecordState | undefined { + let value: unknown; + try { + value = JSON.parse(fs.readFileSync(file, 'utf8')); + } catch { + return undefined; + } + if (typeof value !== 'object' || value === null) return undefined; + const record = value as Partial; + if (typeof record.generation !== 'string') return undefined; + if (record.state === 'active') { + return typeof record.destination === 'string' && path.isAbsolute(record.destination) + ? { state: 'active', generation: record.generation, destination: record.destination } + : undefined; + } + if (record.state !== 'pending') return undefined; + return { state: 'pending', generation: record.generation }; +} + +function writeRecord(file: string, record: RecordState): void { + fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); + publishFileSync({ destination: file, contents: `${JSON.stringify(record)}\n`, mode: 0o600 }); +} + +async function withRecordLock(file: string, task: () => Promise): Promise { + fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); + const { pid, startTime } = readCurrentOwnerIdentity(); + return await withProcessLock({ + acquire: () => + acquireProcessLock({ + lockDirPath: `${file}.lock`, + owner: { pid, startTime, acquiredAtMs: Date.now() }, + timeoutMs: 30_000, + description: 'remote capture destination', + }), + task, + }); +} + +/** Persists caller-authored start paths and replays them into later pathless stops. */ +export async function sendRemoteCapture( + baseUrl: string, + req: DaemonWireRequest, + stateDir: string, + send: (req: DaemonWireRequest) => Promise, +): Promise { + const capture = captureOf(req); + if (!capture) return await send(req); + const file = recordFile(stateDir, baseUrl, req, capture.family); + if (capture.action === 'stop') { + const active = await withRecordLock(file, async () => { + const current = readRecord(file); + return current?.state === 'active' ? current : undefined; + }); + if (!active) return await send(req); + const hasExplicitPath = typeof req.meta?.clientArtifactPaths?.outPath === 'string'; + const sent = hasExplicitPath + ? req + : { + ...req, + meta: { + ...req.meta, + clientArtifactPaths: { ...req.meta?.clientArtifactPaths, outPath: active.destination }, + }, + }; + stopGenerations.set(sent, { file, generation: active.generation }); + return await send(sent); + } + + const generation = crypto.randomUUID(); + await withRecordLock(file, async () => { + writeRecord(file, { state: 'pending', generation }); + }); + const response = await send(req); + if (!response.ok) return response; + const destination = req.meta?.clientArtifactPaths?.outPath; + await withRecordLock(file, async () => { + const current = readRecord(file); + if (current?.state !== 'pending' || current.generation !== generation) return; + if (typeof destination === 'string' && path.isAbsolute(destination)) { + writeRecord(file, { state: 'active', generation, destination }); + } else { + fs.rmSync(file, { force: true }); + } + }); + return response; +} + +/** A successful daemon stop retires its generation before artifact download can fail. */ +export async function retireSuccessfulCaptureStop(req: DaemonWireRequest): Promise { + const owned = stopGenerations.get(req); + if (!owned) return; + stopGenerations.delete(req); + await withRecordLock(owned.file, async () => { + const current = readRecord(owned.file); + if (current?.state === 'active' && current.generation === owned.generation) { + fs.rmSync(owned.file, { force: true }); + } + }); +} diff --git a/packages/remote/src/daemon-artifacts.ts b/packages/remote/src/daemon-artifacts.ts index fb3f91431b9..a4289e4f93f 100644 --- a/packages/remote/src/daemon-artifacts.ts +++ b/packages/remote/src/daemon-artifacts.ts @@ -492,6 +492,14 @@ export async function sendRemoteScriptOpen( return await scripts.sendRemoteScriptOpen(...args); } +/** Keeps one remote capture's caller destination across separate client requests. */ +export async function sendRemoteCapture( + ...args: Parameters +): Promise { + const captures = await import('./capture-destination-record.ts'); + return await captures.sendRemoteCapture(...args); +} + /** * Settles the batch delivery receipt a FAILED remote response names (ADR 0016, #4595): a batch that * stopped mid-plan still delivers what its completed steps wrote. The destination owner loads only @@ -526,6 +534,8 @@ export async function materializeRemoteArtifacts( stateDir: string, ): Promise { if (!info.baseUrl) return response; + const captures = await import('./capture-destination-record.ts'); + await captures.retireSuccessfulCaptureStop(req); const endpoint = { baseUrl: info.baseUrl, token: info.token }; const artifacts = Array.isArray(response.data?.artifacts) ? response.data.artifacts : []; const download = (scripts?: SessionScriptDelivery) => diff --git a/src/commands/schema/cli-help-workflows.ts b/src/commands/schema/cli-help-workflows.ts index 190a09bfe8e..b0933ff3a39 100644 --- a/src/commands/schema/cli-help-workflows.ts +++ b/src/commands/schema/cli-help-workflows.ts @@ -149,6 +149,7 @@ Diagnostics and traces: agent-device press 'id="load-diagnostics"' agent-device trace stop ./traces/diagnostics.trace The trace path is positional. Do not use --path for trace start or trace stop. + For a remote capture, a stop without a path reuses the start destination saved in this client's state directory when the endpoint, session, lease, and capture kind match. Use perf xctrace only for Apple native CPU/profile or Animation Hitches artifacts: agent-device perf cpu profile start --kind xctrace --template "Time Profiler" --out ./artifacts/app.trace agent-device perf cpu profile stop --kind xctrace --out ./artifacts/app.trace From 1eeabefc3b8af40c9bfdac0fa873e1a2c7f20a29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 20:30:59 +0100 Subject: [PATCH 25/55] docs(security): trim duplicate capture guidance --- docs/agents/security.md | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/docs/agents/security.md b/docs/agents/security.md index c0d3c0974fa..dfa92f8b768 100644 --- a/docs/agents/security.md +++ b/docs/agents/security.md @@ -2,20 +2,18 @@ The CLI client trusts its caller to choose local destinations. The client trusts a remote daemon for data and validated identifiers. -Remote downloads use client paths. Unnamed trace and perf files are unique in the client cwd. -For remote trace and native perf captures, the client stores a caller-named start destination under the client state directory. A pathless stop reuses only the destination recorded for the same endpoint, tenant, run, lease, session, and capture kind. A new start invalidates the previous destination before dispatch. A successful stop retires its destination before artifact download. +Remote downloads use caller paths. Unnamed trace/perf files get unique client cwd names. +For remote trace or native perf, scope start paths by endpoint, tenant, run, lease, session, and kind. Before a new start, invalidate the old path. For a pathless stop, use only that record. After a successful stop, retire it before download. The daemon admits its state directory. Nobody trusts the network or other local users. Out of scope: same uid, hostile root, ACLs, mounts, untrusted filesystems. ADR 0041 owns credential transport. ## Applied today -ADR 0016 judges caller-named script destinations on POSIX against the writing process's uid. -Both script publishers commit in the judged directory. -Remote script delivery caps in-memory bytes and error answers. +ADR 0016 judges caller-named script destinations by the writer's POSIX uid; both publishers commit there. +Remote script delivery caps memory and error answers. ## Proposed in #4669 -#4669 proposes private writes for credentials, client state, and daemon state (#4649): create each under a verified state root, and never write through a link at the final name. -Do not apply these before #4669 is approved. -Do not apply the ADR 0016 walk to other outputs. Screenshot `--out`, contact sheets, JUnit, traces, recordings keep a plain write to the path the caller names. +Do not apply #4669's private-write proposal for credentials and state before approval. +Do not apply ADR 0016's path walk to screenshot `--out`, contact sheets, JUnit, traces, or recordings. From a729f39f1ab096fde0aee39abda8aff2838831f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 20:32:52 +0100 Subject: [PATCH 26/55] test(remote): avoid closure-narrowed capture request --- .../src/__tests__/capture-destination-record.test.ts | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/packages/remote/src/__tests__/capture-destination-record.test.ts b/packages/remote/src/__tests__/capture-destination-record.test.ts index 0dba9697526..4f16409c1e6 100644 --- a/packages/remote/src/__tests__/capture-destination-record.test.ts +++ b/packages/remote/src/__tests__/capture-destination-record.test.ts @@ -45,13 +45,13 @@ test.each(['trace', 'perf'] as const)( stateDir, async () => success, ); - let sent: DaemonWireRequest | undefined; + const sent: DaemonWireRequest[] = []; await sendRemoteCapture( endpoint, request('stop', undefined, { family }), stateDir, async (req) => { - sent = req; + sent.push(req); await materializeRemoteArtifacts( { baseUrl: endpoint, token: 'test' }, req, @@ -62,18 +62,17 @@ test.each(['trace', 'perf'] as const)( return success; }, ); - expect(sent?.meta?.clientArtifactPaths?.outPath).toBe(destination); - sent = undefined; + expect(sent[0]?.meta?.clientArtifactPaths?.outPath).toBe(destination); await sendRemoteCapture( endpoint, request('stop', undefined, { family }), stateDir, async (req) => { - sent = req; + sent.push(req); return success; }, ); - expect(sent?.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + expect(sent[1]?.meta?.clientArtifactPaths?.outPath).toBeUndefined(); }, ); From 179b4909707edb6d52960a80c1691862f6b630c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 20:32:52 +0100 Subject: [PATCH 27/55] chore(gates): record capture materialization compatibility --- test/wire-compat/ledger.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index f844aefdb1e..64b02ff324d 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -159,7 +159,7 @@ "packages/remote/src/daemon-artifacts.ts#buildDaemonArtifactUrl": "sha256:06dcde057809b507f70f7bb5cdef9bde6515be84b67e45865cf19e70b8636208", "packages/remote/src/daemon-artifacts.ts#downloadRemoteArtifact": "sha256:3f3b6c01601c54ab2c76c8cb0946de623da4d24ba32254c75ae8a3993f66adcf", "packages/remote/src/daemon-artifacts.ts#isRemoteDaemon": "sha256:0f6a714c5f60ce4e8548d811b516d8b6241eca9f7e5414733732da395b8a00e7", - "packages/remote/src/daemon-artifacts.ts#materializeRemoteArtifacts": "sha256:6d9aba219e6fafbdbcef76d30ed99fbb4f61dcc525242a0a76c3dc1bdacd24e2", + "packages/remote/src/daemon-artifacts.ts#materializeRemoteArtifacts": "sha256:35b77d752799782ae0082b3123f9572e222a67f7d59d18c294c484d4226aabb7", "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath": "sha256:0495174ab15a8c5a7c159eb957d3fc463a856b151c47a77cf0d567eb9843ee21", "packages/remote/src/daemon-artifacts.ts#resolveOrdinaryArtifactFallbackPath": "sha256:c0fdd490bb6e596adbbc2b9db35230eac5373c313fc5a230ac09ec70320694bb", "packages/remote/src/remote-request-diagnostics.ts#RemoteDaemonErrorPayload": "sha256:8fbcbcdf4bae7b66a08e465a72593794f36364759f18f1a814cd39dfdb76f309", @@ -674,8 +674,8 @@ }, { "declaration": "packages/remote/src/daemon-artifacts.ts#materializeRemoteArtifacts", - "digest": "sha256:6d9aba219e6fafbdbcef76d30ed99fbb4f61dcc525242a0a76c3dc1bdacd24e2", - "rationale": "Passes the in-memory fetchRemoteArtifact to the session-script owner instead of the file download. Which artifacts are requested is unchanged, and the wire fields are unchanged; the client no longer adds a repeat warning to its own output. The GET /artifacts/:id request, its headers and the response framing are unchanged, so a peer on the same protocol sees the same bytes." + "digest": "sha256:35b77d752799782ae0082b3123f9572e222a67f7d59d18c294c484d4226aabb7", + "rationale": "Passes the in-memory fetchRemoteArtifact to the session-script owner instead of the file download, and retires a client-local capture destination before downloading a successful stop's artifacts. A pathless stop can carry the existing optional meta.clientArtifactPaths.outPath from client state; an older daemon can ignore that hint or use it as before. An older client receives the same response and retains its fallback. The GET /artifacts/:id request, headers, artifact fields, and response framing are unchanged." }, { "declaration": "packages/remote/src/script-version-publisher.ts#publishScriptVersion", From c36d1cfe02ce26ecfd5bffafb3c47905271ec981 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 21:02:21 +0100 Subject: [PATCH 28/55] fix(client): address security review findings --- docs/adr/0041-credential-transport.md | 2 +- docs/agents/security.md | 15 +- ...emon-client-lifecycle-remote-trust.test.ts | 4 +- .../__tests__/runtime-target-position.test.ts | 2 +- .../internal/__tests__/selector-regex.test.ts | 40 +++-- .../maestro/src/internal/selector-regex.ts | 55 +++++-- .../daemon-proxy-credential-transport.test.ts | 1 + .../__tests__/package-closure-audit.test.ts | 32 +++- scripts/check-package.ts | 17 +-- scripts/lib/shipped-imports.ts | 16 ++ scripts/size-report-package.mjs | 2 +- .../provider-device-runtime.test.ts | 5 +- .../remote-daemon-client.test.ts | 5 +- test/repo-guards/maestro-regex-owner.test.ts | 139 +++++++++++++++++- website/docs/docs/remote-proxy.md | 7 +- website/docs/docs/security-trust.md | 2 +- 16 files changed, 280 insertions(+), 64 deletions(-) diff --git a/docs/adr/0041-credential-transport.md b/docs/adr/0041-credential-transport.md index 4ea0727eaee..2bd354218e0 100644 --- a/docs/adr/0041-credential-transport.md +++ b/docs/adr/0041-credential-transport.md @@ -2,7 +2,7 @@ ## Status -Accepted (2026-11-28). Enforcement is implemented by `admitCredentialDestination`. +Accepted (2026-11-28). `admitCredentialDestination` and upload tickets' `credentialTransportRefusal` use the shared rule. ADR 0006 continues to govern checked RPC. ## Rules at a glance diff --git a/docs/agents/security.md b/docs/agents/security.md index dfa92f8b768..89c6c2b19f5 100644 --- a/docs/agents/security.md +++ b/docs/agents/security.md @@ -1,19 +1,16 @@ # Security boundaries -The CLI client trusts its caller to choose local destinations. -The client trusts a remote daemon for data and validated identifiers. -Remote downloads use caller paths. Unnamed trace/perf files get unique client cwd names. -For remote trace or native perf, scope start paths by endpoint, tenant, run, lease, session, and kind. Before a new start, invalidate the old path. For a pathless stop, use only that record. After a successful stop, retire it before download. +The CLI client owns local destinations; it trusts a remote daemon only for data and validated IDs. +Scripts and remote record stops reject daemon-chosen paths (#4518). +Remote trace/perf uses caller paths. Unnamed captures get unique client cwd names. +For remote trace/native perf, key start paths by endpoint, tenant, run, lease, session, and kind. Before each start, invalidate the old path. A pathless stop uses only that record; a successful stop retires it before download. The daemon admits its state directory. Nobody trusts the network or other local users. Out of scope: same uid, hostile root, ACLs, mounts, untrusted filesystems. ADR 0041 owns credential transport. -## Applied today - -ADR 0016 judges caller-named script destinations by the writer's POSIX uid; both publishers commit there. -Remote script delivery caps memory and error answers. +ADR 0016 owns script destination writes and delivery limits. ## Proposed in #4669 -Do not apply #4669's private-write proposal for credentials and state before approval. +#4669's credential/state private-write proposal needs approval. Do not apply ADR 0016's path walk to screenshot `--out`, contact sheets, JUnit, traces, or recordings. diff --git a/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-trust.test.ts b/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-trust.test.ts index 543dbd7b872..b48e01528af 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-trust.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-trust.test.ts @@ -16,7 +16,9 @@ afterEach(() => { }); test('a plain http daemon off loopback is refused before the token leaves', async () => { - const request = vi.spyOn(http, 'request'); + const request = vi.spyOn(http, 'request').mockImplementation(() => { + throw new Error('insecure request reached the transport'); + }); await assert.rejects( assertRemoteServesCheckedRpc( diff --git a/packages/maestro/src/internal/__tests__/runtime-target-position.test.ts b/packages/maestro/src/internal/__tests__/runtime-target-position.test.ts index f56e34db3c3..fb8fa02c42d 100644 --- a/packages/maestro/src/internal/__tests__/runtime-target-position.test.ts +++ b/packages/maestro/src/internal/__tests__/runtime-target-position.test.ts @@ -90,7 +90,7 @@ test('applies index after composed positional intersections using y then x', () { index: 3, identifier: 'upper', rect: { x: 0, y: 80, width: 40, height: 30 } }, ]); const selector = { - id: 'candidate-.*', + id: 'candidate-(low|high)', index: 0, below: { id: 'upper' }, above: { id: 'lower' }, diff --git a/packages/maestro/src/internal/__tests__/selector-regex.test.ts b/packages/maestro/src/internal/__tests__/selector-regex.test.ts index 3fb3028f244..45a15d88fd3 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -12,6 +12,8 @@ test('matches Maestro regex as case-insensitive full patterns', () => { expect(matchesMaestroRegex('item 22', String.raw`item [0-9]+`)).toBe(true); expect(matchesMaestroRegex('Item 22 ready', String.raw`Item \d+\s+ready`)).toBe(true); expect(matchesMaestroRegex('Item 8', String.raw`Item \8`)).toBe(true); + expect(matchesMaestroRegex('aaab', '(a+)b')).toBe(true); + expect(matchesMaestroRegex('aaabbb', '(a+)b+')).toBe(true); }); test.each([ @@ -19,6 +21,10 @@ test.each([ '(a|aa)+', 'a*a*', 'a*b*a*', + 'a+(?:|a)a+b', + 'a+(?=a)a+b', + 'a+(?:a*)b', + '(?:a+)a+b', '(a+){2}', String.raw`(a+)\1`, '(a|aa)(a|aa)(a|aa)(a|aa)(a|aa)(a|aa)', @@ -31,23 +37,28 @@ test.each([ ); }); +test('refuses a nullable separator before matching a maximum-length node value', () => { + expect(() => matchesMaestroRegex(`${'a'.repeat(8191)}X`, 'a+(?:|a)a+b')).toThrow( + expect.objectContaining({ + code: 'INVALID_ARGS', + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); +}); + test('extracts only patterns that are exact literals', () => { expect(literalFromMaestroRegex('checkout-submit')).toBe('checkout-submit'); expect(literalFromMaestroRegex(String.raw`price\.usd`)).toBe('price.usd'); expect(literalFromMaestroRegex(String.raw`item \d{2}`)).toBeUndefined(); expect(literalFromMaestroRegex('item [ready')).toBe('item [ready'); + expect(literalFromMaestroRegex('a'.repeat(8193))).toBe('a'.repeat(8193)); + expect(literalFromMaestroRegex(`${'a'.repeat(8193)}*`)).toBeUndefined(); }); -test('long device labels keep literal matches but cannot silently pass regex absence', () => { +test('long device labels keep literal matches and cannot drive the regex matcher', () => { expect(matchesMaestroRegex('a'.repeat(8193), 'item')).toBe(false); expect(matchesMaestroRegex('a'.repeat(8193), 'a'.repeat(8193))).toBe(true); - expect(() => matchesMaestroRegex(`Details: ${'x'.repeat(8300)} End`, 'Details: x+ End')).toThrow( - expect.objectContaining({ - code: 'INVALID_ARGS', - message: 'Maestro selector node value exceeds 8192 characters.', - details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), - }), - ); + expect(matchesMaestroRegex(`Details: ${'x'.repeat(8300)} End`, 'Details: x+ End')).toBe(false); expect(matchesMaestroRegex('item', 'item')).toBe(true); }); @@ -57,7 +68,7 @@ test('escaped brackets and braces match literal node text', () => { expect(matchesMaestroRegex('price 22', String.raw`price {2}`)).toBe(false); }); -test('literal matches preserve text while regex-shaped matches still pass the guard', () => { +test('literal matches preserve text while regex-shaped patterns use regex semantics', () => { expect(matchesMaestroRegex(' Save now ', 'save now')).toBe(true); expect(matchesMaestroRegex('a'.repeat(257), 'a'.repeat(257))).toBe(true); expect(() => matchesMaestroRegex('a*a*', 'a*a*')).toThrow( @@ -66,8 +77,15 @@ test('literal matches preserve text while regex-shaped matches still pass the gu }), ); expect(matchesMaestroRegex('Item 22 [ready', 'Item 22 [ready')).toBe(true); - expect(matchesMaestroRegex('Terms | Privacy', 'Terms | Privacy')).toBe(true); - expect(() => matchesMaestroRegex('a'.repeat(256), 'a'.repeat(257))).toThrow( + expect(matchesMaestroRegex('Terms | Privacy', 'Terms | Privacy')).toBe(false); + expect(matchesMaestroRegex('(a|b)', '(a|b)')).toBe(false); + expect(matchesMaestroRegex('a'.repeat(256), 'a'.repeat(257))).toBe(false); + expect(() => matchesMaestroRegex('a'.repeat(8193), `${'a'.repeat(8193)}*`)).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); + expect(() => matchesMaestroRegex('a'.repeat(256), `(${`a`.repeat(255)})`)).toThrow( expect.objectContaining({ details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), }), diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index dfd9dd84d00..621688ee840 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -15,24 +15,13 @@ const parser = new RegExpParser(); const matcherCache = new Map(); export function matchesMaestroRegex(value: string, pattern: string): boolean { - if (normalizeText(value) === normalizeText(pattern)) { - if (literalFromMaestroRegex(pattern) === undefined) matcherForPattern(pattern); - return true; - } const matcher = matcherForPattern(pattern); - if ('literal' in matcher) - return value.toLocaleLowerCase() === matcher.literal.toLocaleLowerCase(); - if (value.length > MAX_VALUE_LENGTH) { - throw new AppError('INVALID_ARGS', 'Maestro selector node value exceeds 8192 characters.', { - reason: MAESTRO_SELECTOR_REGEX_REASONS.unsafe.reason, - retriable: false, - }); - } + if ('literal' in matcher) return normalizeText(value) === normalizeText(matcher.literal); + if (value.length > MAX_VALUE_LENGTH) return false; return matcher.regex.test(value); } function matcherForPattern(pattern: string): { literal: string } | { regex: RegExp } { - if (pattern.length > MAX_PATTERN_LENGTH) unsafeMaestroRegex(); const cached = matcherCache.get(pattern); if (cached) return cached; const literal = literalFromMaestroRegex(pattern); @@ -40,6 +29,7 @@ function matcherForPattern(pattern: string): { literal: string } | { regex: RegE if (literal !== undefined) { matcher = { literal }; } else { + if (pattern.length > MAX_PATTERN_LENGTH) unsafeMaestroRegex(); assertBoundedMaestroPattern(pattern); try { matcher = { regex: new RegExp(`^(?:${pattern})$`, 'ims') }; @@ -85,8 +75,31 @@ function assertBoundedMaestroPattern(pattern: string): void { function assertDisjointAlternativeQuantifiers(node: AST.Alternative): void { for (let index = 0; index < node.elements.length; index += 1) { const first = node.elements[index]; - if (first?.type !== 'Quantifier' || first.max === first.min) continue; - assertDisjointFollowingQuantifiers(node.elements, index, first); + if (first?.type === 'Quantifier' && first.max !== first.min) { + assertDisjointFollowingQuantifiers(node.elements, index, first); + } else if (first?.type === 'Group' || first?.type === 'CapturingGroup') { + assertDisjointGroupedQuantifiers(node.elements, index, first); + } + } +} + +function assertDisjointGroupedQuantifiers( + elements: AST.Alternative['elements'], + index: number, + group: AST.Group | AST.CapturingGroup, +): void { + const nested: AST.Quantifier[] = []; + visitRegExpAST(group, { + onQuantifierEnter(node) { + if (node.max > node.min) nested.push(node); + }, + }); + if (nested.length === 0) return; + for (const later of elements.slice(index + 1)) { + if (later.type !== 'Quantifier' || later.max === later.min) continue; + if (nested.some((earlier) => !quantifiedAtomsAreDisjoint(earlier.element, later.element))) { + unsafeMaestroRegex(); + } } } @@ -97,7 +110,11 @@ function assertDisjointFollowingQuantifiers( ): void { for (let next = index + 1; next < elements.length; next += 1) { const element = elements[next]; - if (element?.type === 'Assertion') continue; + if (element?.type === 'Assertion') { + if ('alternatives' in element) unsafeMaestroRegex(); + continue; + } + if (element?.type === 'Group' || element?.type === 'CapturingGroup') unsafeMaestroRegex(); if (element?.type === 'Quantifier') { if ( element.max > element.min && @@ -135,6 +152,12 @@ function unsafeMaestroRegex(): never { } export function literalFromMaestroRegex(pattern: string): string | undefined { + if (pattern.length > MAX_PATTERN_LENGTH) { + for (const character of pattern) { + if (REGEX_SYNTAX.has(character)) return undefined; + } + return pattern; + } try { new RegExp(pattern); } catch { diff --git a/packages/proxy/src/daemon-proxy-credential-transport.test.ts b/packages/proxy/src/daemon-proxy-credential-transport.test.ts index b9da325b3ac..7bb2e997dff 100644 --- a/packages/proxy/src/daemon-proxy-credential-transport.test.ts +++ b/packages/proxy/src/daemon-proxy-credential-transport.test.ts @@ -37,6 +37,7 @@ test('plain http upstream off loopback is refused ahead of any send', async () = const proxy = proxyFor('http://upstream.example.test:4310'); const response = await proxy.handle(health()); expect(response.status).toBe(400); + expect(await response.text()).not.toMatch(/daemon-secret/); expect(atSend).toEqual([]); expect(stderr).not.toMatch(/daemon-secret|AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT/); }); diff --git a/scripts/__tests__/package-closure-audit.test.ts b/scripts/__tests__/package-closure-audit.test.ts index 4f2742eb26e..45c0e95855c 100644 --- a/scripts/__tests__/package-closure-audit.test.ts +++ b/scripts/__tests__/package-closure-audit.test.ts @@ -17,7 +17,37 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { afterEach, test } from 'vitest'; -import { auditDependencyClosure, type PackedManifest } from '../lib/shipped-imports.ts'; +import { + auditDependencyClosure, + assertBundledWorkspaceDependencies, + type PackedManifest, +} from '../lib/shipped-imports.ts'; + +test('a bundled workspace dependency needs rendered notice attribution', () => { + assert.throws( + () => assertBundledWorkspaceDependencies(new Set(['regexpp']), new Set(), new Map()), + /does not attribute rendered regexpp modules/, + ); + assert.doesNotThrow(() => + assertBundledWorkspaceDependencies( + new Set(['regexpp']), + new Set(['regexpp@4.12.2 (MIT)']), + new Map(), + ), + ); +}); + +test('a bundled workspace dependency cannot retain a shipped runtime import', () => { + assert.throws( + () => + assertBundledWorkspaceDependencies( + new Set(['regexpp']), + new Set(['regexpp@4.12.2 (MIT)']), + new Map([['regexpp', ['dist/cli.js']]]), + ), + /still imports regexpp at runtime/, + ); +}); const tempRoots: string[] = []; diff --git a/scripts/check-package.ts b/scripts/check-package.ts index 3ee39d0ebbc..fe002a11893 100644 --- a/scripts/check-package.ts +++ b/scripts/check-package.ts @@ -28,6 +28,7 @@ import os from 'node:os'; import path from 'node:path'; import { auditDependencyClosure, + assertBundledWorkspaceDependencies, type PackedManifest as PackedDependencies, } from './lib/shipped-imports.ts'; import { assertInstalledSnapshotBridge } from './size-report-install.mjs'; @@ -36,6 +37,7 @@ import { bundledDependencyNames } from './bundled-dependency-names.ts'; import { readWorkspacePackages } from './layering/package-boundaries.ts'; import { assertBundledLicenseNotices, + BUNDLED_LICENSE_NOTICES_PATH, parseNpmPackOutput, type NpmPackEntry, } from './size-report-package.mjs'; @@ -295,16 +297,13 @@ try { ), ); const notices = readLicenseNotices( - fs.readFileSync(path.join(installedRoot, 'dist/src/THIRD_PARTY_NOTICES.txt'), 'utf8'), + fs.readFileSync(path.join(installedRoot, BUNDLED_LICENSE_NOTICES_PATH), 'utf8'), + ); + assertBundledWorkspaceDependencies( + bundledWorkspaceDependencies, + new Set(notices.attributions.map(({ label }) => label)), + importedBy, ); - for (const name of bundledWorkspaceDependencies) { - if (!notices.attributions.some(({ label }) => label.startsWith(`${name}@`))) { - throw new Error(`The packed bundle does not attribute rendered ${name} modules.`); - } - if (importedBy.has(name)) { - throw new Error(`The packed bundle still imports ${name} at runtime.`); - } - } step( `Confirmed ${bundledWorkspaceDependencies.size} workspace runtime dependencies are bundled.`, ); diff --git a/scripts/lib/shipped-imports.ts b/scripts/lib/shipped-imports.ts index 6acf2b83abb..339ae370549 100644 --- a/scripts/lib/shipped-imports.ts +++ b/scripts/lib/shipped-imports.ts @@ -59,6 +59,22 @@ export type PackedManifest = { peerDependencies?: Record; }; +/** Prove that a workspace runtime dependency omitted from the root manifest is in the packed code. */ +export function assertBundledWorkspaceDependencies( + names: ReadonlySet, + attributionLabels: ReadonlySet, + importedBy: ReadonlyMap, +): void { + for (const name of names) { + if (![...attributionLabels].some((label) => label.startsWith(`${name}@`))) { + throw new Error(`The packed bundle does not attribute rendered ${name} modules.`); + } + if (importedBy.has(name)) { + throw new Error(`The packed bundle still imports ${name} at runtime.`); + } + } +} + /** Every file extension the package ships that Node can resolve a specifier from. */ const SHIPPED_SOURCE = /\.(?:m?js|cjs|d\.ts)$/; diff --git a/scripts/size-report-package.mjs b/scripts/size-report-package.mjs index f873a1c5575..a56fe2932fe 100644 --- a/scripts/size-report-package.mjs +++ b/scripts/size-report-package.mjs @@ -75,7 +75,7 @@ export function collectNpmPack(root) { * The notices asset a packed tree ships, and the build output it comes from. One path keeps the * manifest check and the content check naming the same file. */ -const BUNDLED_LICENSE_NOTICES_PATH = 'dist/src/THIRD_PARTY_NOTICES.txt'; +export const BUNDLED_LICENSE_NOTICES_PATH = 'dist/src/THIRD_PARTY_NOTICES.txt'; function describeUnresolvedAttribution(attribution) { return ( diff --git a/test/integration/provider-scenarios/provider-device-runtime.test.ts b/test/integration/provider-scenarios/provider-device-runtime.test.ts index eaf6874ece8..8f9f9e804bb 100644 --- a/test/integration/provider-scenarios/provider-device-runtime.test.ts +++ b/test/integration/provider-scenarios/provider-device-runtime.test.ts @@ -154,7 +154,10 @@ test('provider lease allocation is refused when no registered runtime claims the assert.equal(details.reason, 'provider-not-registered'); assert.equal(details.provider, 'testmu'); assert.deepEqual(details.registeredProviders, [FAKE_PROVIDER]); - assert.match(String(error.hint), /restart the daemon/i); + assert.equal( + error.hint, + 'Fix the plugin that failed to register (see failedPlugins or agent-device daemon status), restart the daemon, then retry lease allocation.', + ); const retried = await daemon.callCommand( 'lease_allocate', [], diff --git a/test/integration/provider-scenarios/remote-daemon-client.test.ts b/test/integration/provider-scenarios/remote-daemon-client.test.ts index 78b4aed2973..bfbd23526c0 100644 --- a/test/integration/provider-scenarios/remote-daemon-client.test.ts +++ b/test/integration/provider-scenarios/remote-daemon-client.test.ts @@ -554,7 +554,10 @@ async function assertRecordingArtifactRoundTrip( assert.equal(stop.recording, 'stopped'); const landed = stop.outPath; assert.equal(path.dirname(landed), paths.cwd); - assert.match(path.basename(landed), /^remote-recording-[0-9a-f-]{36}\.mp4$/); + assert.match( + path.basename(landed), + /^remote-recording-[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}\.mp4$/, + ); assert.deepEqual(fs.readFileSync(landed), RECORDING_BYTES); assert.equal(fs.existsSync(paths.recordingPath), false); assert.deepEqual( diff --git a/test/repo-guards/maestro-regex-owner.test.ts b/test/repo-guards/maestro-regex-owner.test.ts index 8061eff84b5..9951634b85c 100644 --- a/test/repo-guards/maestro-regex-owner.test.ts +++ b/test/repo-guards/maestro-regex-owner.test.ts @@ -32,19 +32,98 @@ function regexBypassViolations(source: string, filePath: string): string[] { regex?: unknown; start?: number; callee?: Node; + id?: Node; + init?: Node; + left?: Node; + object?: Node; property?: Node; arguments?: Node[]; + body?: Node[]; + declarations?: Node[]; + params?: Node[]; [key: string]: unknown; }; + type Scope = { parent?: Scope; bindings: Map }; function calledName(callee: Node | undefined): unknown { if (callee?.type === 'Identifier') return callee.name; if (callee?.type === 'MemberExpression') return callee.property?.name ?? callee.property?.value; return undefined; } - function isRegexBypass(node: Node): boolean { + function binding(scope: Scope, name: string): boolean | undefined { + for (let current: Scope | undefined = scope; current; current = current.parent) { + if (current.bindings.has(name)) return current.bindings.get(name); + } + return undefined; + } + function isRegexReference(node: Node | undefined, scope: Scope): boolean { + if (node?.type !== 'Identifier' || !node.name) return false; + return binding(scope, node.name) ?? node.name === 'RegExp'; + } + function bindPattern(node: Node | undefined, scope: Scope): void { + if (!node) return; + if (node.type === 'Identifier' && node.name) { + scope.bindings.set(node.name, false); + return; + } + if (node.type === 'Property') { + bindPattern(node.value as Node, scope); + return; + } + if (node.type === 'RestElement') { + bindPattern(node.argument as Node, scope); + return; + } + if (node.type === 'AssignmentPattern') { + bindPattern(node.left as Node, scope); + return; + } + if (node.type === 'ObjectPattern' || node.type === 'ArrayPattern') { + for (const child of Object.values(node)) { + if (Array.isArray(child)) for (const item of child) bindPattern(item, scope); + } + } + } + function blockScope(node: Node, parent: Scope): Scope { + const scope: Scope = { parent, bindings: new Map() }; + for (const statement of node.body ?? []) { + if (statement.type === 'VariableDeclaration') { + for (const declaration of statement.declarations ?? []) bindPattern(declaration.id, scope); + } else if ( + statement.type === 'FunctionDeclaration' || + statement.type === 'ClassDeclaration' + ) { + bindPattern(statement.id, scope); + } + } + for (const statement of node.body ?? []) { + if (statement.type !== 'VariableDeclaration') continue; + for (const declaration of statement.declarations ?? []) { + if (declaration.id?.type === 'Identifier' && isRegexReference(declaration.init, scope)) { + scope.bindings.set(declaration.id.name!, true); + } + } + } + return scope; + } + function isRegexBypass(node: Node, scope: Scope): boolean { if (node.type !== 'NewExpression' && node.type !== 'CallExpression') return false; const name = calledName(node.callee); - if (name === 'RegExp') return true; + if (isRegexReference(node.callee, scope)) return true; + if ( + node.type === 'CallExpression' && + node.callee?.type === 'MemberExpression' && + (name === 'call' || name === 'apply') && + isRegexReference(node.callee.object, scope) + ) + return true; + if ( + node.type === 'CallExpression' && + name === 'construct' && + node.callee?.object?.name === 'Reflect' && + binding(scope, 'Reflect') === undefined && + isRegexReference(node.arguments?.[0], scope) + ) + return true; return ( node.type === 'CallExpression' && node.callee?.type === 'MemberExpression' && @@ -52,20 +131,45 @@ function regexBypassViolations(source: string, filePath: string): string[] { node.arguments?.[0]?.regex === undefined ); } - function visit(value: unknown): void { + function visit(value: unknown, scope: Scope): void { if (!value || typeof value !== 'object') return; if (Array.isArray(value)) { - for (const item of value) visit(item); + for (const item of value) visit(item, scope); return; } const node = value as Node; - if (isRegexBypass(node)) { + let local = scope; + if (node.type === 'Program' || node.type === 'BlockStatement') { + local = blockScope(node, scope); + } else if ( + node.type === 'FunctionDeclaration' || + node.type === 'FunctionExpression' || + node.type === 'ArrowFunctionExpression' + ) { + local = { parent: scope, bindings: new Map() }; + bindPattern(node.id, local); + for (const parameter of node.params ?? []) bindPattern(parameter, local); + } else if (node.type === 'CatchClause') { + local = { parent: scope, bindings: new Map() }; + bindPattern(node.param as Node, local); + } else if ( + node.type === 'ForStatement' || + node.type === 'ForOfStatement' || + node.type === 'ForInStatement' + ) { + local = { parent: scope, bindings: new Map() }; + const declaration = node.type === 'ForStatement' ? node.init : node.left; + if (declaration?.type === 'VariableDeclaration') { + for (const item of declaration.declarations ?? []) bindPattern(item.id, local); + } + } + if (isRegexBypass(node, local)) { const line = source.slice(0, node.start).split('\n').length; violations.push(`${path.relative(SOURCE_ROOT, filePath)}:${line}`); } - for (const child of Object.values(node)) visit(child); + for (const child of Object.values(node)) visit(child, local); } - visit(parsed.program); + visit(parsed.program, { bindings: new Map() }); return violations; } @@ -87,7 +191,26 @@ test('Maestro regex guard catches direct and implicit construction', () => { 'value.matchAll(query)', 'value.search(query)', "value['match'](query)", + 'const R = RegExp; new R(query)', + 'Reflect.construct(RegExp, [query])', + 'RegExp.call(null, query)', + 'RegExp.apply(null, [query])', ].join(';'); - assert.equal(regexBypassViolations(source, 'fixture.ts').length, 6); + assert.equal(regexBypassViolations(source, 'fixture.ts').length, 10); assert.deepEqual(regexBypassViolations('value.matchAll(/fixed/g)', 'fixture.ts'), []); + assert.deepEqual( + regexBypassViolations('const R = RegExp; function use(R) { new R(query) }', 'fixture.ts'), + [], + ); + assert.deepEqual( + regexBypassViolations( + 'function use() { const RegExp = make(); new RegExp(query) }', + 'fixture.ts', + ), + [], + ); + assert.deepEqual( + regexBypassViolations('const R = RegExp; for (const R of values) new R(query)', 'fixture.ts'), + [], + ); }); diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index f8684f936e7..1d2bf1e9942 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -99,9 +99,10 @@ request. Without one, it downloads to a unique file in the working directory wit The directory of a `record start` path does not carry over. Direct RPC callers receive artifact IDs and download each result with `GET /artifacts/` using the same authentication. -For every artifact without a destination on the current request, the client appends a unique suffix -to the artifact file name in its working directory. A daemon-provided name or path cannot select an -existing client file, including for trace and performance stop or report. +For an artifact without a destination on the current request, the client uses a recorded start path +for a trace or performance stop when one exists. Otherwise, it appends a unique suffix to the +artifact file name in its working directory. A daemon-provided name or path cannot select an +existing client file. By default, artifacts leave the inventory after download or after 15 minutes. `AGENT_DEVICE_RETAIN_ARTIFACTS` keeps downloaded artifacts in inventory until expiry. Downloads already in progress diff --git a/website/docs/docs/security-trust.md b/website/docs/docs/security-trust.md index 88fdaa7b203..a2db1ad9ae9 100644 --- a/website/docs/docs/security-trust.md +++ b/website/docs/docs/security-trust.md @@ -45,7 +45,7 @@ In this setup the token and your device traffic travel between the two machines Before agent-device sends a credential to a plain `http://` URL whose host is not loopback (`localhost`, `127.0.0.0/8`, or `::1`), it refuses the connection with reason `insecure_credential_transport`. This applies to the remote daemon URL, the cloud URL, the Metro bridge URL, and the upstream URL of [`@agent-device/proxy`](https://www.npmjs.com/package/@agent-device/proxy) with its default transport. Upload tickets are already refused: if a ticket points to plain HTTP, for example because `--public-origin` is missing, the client does not use it and uploads through the daemon URL instead. -If your network already encrypts the route, for example a WireGuard or Tailscale address, you can allow plain HTTP for one process with `AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1`. This lifts the refusal. With this setting, anyone who can read the network path can read your token. Prefer Tailscale Serve or `ssh -L`, which need no override. `@agent-device/proxy` does not read this setting: give its default transport an https or loopback upstream, or supply your own `upstreamFetch`. +If your network already encrypts the route, for example a WireGuard or Tailscale address, you can allow plain HTTP in the client process that sends the credential with `AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1`. This lifts the refusal. With this setting, anyone who can read the network path can read your token. Prefer Tailscale Serve or `ssh -L`, which need no override. `@agent-device/proxy` does not read this setting: give its default transport an https or loopback upstream, or supply your own `upstreamFetch`. You stay responsible for these points: From 17af03433c5e175c8820851312eae6f492f1752a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 21:11:39 +0100 Subject: [PATCH 29/55] fix: keep Maestro regex guard and package declarations within CI contracts --- .../maestro/src/internal/selector-regex.ts | 40 ++++-- scripts/size-report-package.d.mts | 1 + test/repo-guards/maestro-regex-owner.test.ts | 122 ++++++++---------- 3 files changed, 85 insertions(+), 78 deletions(-) diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index 621688ee840..73d49de33c9 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -110,24 +110,30 @@ function assertDisjointFollowingQuantifiers( ): void { for (let next = index + 1; next < elements.length; next += 1) { const element = elements[next]; - if (element?.type === 'Assertion') { - if ('alternatives' in element) unsafeMaestroRegex(); + if (!element) break; + if (element.type === 'Assertion') { + assertSafeAssertion(element); continue; } - if (element?.type === 'Group' || element?.type === 'CapturingGroup') unsafeMaestroRegex(); + if (element.type === 'Group' || element.type === 'CapturingGroup') unsafeMaestroRegex(); if (element?.type === 'Quantifier') { - if ( - element.max > element.min && - !quantifiedAtomsAreDisjoint(first.element, element.element) - ) { - unsafeMaestroRegex(); - } + assertSafeFollowingQuantifier(first, element); if (element.min === 0) continue; } break; } } +function assertSafeAssertion(element: AST.Assertion): void { + if ('alternatives' in element) unsafeMaestroRegex(); +} + +function assertSafeFollowingQuantifier(first: AST.Quantifier, later: AST.Quantifier): void { + if (later.max > later.min && !quantifiedAtomsAreDisjoint(first.element, later.element)) { + unsafeMaestroRegex(); + } +} + function quantifiedAtomsAreDisjoint( left: AST.QuantifiableElement, right: AST.QuantifiableElement, @@ -153,10 +159,7 @@ function unsafeMaestroRegex(): never { export function literalFromMaestroRegex(pattern: string): string | undefined { if (pattern.length > MAX_PATTERN_LENGTH) { - for (const character of pattern) { - if (REGEX_SYNTAX.has(character)) return undefined; - } - return pattern; + return hasRegexSyntax(pattern) ? undefined : pattern; } try { new RegExp(pattern); @@ -164,6 +167,17 @@ export function literalFromMaestroRegex(pattern: string): string | undefined { return pattern; } + return literalFromEscapedPattern(pattern); +} + +function hasRegexSyntax(pattern: string): boolean { + for (const character of pattern) { + if (REGEX_SYNTAX.has(character)) return true; + } + return false; +} + +function literalFromEscapedPattern(pattern: string): string | undefined { let literal = ''; for (let index = 0; index < pattern.length; index += 1) { const character = pattern[index]!; diff --git a/scripts/size-report-package.d.mts b/scripts/size-report-package.d.mts index 2056499a205..48b1afc91f8 100644 --- a/scripts/size-report-package.d.mts +++ b/scripts/size-report-package.d.mts @@ -2,6 +2,7 @@ // it is not in the typechecked program). TypeScript resolves this file when a checked module // imports `./size-report-package.mjs`; keep it in step with the exports there. export const DOCUMENTED_PACK_STUBS: readonly string[]; +export const BUNDLED_LICENSE_NOTICES_PATH: string; export function readMacosHelperTestTargets(manifestSource: string): string[]; export type NpmPackEntry = Readonly<{ path: string; size: number }>; export function assertBundledLicenseNotices( diff --git a/test/repo-guards/maestro-regex-owner.test.ts b/test/repo-guards/maestro-regex-owner.test.ts index 9951634b85c..f054f99e406 100644 --- a/test/repo-guards/maestro-regex-owner.test.ts +++ b/test/repo-guards/maestro-regex-owner.test.ts @@ -65,104 +65,96 @@ function regexBypassViolations(source: string, filePath: string): string[] { scope.bindings.set(node.name, false); return; } - if (node.type === 'Property') { - bindPattern(node.value as Node, scope); - return; - } - if (node.type === 'RestElement') { - bindPattern(node.argument as Node, scope); - return; - } - if (node.type === 'AssignmentPattern') { - bindPattern(node.left as Node, scope); - return; - } - if (node.type === 'ObjectPattern' || node.type === 'ArrayPattern') { - for (const child of Object.values(node)) { - if (Array.isArray(child)) for (const item of child) bindPattern(item, scope); - } - } + for (const child of patternChildren(node)) bindPattern(child, scope); + } + function patternChildren(node: Node): Node[] { + if (node.type === 'Property') return [node.value as Node]; + if (node.type === 'RestElement') return [node.argument as Node]; + if (node.type === 'AssignmentPattern') return [node.left as Node]; + if (node.type !== 'ObjectPattern' && node.type !== 'ArrayPattern') return []; + return Object.values(node).flatMap((child) => (Array.isArray(child) ? (child as Node[]) : [])); } function blockScope(node: Node, parent: Scope): Scope { const scope: Scope = { parent, bindings: new Map() }; - for (const statement of node.body ?? []) { - if (statement.type === 'VariableDeclaration') { - for (const declaration of statement.declarations ?? []) bindPattern(declaration.id, scope); - } else if ( - statement.type === 'FunctionDeclaration' || - statement.type === 'ClassDeclaration' - ) { - bindPattern(statement.id, scope); - } + for (const statement of node.body ?? []) declareStatement(statement, scope); + for (const statement of node.body ?? []) bindRegexAliases(statement, scope); + return scope; + } + function declareStatement(statement: Node, scope: Scope): void { + if (statement.type === 'VariableDeclaration') { + for (const declaration of statement.declarations ?? []) bindPattern(declaration.id, scope); + } else if (statement.type === 'FunctionDeclaration' || statement.type === 'ClassDeclaration') { + bindPattern(statement.id, scope); } - for (const statement of node.body ?? []) { - if (statement.type !== 'VariableDeclaration') continue; - for (const declaration of statement.declarations ?? []) { - if (declaration.id?.type === 'Identifier' && isRegexReference(declaration.init, scope)) { - scope.bindings.set(declaration.id.name!, true); - } + } + function bindRegexAliases(statement: Node, scope: Scope): void { + if (statement.type !== 'VariableDeclaration') return; + for (const declaration of statement.declarations ?? []) { + if (declaration.id?.type === 'Identifier' && isRegexReference(declaration.init, scope)) { + scope.bindings.set(declaration.id.name!, true); } } - return scope; } function isRegexBypass(node: Node, scope: Scope): boolean { if (node.type !== 'NewExpression' && node.type !== 'CallExpression') return false; - const name = calledName(node.callee); if (isRegexReference(node.callee, scope)) return true; - if ( - node.type === 'CallExpression' && - node.callee?.type === 'MemberExpression' && - (name === 'call' || name === 'apply') && - isRegexReference(node.callee.object, scope) - ) - return true; - if ( - node.type === 'CallExpression' && - name === 'construct' && - node.callee?.object?.name === 'Reflect' && - binding(scope, 'Reflect') === undefined && - isRegexReference(node.arguments?.[0], scope) - ) + return node.type === 'CallExpression' && isIndirectRegexCall(node, scope); + } + function isIndirectRegexCall(node: Node, scope: Scope): boolean { + const name = calledName(node.callee); + if (node.callee?.type !== 'MemberExpression') return false; + if ((name === 'call' || name === 'apply') && isRegexReference(node.callee.object, scope)) { return true; + } + if (name === 'construct' && node.callee.object?.name === 'Reflect') { + return binding(scope, 'Reflect') === undefined && isRegexReference(node.arguments?.[0], scope); + } return ( - node.type === 'CallExpression' && - node.callee?.type === 'MemberExpression' && (name === 'match' || name === 'matchAll' || name === 'search') && node.arguments?.[0]?.regex === undefined ); } - function visit(value: unknown, scope: Scope): void { - if (!value || typeof value !== 'object') return; - if (Array.isArray(value)) { - for (const item of value) visit(item, scope); - return; - } - const node = value as Node; - let local = scope; + function scopeForNode(node: Node, scope: Scope): Scope { if (node.type === 'Program' || node.type === 'BlockStatement') { - local = blockScope(node, scope); - } else if ( + return blockScope(node, scope); + } + if ( node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression' ) { - local = { parent: scope, bindings: new Map() }; + const local: Scope = { parent: scope, bindings: new Map() }; bindPattern(node.id, local); for (const parameter of node.params ?? []) bindPattern(parameter, local); - } else if (node.type === 'CatchClause') { - local = { parent: scope, bindings: new Map() }; + return local; + } + if (node.type === 'CatchClause') { + const local: Scope = { parent: scope, bindings: new Map() }; bindPattern(node.param as Node, local); - } else if ( + return local; + } + if ( node.type === 'ForStatement' || node.type === 'ForOfStatement' || node.type === 'ForInStatement' ) { - local = { parent: scope, bindings: new Map() }; + const local: Scope = { parent: scope, bindings: new Map() }; const declaration = node.type === 'ForStatement' ? node.init : node.left; if (declaration?.type === 'VariableDeclaration') { for (const item of declaration.declarations ?? []) bindPattern(item.id, local); } + return local; + } + return scope; + } + function visit(value: unknown, scope: Scope): void { + if (!value || typeof value !== 'object') return; + if (Array.isArray(value)) { + for (const item of value) visit(item, scope); + return; } + const node = value as Node; + const local = scopeForNode(node, scope); if (isRegexBypass(node, local)) { const line = source.slice(0, node.start).split('\n').length; violations.push(`${path.relative(SOURCE_ROOT, filePath)}:${line}`); From ef6651f0c8c72956bc84f0182dbcf7774c947115 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 21:14:49 +0100 Subject: [PATCH 30/55] chore(gates): format Maestro regex guard --- test/repo-guards/maestro-regex-owner.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/repo-guards/maestro-regex-owner.test.ts b/test/repo-guards/maestro-regex-owner.test.ts index f054f99e406..aaa45014a40 100644 --- a/test/repo-guards/maestro-regex-owner.test.ts +++ b/test/repo-guards/maestro-regex-owner.test.ts @@ -107,7 +107,9 @@ function regexBypassViolations(source: string, filePath: string): string[] { return true; } if (name === 'construct' && node.callee.object?.name === 'Reflect') { - return binding(scope, 'Reflect') === undefined && isRegexReference(node.arguments?.[0], scope); + return ( + binding(scope, 'Reflect') === undefined && isRegexReference(node.arguments?.[0], scope) + ); } return ( (name === 'match' || name === 'matchAll' || name === 'search') && From a1c00f5f7520db303695e557c613bc4bc3d2e2c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 21:22:43 +0100 Subject: [PATCH 31/55] fix: isolate provider hint scenario and simplify regex guard scopes --- .../provider-device-runtime.test.ts | 4 +- test/repo-guards/maestro-regex-owner.test.ts | 59 ++++++++++--------- 2 files changed, 34 insertions(+), 29 deletions(-) diff --git a/test/integration/provider-scenarios/provider-device-runtime.test.ts b/test/integration/provider-scenarios/provider-device-runtime.test.ts index 8f9f9e804bb..ce6c9f2d5c3 100644 --- a/test/integration/provider-scenarios/provider-device-runtime.test.ts +++ b/test/integration/provider-scenarios/provider-device-runtime.test.ts @@ -125,6 +125,7 @@ test('provider lease allocation is refused when no registered runtime claims the const daemon = await createProviderScenarioHarness({ providerRuntimeIds: [FAKE_PROVIDER], deviceInventoryProvider: async () => null, + pluginInventory: [], }); // A daemon never reuses an id it issued, so naming the refused lease's id again proves no lease // was recorded. @@ -154,9 +155,10 @@ test('provider lease allocation is refused when no registered runtime claims the assert.equal(details.reason, 'provider-not-registered'); assert.equal(details.provider, 'testmu'); assert.deepEqual(details.registeredProviders, [FAKE_PROVIDER]); + assert.equal(details.failedPlugins, undefined); assert.equal( error.hint, - 'Fix the plugin that failed to register (see failedPlugins or agent-device daemon status), restart the daemon, then retry lease allocation.', + 'Restart the daemon with testmu configured, then retry lease allocation.', ); const retried = await daemon.callCommand( 'lease_allocate', diff --git a/test/repo-guards/maestro-regex-owner.test.ts b/test/repo-guards/maestro-regex-owner.test.ts index aaa45014a40..5911943cc9a 100644 --- a/test/repo-guards/maestro-regex-owner.test.ts +++ b/test/repo-guards/maestro-regex-owner.test.ts @@ -117,35 +117,38 @@ function regexBypassViolations(source: string, filePath: string): string[] { ); } function scopeForNode(node: Node, scope: Scope): Scope { - if (node.type === 'Program' || node.type === 'BlockStatement') { - return blockScope(node, scope); - } - if ( - node.type === 'FunctionDeclaration' || - node.type === 'FunctionExpression' || - node.type === 'ArrowFunctionExpression' - ) { - const local: Scope = { parent: scope, bindings: new Map() }; - bindPattern(node.id, local); - for (const parameter of node.params ?? []) bindPattern(parameter, local); - return local; - } - if (node.type === 'CatchClause') { - const local: Scope = { parent: scope, bindings: new Map() }; - bindPattern(node.param as Node, local); - return local; - } - if ( - node.type === 'ForStatement' || - node.type === 'ForOfStatement' || - node.type === 'ForInStatement' - ) { - const local: Scope = { parent: scope, bindings: new Map() }; - const declaration = node.type === 'ForStatement' ? node.init : node.left; - if (declaration?.type === 'VariableDeclaration') { - for (const item of declaration.declarations ?? []) bindPattern(item.id, local); + switch (node.type) { + case 'Program': + case 'BlockStatement': + return blockScope(node, scope); + case 'FunctionDeclaration': + case 'FunctionExpression': + case 'ArrowFunctionExpression': + return functionScope(node, scope); + case 'CatchClause': { + const local: Scope = { parent: scope, bindings: new Map() }; + bindPattern(node.param as Node, local); + return local; } - return local; + case 'ForStatement': + case 'ForOfStatement': + case 'ForInStatement': + return loopScope(node, scope); + default: + return scope; + } + } + function functionScope(node: Node, parent: Scope): Scope { + const scope: Scope = { parent, bindings: new Map() }; + bindPattern(node.id, scope); + for (const parameter of node.params ?? []) bindPattern(parameter, scope); + return scope; + } + function loopScope(node: Node, parent: Scope): Scope { + const scope: Scope = { parent, bindings: new Map() }; + const declaration = node.type === 'ForStatement' ? node.init : node.left; + if (declaration?.type === 'VariableDeclaration') { + for (const item of declaration.declarations ?? []) bindPattern(item.id, scope); } return scope; } From aab1b0ad1ca270c2924347c1fb7c988d1ed82cc1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 22:27:00 +0100 Subject: [PATCH 32/55] fix(maestro): preserve exact text for safe regex-shaped selectors --- .../src/internal/__tests__/selector-regex.test.ts | 9 ++++++--- packages/maestro/src/internal/selector-regex.ts | 1 + website/docs/docs/run-maestro-flows.md | 2 +- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/packages/maestro/src/internal/__tests__/selector-regex.test.ts b/packages/maestro/src/internal/__tests__/selector-regex.test.ts index 45a15d88fd3..0dbef56795a 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -68,7 +68,7 @@ test('escaped brackets and braces match literal node text', () => { expect(matchesMaestroRegex('price 22', String.raw`price {2}`)).toBe(false); }); -test('literal matches preserve text while regex-shaped patterns use regex semantics', () => { +test('literal matches preserve text before safe regex-shaped patterns use regex semantics', () => { expect(matchesMaestroRegex(' Save now ', 'save now')).toBe(true); expect(matchesMaestroRegex('a'.repeat(257), 'a'.repeat(257))).toBe(true); expect(() => matchesMaestroRegex('a*a*', 'a*a*')).toThrow( @@ -77,8 +77,11 @@ test('literal matches preserve text while regex-shaped patterns use regex semant }), ); expect(matchesMaestroRegex('Item 22 [ready', 'Item 22 [ready')).toBe(true); - expect(matchesMaestroRegex('Terms | Privacy', 'Terms | Privacy')).toBe(false); - expect(matchesMaestroRegex('(a|b)', '(a|b)')).toBe(false); + expect(matchesMaestroRegex('Terms | Privacy', 'Terms | Privacy')).toBe(true); + expect(matchesMaestroRegex('(a|b)', '(a|b)')).toBe(true); + expect(matchesMaestroRegex('Terms ', 'Terms | Privacy')).toBe(true); + expect(matchesMaestroRegex('a'.repeat(8193), 'a+')).toBe(false); + expect(matchesMaestroRegex('a'.repeat(8193), 'a'.repeat(8193))).toBe(true); expect(matchesMaestroRegex('a'.repeat(256), 'a'.repeat(257))).toBe(false); expect(() => matchesMaestroRegex('a'.repeat(8193), `${'a'.repeat(8193)}*`)).toThrow( expect.objectContaining({ diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index 73d49de33c9..953d801528c 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -18,6 +18,7 @@ export function matchesMaestroRegex(value: string, pattern: string): boolean { const matcher = matcherForPattern(pattern); if ('literal' in matcher) return normalizeText(value) === normalizeText(matcher.literal); if (value.length > MAX_VALUE_LENGTH) return false; + if (normalizeText(value) === normalizeText(pattern)) return true; return matcher.regex.test(value); } diff --git a/website/docs/docs/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index c82b034d73a..8fa65f93505 100644 --- a/website/docs/docs/run-maestro-flows.md +++ b/website/docs/docs/run-maestro-flows.md @@ -30,7 +30,7 @@ Keep the target binding, such as `--platform ios`, on the `replay` or `test` com ## Boundaries -- Selector `id` and `text` match exact text before interpreting a pattern as a regular expression. Regex patterns can use groups, alternatives, character classes, and counted or disjoint repetitions. Backreferences, overlapping repetitions, quantified groups with alternatives or repetitions, excessive ambiguous groups, and regex patterns over 256 characters fail with `maestro_selector_regex_unsafe`. A regex against a node value over 8192 characters also fails with that reason; an exact text match remains available. These limits keep matching bounded. +- Selector `id` and `text` match exact text before interpreting a safe pattern as a regular expression. Regex patterns can use groups, alternatives, character classes, and counted or disjoint repetitions. Backreferences, overlapping repetitions, quantified groups with alternatives or repetitions, excessive ambiguous groups, and regex patterns over 256 characters fail with `maestro_selector_regex_unsafe`. A regex against a node value over 8192 characters does not match; exact literal text matching remains available. These limits keep matching bounded. - 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 a36cd0772205e62ce6c0d28cfe88d54df5312f5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 23:32:19 +0100 Subject: [PATCH 33/55] fix(maestro): bound selector regex paths and retain full text matches --- .../internal/__tests__/selector-regex.test.ts | 31 ++- .../maestro/src/internal/selector-regex.ts | 177 +++++++++++------- website/docs/docs/run-maestro-flows.md | 2 +- 3 files changed, 141 insertions(+), 69 deletions(-) diff --git a/packages/maestro/src/internal/__tests__/selector-regex.test.ts b/packages/maestro/src/internal/__tests__/selector-regex.test.ts index 0dbef56795a..ec2679d9e07 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -14,6 +14,11 @@ test('matches Maestro regex as case-insensitive full patterns', () => { expect(matchesMaestroRegex('Item 8', String.raw`Item \8`)).toBe(true); expect(matchesMaestroRegex('aaab', '(a+)b')).toBe(true); expect(matchesMaestroRegex('aaabbb', '(a+)b+')).toBe(true); + expect(matchesMaestroRegex('AB12', '[A-Z]+[0-9]+')).toBe(true); + expect(matchesMaestroRegex('aa12', String.raw`a+\d+`)).toBe(true); + expect(matchesMaestroRegex('ab12', String.raw`[a-z]+\d+`)).toBe(true); + expect(matchesMaestroRegex('12kg', String.raw`\d+(kg|lb)`)).toBe(true); + expect(matchesMaestroRegex('Status\nReady\nDetails', 'Ready')).toBe(true); }); test.each([ @@ -21,6 +26,11 @@ test.each([ '(a|aa)+', 'a*a*', 'a*b*a*', + '.*a.*b', + '.*x.*y.*z', + '.*a.*a.*a.*b', + '(a*)(a*)b', + '(?:aa)+a+b', 'a+(?:|a)a+b', 'a+(?=a)a+b', 'a+(?:a*)b', @@ -46,6 +56,17 @@ test('refuses a nullable separator before matching a maximum-length node value', ); }); +test('refuses overlapping wildcard and grouped repetitions before a long node value runs', () => { + const value = `${'a\n'.repeat(4096)}X`; + for (const pattern of ['.*a.*b', '.*a.*a.*a.*b', '(a*)(a*)b']) { + expect(() => matchesMaestroRegex(value, pattern)).toThrow( + 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'); expect(literalFromMaestroRegex(String.raw`price\.usd`)).toBe('price.usd'); @@ -55,10 +76,14 @@ test('extracts only patterns that are exact literals', () => { expect(literalFromMaestroRegex(`${'a'.repeat(8193)}*`)).toBeUndefined(); }); -test('long device labels keep literal matches and cannot drive the regex matcher', () => { +test('long device labels retain literal and bounded regex matches', () => { expect(matchesMaestroRegex('a'.repeat(8193), 'item')).toBe(false); expect(matchesMaestroRegex('a'.repeat(8193), 'a'.repeat(8193))).toBe(true); - expect(matchesMaestroRegex(`Details: ${'x'.repeat(8300)} End`, 'Details: x+ End')).toBe(false); + expect(matchesMaestroRegex(`Status\n${'A'.repeat(8193)}\nDetails`, 'a'.repeat(8193))).toBe(true); + expect(matchesMaestroRegex(`Status\n${'A'.repeat(8192)}X\nDetails`, 'a'.repeat(8193))).toBe( + false, + ); + expect(matchesMaestroRegex(`Details: ${'x'.repeat(8300)} End`, 'Details: x+ End')).toBe(true); expect(matchesMaestroRegex('item', 'item')).toBe(true); }); @@ -80,7 +105,7 @@ test('literal matches preserve text before safe regex-shaped patterns use regex expect(matchesMaestroRegex('Terms | Privacy', 'Terms | Privacy')).toBe(true); expect(matchesMaestroRegex('(a|b)', '(a|b)')).toBe(true); expect(matchesMaestroRegex('Terms ', 'Terms | Privacy')).toBe(true); - expect(matchesMaestroRegex('a'.repeat(8193), 'a+')).toBe(false); + expect(matchesMaestroRegex('a'.repeat(8193), 'a+')).toBe(true); expect(matchesMaestroRegex('a'.repeat(8193), 'a'.repeat(8193))).toBe(true); expect(matchesMaestroRegex('a'.repeat(256), 'a'.repeat(257))).toBe(false); expect(() => matchesMaestroRegex('a'.repeat(8193), `${'a'.repeat(8193)}*`)).toThrow( diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index 953d801528c..774873c0ebd 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -9,24 +9,55 @@ const MAESTRO_SELECTOR_REGEX_REASONS = { const REGEX_SYNTAX = new Set(String.raw`^$\.*+?()[]{}|`); const MAX_PATTERN_LENGTH = 256; -const MAX_VALUE_LENGTH = 8192; const MAX_CACHED_PATTERNS = 128; +const MAX_PATTERN_PATHS = 32; const parser = new RegExpParser(); -const matcherCache = new Map(); +type RegexElement = AST.Alternative['elements'][number]; +type LiteralMatcher = { literal: string; lineRegex?: RegExp }; +type Matcher = LiteralMatcher | { regex: RegExp }; +const matcherCache = new Map(); export function matchesMaestroRegex(value: string, pattern: string): boolean { const matcher = matcherForPattern(pattern); - if ('literal' in matcher) return normalizeText(value) === normalizeText(matcher.literal); - if (value.length > MAX_VALUE_LENGTH) return false; + if ('literal' in matcher) return matchesLiteral(value, matcher); if (normalizeText(value) === normalizeText(pattern)) return true; return matcher.regex.test(value); } -function matcherForPattern(pattern: string): { literal: string } | { regex: RegExp } { +function matchesLiteral(value: string, matcher: LiteralMatcher): boolean { + if (normalizeText(value) === normalizeText(matcher.literal)) return true; + if (matcher.literal.length > MAX_PATTERN_LENGTH) { + return matchesLongLiteralLine(value, matcher.literal); + } + matcher.lineRegex ??= new RegExp( + `^(?:${matcher.literal.replaceAll(/[\\^$.*+?()[\]{}|]/g, '\\$&')})$`, + 'im', + ); + return matcher.lineRegex.test(value); +} + +function matchesLongLiteralLine(value: string, literal: string): boolean { + const text = value.toLowerCase(); + const query = literal.toLowerCase(); + for (let index = text.indexOf(query); index >= 0; index = text.indexOf(query, index + 1)) { + const before = index === 0 || isLineTerminator(text[index - 1]); + const after = index + query.length; + if (before && (after === text.length || isLineTerminator(text[after]))) return true; + } + return false; +} + +function isLineTerminator(character: string | undefined): boolean { + return ( + character === '\n' || character === '\r' || character === '\u2028' || character === '\u2029' + ); +} + +function matcherForPattern(pattern: string): Matcher { const cached = matcherCache.get(pattern); if (cached) return cached; const literal = literalFromMaestroRegex(pattern); - let matcher: { literal: string } | { regex: RegExp }; + let matcher: Matcher; if (literal !== undefined) { matcher = { literal }; } else { @@ -58,6 +89,9 @@ function assertBoundedMaestroPattern(pattern: string): void { }; visitRegExpAST(parsed, { onBackreferenceEnter: unsafeMaestroRegex, + onAssertionEnter(node) { + if ('alternatives' in node) unsafeMaestroRegex(); + }, onGroupEnter(node) { countAlternatives(node.alternatives.length); }, @@ -69,86 +103,99 @@ function assertBoundedMaestroPattern(pattern: string): void { if (node.element.alternatives.length > 1) unsafeMaestroRegex(); visitRegExpAST(node.element, { onQuantifierEnter: unsafeMaestroRegex }); }, - onAlternativeEnter: assertDisjointAlternativeQuantifiers, }); -} - -function assertDisjointAlternativeQuantifiers(node: AST.Alternative): void { - for (let index = 0; index < node.elements.length; index += 1) { - const first = node.elements[index]; - if (first?.type === 'Quantifier' && first.max !== first.min) { - assertDisjointFollowingQuantifiers(node.elements, index, first); - } else if (first?.type === 'Group' || first?.type === 'CapturingGroup') { - assertDisjointGroupedQuantifiers(node.elements, index, first); - } + for (const alternative of parsed.alternatives) { + for (const path of expandedPaths(alternative.elements)) assertDisjointQuantifiers(path); } } -function assertDisjointGroupedQuantifiers( - elements: AST.Alternative['elements'], - index: number, - group: AST.Group | AST.CapturingGroup, -): void { - const nested: AST.Quantifier[] = []; - visitRegExpAST(group, { - onQuantifierEnter(node) { - if (node.max > node.min) nested.push(node); - }, - }); - if (nested.length === 0) return; - for (const later of elements.slice(index + 1)) { - if (later.type !== 'Quantifier' || later.max === later.min) continue; - if (nested.some((earlier) => !quantifiedAtomsAreDisjoint(earlier.element, later.element))) { - unsafeMaestroRegex(); - } +function expandedPaths(elements: AST.Alternative['elements']): RegexElement[][] { + let paths: RegexElement[][] = [[]]; + for (const element of elements) { + paths = appendElement(paths, element); } + return paths; } -function assertDisjointFollowingQuantifiers( - elements: AST.Alternative['elements'], - index: number, - first: AST.Quantifier, -): void { - for (let next = index + 1; next < elements.length; next += 1) { - const element = elements[next]; - if (!element) break; - if (element.type === 'Assertion') { - assertSafeAssertion(element); - continue; - } - if (element.type === 'Group' || element.type === 'CapturingGroup') unsafeMaestroRegex(); - if (element?.type === 'Quantifier') { - assertSafeFollowingQuantifier(first, element); - if (element.min === 0) continue; +function appendElement(paths: RegexElement[][], element: RegexElement): RegexElement[][] { + const isGroup = element.type === 'Group' || element.type === 'CapturingGroup'; + const branches = isGroup + ? element.alternatives.flatMap((alternative) => expandedPaths(alternative.elements)) + : [[element]]; + const next: RegexElement[][] = []; + for (const prefix of paths) { + for (const branch of branches) { + if (isGroup) assertSafeGroupAfterQuantifier(prefix.at(-1), branch); + next.push([...prefix, ...branch]); + if (next.length > MAX_PATTERN_PATHS) unsafeMaestroRegex(); } - break; } + return next; } -function assertSafeAssertion(element: AST.Assertion): void { - if ('alternatives' in element) unsafeMaestroRegex(); +function assertSafeGroupAfterQuantifier( + previous: RegexElement | undefined, + branch: RegexElement[], +) { + if (previous?.type !== 'Quantifier' || previous.max === previous.min) return; + const first = branch.find((element) => element.type !== 'Assertion'); + if (!first || (first.type === 'Quantifier' && first.min === 0)) unsafeMaestroRegex(); + const atom = first.type === 'Quantifier' ? first.element : first; + if (!quantifiedAtomsAreDisjoint(previous.element, atom)) unsafeMaestroRegex(); } -function assertSafeFollowingQuantifier(first: AST.Quantifier, later: AST.Quantifier): void { - if (later.max > later.min && !quantifiedAtomsAreDisjoint(first.element, later.element)) { - unsafeMaestroRegex(); +function assertDisjointQuantifiers(path: RegexElement[]): void { + const quantifiers = path.flatMap((element, index) => + element.type === 'Quantifier' && element.max > element.min ? [{ element, index }] : [], + ); + for (let left = 0; left < quantifiers.length; left += 1) { + for (let right = left + 1; right < quantifiers.length; right += 1) { + const later = quantifiers[right]!; + if (later.index === path.length - 1 && isTrailingWildcard(later.element)) continue; + if (!quantifiedAtomsAreDisjoint(quantifiers[left]!.element.element, later.element.element)) { + unsafeMaestroRegex(); + } + } } } +function isTrailingWildcard(quantifier: AST.Quantifier): boolean { + return quantifier.element.raw === '.' && quantifier.max === Infinity && quantifier.min <= 1; +} + function quantifiedAtomsAreDisjoint( left: AST.QuantifiableElement, right: AST.QuantifiableElement, ): boolean { - if (left.type === 'Character' && right.type === 'Character') { - return ( - String.fromCodePoint(left.value).toLocaleLowerCase() !== - String.fromCodePoint(right.value).toLocaleLowerCase() - ); + if ( + left.type === 'Group' || + left.type === 'CapturingGroup' || + right.type === 'Group' || + right.type === 'CapturingGroup' + ) { + return false; } - return ( - (left.raw === String.raw`\d` && right.raw === String.raw`\s`) || - (left.raw === String.raw`\s` && right.raw === String.raw`\d`) - ); + if (!isAsciiOnly(left) && !isAsciiOnly(right)) return false; + 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 false; + } + return true; +} + +function isAsciiOnly(element: AST.QuantifiableElement): boolean { + if (element.type === 'Character') return element.value < 128; + if (element.type === 'CharacterSet') { + return !element.negate && (element.kind === 'digit' || element.kind === 'word'); + } + 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 { diff --git a/website/docs/docs/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index 8fa65f93505..4cfd8eb73b7 100644 --- a/website/docs/docs/run-maestro-flows.md +++ b/website/docs/docs/run-maestro-flows.md @@ -30,7 +30,7 @@ Keep the target binding, such as `--platform ios`, on the `replay` or `test` com ## Boundaries -- Selector `id` and `text` match exact text before interpreting a safe pattern as a regular expression. Regex patterns can use groups, alternatives, character classes, and counted or disjoint repetitions. Backreferences, overlapping repetitions, quantified groups with alternatives or repetitions, excessive ambiguous groups, and regex patterns over 256 characters fail with `maestro_selector_regex_unsafe`. A regex against a node value over 8192 characters does not match; exact literal text matching remains available. These limits keep matching bounded. +- Selector `id` and `text` match exact text before interpreting a safe pattern as a regular expression. A plain literal also matches one line of a multiline value. Regex patterns can use groups, alternatives, character classes, and counted or disjoint repetitions. Backreferences, overlapping repetitions across literals or groups, quantified groups with alternatives or repetitions, excessive ambiguous groups, and regex patterns over 256 characters fail with `maestro_selector_regex_unsafe`. These limits keep matching bounded while allowing full device text values. - 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 251351fb86c8d858be02d1356ceb40679bf9470f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 23:40:02 +0100 Subject: [PATCH 34/55] fix(maestro): refuse indeterminate partial multiline selector matches --- .../runtime-selector-resolution.test.ts | 14 +++ .../internal/__tests__/selector-regex.test.ts | 19 ++++ .../maestro/src/internal/selector-regex.ts | 88 +++++++++++++++++-- website/docs/docs/error-reasons.md | 1 + website/docs/docs/run-maestro-flows.md | 2 +- 5 files changed, 114 insertions(+), 10 deletions(-) diff --git a/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts b/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts index acec5e12a9e..2add1b7953c 100644 --- a/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts +++ b/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts @@ -55,6 +55,20 @@ test('rejects cyclic selector graphs explicitly', () => { expect(() => resolver.resolve(selector)).toThrow(/cannot contain cycles/); }); +test('refuses uncertain multiline regex candidates before ordered target selection', () => { + const snapshot = makeSnapshot([ + { index: 0, label: 'prefix\nstart\nmiddle\nend\nsuffix' }, + { index: 1, label: 'start\nend' }, + ]); + const resolver = createMaestroSnapshotResolver(snapshot); + + expect(() => resolver.resolve({ text: 'start.*end', index: 0 })).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); +}); + test('resolves containment through array-offset parent links with non-contiguous indexes', () => { const snapshot = makeSnapshot([ { index: 10, identifier: 'container' }, diff --git a/packages/maestro/src/internal/__tests__/selector-regex.test.ts b/packages/maestro/src/internal/__tests__/selector-regex.test.ts index ec2679d9e07..68d2229e30b 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -31,6 +31,8 @@ test.each([ '.*a.*a.*a.*b', '(a*)(a*)b', '(?:aa)+a+b', + 'a{10001}', + 'a{10001,}', 'a+(?:|a)a+b', 'a+(?=a)a+b', 'a+(?:a*)b', @@ -87,6 +89,23 @@ test('long device labels retain literal and bounded regex matches', () => { expect(matchesMaestroRegex('item', 'item')).toBe(true); }); +test('multiline regex matches whole values and individual lines without retrying every suffix', () => { + expect(matchesMaestroRegex('start\nmiddle\nend', 'start.*end')).toBe(true); + expect(matchesMaestroRegex('before\nReady\nafter', 'Ready')).toBe(true); + expect(matchesMaestroRegex('before\nReady\nafter', '.*Ready.*')).toBe(true); + expect(matchesMaestroRegex('a\n'.repeat(192_000), 'a+Z')).toBe(false); + expect(() => matchesMaestroRegex('a\n'.repeat(192_000), '.*Z')).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); + expect(() => matchesMaestroRegex('prefix\nstart\nmiddle\nend\nsuffix', 'start.*end')).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); +}); + test('escaped brackets and braces match literal node text', () => { expect(matchesMaestroRegex('a(b', String.raw`a\(b`)).toBe(true); expect(matchesMaestroRegex('price {2}', String.raw`price \{2\}`)).toBe(true); diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index 774873c0ebd..e46814958bc 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -5,23 +5,30 @@ import { normalizeText } from './shared.ts'; const MAESTRO_SELECTOR_REGEX_REASONS = { // The selector pattern uses constructs that the bounded matcher cannot safely execute. unsafe: { reason: 'maestro_selector_regex_unsafe' }, + // A multiline value might match across partial lines, so absence cannot be confirmed safely. + indeterminate: { reason: 'maestro_selector_regex_indeterminate' }, } as const satisfies ReasonTable<'maestro selector regex'>; const REGEX_SYNTAX = new Set(String.raw`^$\.*+?()[]{}|`); const MAX_PATTERN_LENGTH = 256; +const MAX_COUNTED_REPETITION = 10_000; const MAX_CACHED_PATTERNS = 128; const MAX_PATTERN_PATHS = 32; const parser = new RegExpParser(); type RegexElement = AST.Alternative['elements'][number]; type LiteralMatcher = { literal: string; lineRegex?: RegExp }; -type Matcher = LiteralMatcher | { regex: RegExp }; +type Matcher = LiteralMatcher | { regex: RegExp; canSpanLines: boolean }; const matcherCache = new Map(); export function matchesMaestroRegex(value: string, pattern: string): boolean { const matcher = matcherForPattern(pattern); if ('literal' in matcher) return matchesLiteral(value, matcher); if (normalizeText(value) === normalizeText(pattern)) return true; - return matcher.regex.test(value); + if (matcher.regex.test(value)) return true; + if (!hasLineTerminator(value)) return false; + if (matchesAnyLine(value, matcher.regex)) return true; + if (matcher.canSpanLines) indeterminateMaestroRegex(); + return false; } function matchesLiteral(value: string, matcher: LiteralMatcher): boolean { @@ -39,20 +46,53 @@ function matchesLiteral(value: string, matcher: LiteralMatcher): boolean { function matchesLongLiteralLine(value: string, literal: string): boolean { const text = value.toLowerCase(); const query = literal.toLowerCase(); - for (let index = text.indexOf(query); index >= 0; index = text.indexOf(query, index + 1)) { - const before = index === 0 || isLineTerminator(text[index - 1]); - const after = index + query.length; - if (before && (after === text.length || isLineTerminator(text[after]))) return true; + const fallbacks = literalPrefixFallbacks(query); + let matched = 0; + for (let index = 0; index < text.length; index += 1) { + while (matched > 0 && text[index] !== query[matched]) matched = fallbacks[matched - 1]!; + if (text[index] === query[matched]) matched += 1; + if (matched !== query.length) continue; + const start = index + 1 - matched; + const before = start === 0 || isLineTerminator(text[start - 1]); + const after = index + 1 === text.length || isLineTerminator(text[index + 1]); + if (before && after) return true; + matched = fallbacks[matched - 1]!; } return false; } +function literalPrefixFallbacks(query: string): Uint32Array { + const fallbacks = new Uint32Array(query.length); + let matched = 0; + for (let index = 1; index < query.length; index += 1) { + while (matched > 0 && query[index] !== query[matched]) matched = fallbacks[matched - 1]!; + if (query[index] === query[matched]) matched += 1; + fallbacks[index] = matched; + } + return fallbacks; +} + function isLineTerminator(character: string | undefined): boolean { return ( character === '\n' || character === '\r' || character === '\u2028' || character === '\u2029' ); } +function hasLineTerminator(value: string): boolean { + return /[\n\r\u2028\u2029]/.test(value); +} + +function matchesAnyLine(value: string, regex: RegExp): boolean { + let start = 0; + for (let index = 0; index < value.length; index += 1) { + if (!isLineTerminator(value[index])) continue; + if (regex.test(value.slice(start, index))) return true; + if (value[index] === '\r' && value[index + 1] === '\n') index += 1; + start = index + 1; + } + return regex.test(value.slice(start)); +} + function matcherForPattern(pattern: string): Matcher { const cached = matcherCache.get(pattern); if (cached) return cached; @@ -62,9 +102,9 @@ function matcherForPattern(pattern: string): Matcher { matcher = { literal }; } else { if (pattern.length > MAX_PATTERN_LENGTH) unsafeMaestroRegex(); - assertBoundedMaestroPattern(pattern); + const canSpanLines = assertBoundedMaestroPattern(pattern); try { - matcher = { regex: new RegExp(`^(?:${pattern})$`, 'ims') }; + matcher = { regex: new RegExp(`^(?:${pattern})$`, 'is'), canSpanLines }; } catch { unsafeMaestroRegex(); } @@ -76,7 +116,7 @@ function matcherForPattern(pattern: string): Matcher { return matcher; } -function assertBoundedMaestroPattern(pattern: string): void { +function assertBoundedMaestroPattern(pattern: string): boolean { let parsed: AST.Pattern; try { parsed = parser.parsePattern(pattern); @@ -99,6 +139,12 @@ function assertBoundedMaestroPattern(pattern: string): void { countAlternatives(node.alternatives.length); }, onQuantifierEnter(node) { + if ( + node.min > MAX_COUNTED_REPETITION || + (Number.isFinite(node.max) && node.max > MAX_COUNTED_REPETITION) + ) { + unsafeMaestroRegex(); + } if (node.element.type !== 'Group' && node.element.type !== 'CapturingGroup') return; if (node.element.alternatives.length > 1) unsafeMaestroRegex(); visitRegExpAST(node.element, { onQuantifierEnter: unsafeMaestroRegex }); @@ -107,6 +153,19 @@ function assertBoundedMaestroPattern(pattern: string): void { for (const alternative of parsed.alternatives) { for (const path of expandedPaths(alternative.elements)) assertDisjointQuantifiers(path); } + return parsed.alternatives.some((alternative) => alternative.elements.some(elementCanSpanLines)); +} + +function elementCanSpanLines(element: RegexElement): boolean { + if (element.type === 'Assertion') return false; + if (element.type === 'Quantifier') return elementCanSpanLines(element.element); + if (element.type === 'Group' || element.type === 'CapturingGroup') { + return element.alternatives.some((alternative) => + alternative.elements.some(elementCanSpanLines), + ); + } + const atom = new RegExp(`^(?:${element.raw})$`, 'is'); + return ['\n', '\r', '\u2028', '\u2029'].some((character) => atom.test(character)); } function expandedPaths(elements: AST.Alternative['elements']): RegexElement[][] { @@ -205,6 +264,17 @@ function unsafeMaestroRegex(): never { }); } +function indeterminateMaestroRegex(): never { + throw new AppError( + 'UNSUPPORTED_OPERATION', + 'Maestro selector cannot safely decide a multiline match.', + { + reason: MAESTRO_SELECTOR_REGEX_REASONS.indeterminate.reason, + retriable: false, + }, + ); +} + export function literalFromMaestroRegex(pattern: string): string | undefined { if (pattern.length > MAX_PATTERN_LENGTH) { return hasRegexSyntax(pattern) ? undefined : pattern; diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 075d6b707f6..d294e026249 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -878,6 +878,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | | `maestro_selector_regex_unsafe` | The selector pattern uses constructs that the bounded matcher cannot safely execute. | +| `maestro_selector_regex_indeterminate` | A multiline value might match across partial lines, so absence cannot be confirmed safely. | ### Metro reload diff --git a/website/docs/docs/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index 4cfd8eb73b7..12bda615194 100644 --- a/website/docs/docs/run-maestro-flows.md +++ b/website/docs/docs/run-maestro-flows.md @@ -30,7 +30,7 @@ Keep the target binding, such as `--platform ios`, on the `replay` or `test` com ## Boundaries -- Selector `id` and `text` match exact text before interpreting a safe pattern as a regular expression. A plain literal also matches one line of a multiline value. Regex patterns can use groups, alternatives, character classes, and counted or disjoint repetitions. Backreferences, overlapping repetitions across literals or groups, quantified groups with alternatives or repetitions, excessive ambiguous groups, and regex patterns over 256 characters fail with `maestro_selector_regex_unsafe`. These limits keep matching bounded while allowing full device text values. +- Selector `id` and `text` match exact text before interpreting a safe pattern as a regular expression. A plain literal also matches one line of a multiline value. Regex patterns match a whole value or one line and can use groups, alternatives, character classes, and counted or disjoint repetitions. Backreferences, overlapping repetitions across literals or groups, quantified groups with alternatives or repetitions, excessive ambiguous groups, counted repetitions over 10,000, and regex patterns over 256 characters fail with `maestro_selector_regex_unsafe`. If a pattern could span lines but neither the whole value nor one line matches, the step fails with `maestro_selector_regex_indeterminate` rather than treating a possible partial cross-line match as absent. - 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 11aba647d31d6b1e6c5dcea8789f49697a9d76ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 23:36:35 +0100 Subject: [PATCH 35/55] fix(remote): bind capture destinations to live capture identity --- docs/agents/security.md | 9 +- .../src/core/session-capture-binding.ts | 3 +- packages/daemon/src/core/session-state.ts | 2 + .../handlers/__tests__/trace-runtime.test.ts | 41 ++- .../src/sessions/handlers/trace-runtime.ts | 28 ++- .../__tests__/session-perf-runtime.test.ts | 22 +- .../internal/session-perf-runtime.ts | 25 +- packages/kernel/src/contracts.ts | 2 + packages/kernel/src/errors.ts | 6 + .../capture-destination-record.test.ts | 237 ++++++++++++++++-- .../remote/src/capture-destination-record.ts | 154 ++++++++---- packages/remote/src/daemon-artifacts.ts | 3 +- 12 files changed, 456 insertions(+), 76 deletions(-) diff --git a/docs/agents/security.md b/docs/agents/security.md index 89c6c2b19f5..6c5c719c9ac 100644 --- a/docs/agents/security.md +++ b/docs/agents/security.md @@ -3,7 +3,14 @@ The CLI client owns local destinations; it trusts a remote daemon only for data and validated IDs. Scripts and remote record stops reject daemon-chosen paths (#4518). Remote trace/perf uses caller paths. Unnamed captures get unique client cwd names. -For remote trace/native perf, key start paths by endpoint, tenant, run, lease, session, and kind. Before each start, invalidate the old path. A pathless stop uses only that record; a successful stop retires it before download. +For remote trace/native perf, key start paths by endpoint, tenant, run, lease, session, and kind. +Before each start, mark the new capture pending and keep the last confirmed destination. +If the daemon rejects a repeated start and names the same capture ID, restore the confirmed destination. +If a start has no clear outcome, do not use the confirmed destination for a pathless stop. +For a pathless stop, require the daemon to match the client capture ID before it stops the capture. +Before a remote download, require the stop response to confirm that ID and read the destination from client state. +If the daemon does not confirm the ID, use a unique client cwd name. +After a successful full close or stop, retire the confirmed destination. The daemon admits its state directory. Nobody trusts the network or other local users. Out of scope: same uid, hostile root, ACLs, mounts, untrusted filesystems. ADR 0041 owns credential transport. diff --git a/packages/daemon/src/core/session-capture-binding.ts b/packages/daemon/src/core/session-capture-binding.ts index 79a809d6512..4b84035e171 100644 --- a/packages/daemon/src/core/session-capture-binding.ts +++ b/packages/daemon/src/core/session-capture-binding.ts @@ -39,12 +39,13 @@ export function bindSessionPerfCapture( sessionStore: SessionStore, ref: SessionRef, clientOutPath?: string, + clientCaptureId?: string, ) { return bindSessionCapture(sessionStore, ref, { read: (session) => session.perfCapture, write: (perfCapture) => { sessionStore.update(ref, { - perfCapture: perfCapture ? { ...perfCapture, clientOutPath } : undefined, + perfCapture: perfCapture ? { ...perfCapture, clientOutPath, clientCaptureId } : undefined, }); }, }); diff --git a/packages/daemon/src/core/session-state.ts b/packages/daemon/src/core/session-state.ts index 0a12367c0e7..aef1385b1e2 100644 --- a/packages/daemon/src/core/session-state.ts +++ b/packages/daemon/src/core/session-state.ts @@ -224,6 +224,7 @@ export type SessionState = { snapshotDiagnostics?: SnapshotDiagnosticsState; trace?: { outPath: string; + clientCaptureId?: string; clientOutPath?: string; remoteCaptureOutputPath?: string; remoteCaptureTenantId?: string; @@ -231,6 +232,7 @@ export type SessionState = { }; /** Native profiling mechanics stay behind one exact-owner durable handle. */ perfCapture?: { + clientCaptureId?: string; clientOutPath?: string; handle: PerfNativeCaptureLiveHandle; envelope: DurableResourceEnvelope<'perf-capture'>; diff --git a/packages/daemon/src/sessions/handlers/__tests__/trace-runtime.test.ts b/packages/daemon/src/sessions/handlers/__tests__/trace-runtime.test.ts index 95db10173f2..99ea84bcd7f 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/trace-runtime.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/trace-runtime.test.ts @@ -36,14 +36,21 @@ function fixture() { return { root, session, sessionStore }; } -function request(positionals: string[], clientOutPath?: string): DaemonRequest { +function request(positionals: string[], clientOutPath?: string, captureId?: string): DaemonRequest { return { token: 'token', session: 'trace-session', command: 'trace', positionals, flags: {}, - ...(clientOutPath ? { meta: { clientArtifactPaths: { outPath: clientOutPath } } } : {}), + ...(clientOutPath || captureId + ? { + meta: { + ...(clientOutPath ? { clientArtifactPaths: { outPath: clientOutPath } } : {}), + ...(captureId ? { captureId } : {}), + }, + } + : {}), }; } @@ -69,6 +76,36 @@ test('starts and stops one trace through the session-owned trace slot', () => { expect(session.trace).toBeUndefined(); }); +test('a stale client capture identity cannot stop a reopened trace', () => { + const { session, sessionStore } = fixture(); + const host = createTestHostEnvironment(); + const started = handleTraceCommand({ + host, + req: request(['start'], undefined, 'capture-b'), + sessionName: session.name, + sessionStore, + }); + expect(started).toMatchObject({ ok: true, data: { clientCaptureId: 'capture-b' } }); + const stale = handleTraceCommand({ + host, + req: request(['stop'], undefined, 'capture-a'), + sessionName: session.name, + sessionStore, + }); + expect(stale).toMatchObject({ + ok: false, + error: { details: { reason: 'capture-identity-mismatch' } }, + }); + expect(session.trace).toBeDefined(); + const stopped = handleTraceCommand({ + host, + req: request(['stop'], undefined, 'capture-b'), + sessionName: session.name, + sessionStore, + }); + expect(stopped).toMatchObject({ ok: true, data: { clientCaptureId: 'capture-b' } }); +}); + test('relocates trace output and projects the client artifact path', () => { const { root, session, sessionStore } = fixture(); const original = path.join(root, 'original.trace'); diff --git a/packages/daemon/src/sessions/handlers/trace-runtime.ts b/packages/daemon/src/sessions/handlers/trace-runtime.ts index 556240ea0b3..cefd28ce593 100644 --- a/packages/daemon/src/sessions/handlers/trace-runtime.ts +++ b/packages/daemon/src/sessions/handlers/trace-runtime.ts @@ -1,13 +1,10 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; +import { CAPTURE_IDENTITY_REASONS } from '@agent-device/kernel/errors'; import { expandSessionPath } from '@agent-device/host-kit/session-paths'; import fs from 'node:fs'; import path from 'node:path'; -import { - parseTraceAction, - TRACE_ACTION_REQUIRED_MESSAGE, - type TraceCommandResult, -} from '@agent-device/contracts/recording'; +import { parseTraceAction, TRACE_ACTION_REQUIRED_MESSAGE } from '@agent-device/contracts/recording'; import type { SessionStore } from '../../core/session-store.ts'; import type { DaemonRequest } from '../../core/daemon-request.ts'; import { requestCwd } from '../../core/context.ts'; @@ -38,7 +35,11 @@ function startTrace( ref: SessionRef, ): DaemonResponse { const session = sessionStore.requireCurrent(ref); - if (session.trace) return errorResponse('INVALID_ARGS', 'trace already in progress'); + if (session.trace) + return errorResponse('INVALID_ARGS', 'trace already in progress', { + reason: CAPTURE_IDENTITY_REASONS.alreadyActive.reason, + clientCaptureId: session.trace.clientCaptureId, + }); const outPath = expandSessionPath( req.positionals?.[1] ?? sessionStore.defaultTracePath(session), requestCwd(req, host), @@ -47,6 +48,7 @@ function startTrace( fs.appendFileSync(outPath, ''); session.trace = { outPath, + clientCaptureId: req.meta?.captureId, startedAt: Date.now(), clientOutPath: req.meta?.clientArtifactPaths?.outPath, ...(req.internal?.publicNetworkOnly ? { remoteCaptureOutputPath: outPath } : {}), @@ -55,7 +57,11 @@ function startTrace( recordSessionAction(sessionStore, ref, req, req.command, { action: 'start', outPath }); return { ok: true, - data: { trace: 'started', outPath } satisfies TraceCommandResult, + data: { + trace: 'started', + outPath, + ...(req.meta?.captureId ? { clientCaptureId: req.meta.captureId } : {}), + }, }; } @@ -67,6 +73,11 @@ function stopTrace( ): DaemonResponse { const session = sessionStore.requireCurrent(ref); if (!session.trace) return errorResponse('INVALID_ARGS', 'no active trace'); + if (req.meta?.captureId && req.meta.captureId !== session.trace.clientCaptureId) + return errorResponse('INVALID_ARGS', 'trace capture identity changed', { + reason: CAPTURE_IDENTITY_REASONS.mismatch.reason, + }); + const clientCaptureId = session.trace.clientCaptureId; const outPath = relocateTraceOutput( requestCwd(req, host), session.trace.outPath, @@ -86,6 +97,7 @@ function stopTrace( { trace: 'stopped', outPath, + ...(clientCaptureId ? { clientCaptureId } : {}), artifacts: [ { field: 'outPath', @@ -95,7 +107,7 @@ function stopTrace( fileName: path.basename(clientOutPath ?? outPath), }, ], - } satisfies TraceCommandResult, + }, daemonOwned ? 'daemon' : 'caller', tenantId, ), diff --git a/packages/daemon/src/sessions/session-observability/internal/__tests__/session-perf-runtime.test.ts b/packages/daemon/src/sessions/session-observability/internal/__tests__/session-perf-runtime.test.ts index 45328d8b8ce..189e91b2b4f 100644 --- a/packages/daemon/src/sessions/session-observability/internal/__tests__/session-perf-runtime.test.ts +++ b/packages/daemon/src/sessions/session-observability/internal/__tests__/session-perf-runtime.test.ts @@ -211,10 +211,11 @@ test('perf native capture is adopted durably and stop uses the live handle witho command: 'perf', positionals: ['trace', 'start', 'xctrace'], flags: { out: '/tmp/app.trace' }, - meta: { clientArtifactPaths: { outPath: '/client/app.trace' } }, + meta: { clientArtifactPaths: { outPath: '/client/app.trace' }, captureId: 'capture-b' }, }, }); assert.equal(startResponse?.ok, true, JSON.stringify(startResponse)); + assert.equal(startResponse?.data?.clientCaptureId, 'capture-b'); assert.ok(sessionStore.get('android')?.perfCapture); assert.deepEqual( sessionStore.get('android')?.actions.map(({ command }) => command), @@ -243,6 +244,23 @@ test('perf native capture is adopted durably and stop uses the live handle witho assert.ok(sessionStore.get('android')?.perfCapture); assert.equal(sessionStore.get('android')?.actions.length, 1); + const staleStop = await handleSessionObservabilityCommands({ + host: createTestHostEnvironment(), + platformServices: daemonPlatformServicesFixture(), + ...common, + req: { + token: 't', + session: 'android', + command: 'perf', + positionals: ['trace', 'stop', 'xctrace'], + meta: { captureId: 'capture-a' }, + }, + }); + assert.equal(staleStop?.ok, false); + if (staleStop && !staleStop.ok) + assert.equal(staleStop.error.details?.reason, 'capture-identity-mismatch'); + assert.equal(finish.mock.calls.length, 0); + const stopResponse = await handleSessionObservabilityCommands({ host: createTestHostEnvironment(), platformServices: daemonPlatformServicesFixture(), @@ -252,10 +270,12 @@ test('perf native capture is adopted durably and stop uses the live handle witho session: 'android', command: 'perf', positionals: ['trace', 'stop', 'xctrace'], + meta: { captureId: 'capture-b' }, }, }); assert.equal(stopResponse?.ok, true, JSON.stringify(stopResponse)); if (stopResponse?.ok) assert.equal(stopResponse.data?.clientOutPath, '/client/app.trace'); + if (stopResponse?.ok) assert.equal(stopResponse.data?.clientCaptureId, 'capture-b'); assert.equal(finish.mock.calls.length, 1); assert.deepEqual(runtime.uses, [['perfNativeCaptureStart']]); assert.equal(sessionStore.get('android')?.perfCapture, undefined); diff --git a/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts b/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts index 789baa32175..9c91931b96e 100644 --- a/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts +++ b/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts @@ -1,5 +1,6 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; +import { CAPTURE_IDENTITY_REASONS } from '@agent-device/kernel/errors'; import { expandSessionPath } from '@agent-device/host-kit/session-paths'; import path from 'node:path'; import { type PerfCaptureAdmissionLedger } from '@agent-device/capture-kit/perf-capture-admission-ledger'; @@ -215,7 +216,10 @@ async function startPerfCapture( request: Extract, ): Promise { if (session.perfCapture) { - return errorResponse('INVALID_ARGS', 'native perf capture already in progress'); + return errorResponse('INVALID_ARGS', 'native perf capture already in progress', { + reason: CAPTURE_IDENTITY_REASONS.alreadyActive.reason, + clientCaptureId: session.perfCapture.clientCaptureId, + }); } if (!session.appBundleId) { return errorResponse('COMMAND_FAILED', 'No app is associated with this session.', { @@ -241,6 +245,7 @@ async function startPerfCapture( params.sessionStore, params.ref, params.req.meta?.clientArtifactPaths?.outPath, + params.req.meta?.captureId, ); binding.assertAdoptable(); const started = await runtime.operations.perfNativeCaptureStart({ @@ -272,7 +277,13 @@ async function startPerfCapture( : started.envelope, throwIfCanceled: params.throwIfCanceled, }); - return { ok: true, data: started.response }; + return { + ok: true, + data: { + ...started.response, + ...(params.req.meta?.captureId ? { clientCaptureId: params.req.meta.captureId } : {}), + }, + }; } function requirePerfCaptureAdmissionLedger( @@ -291,6 +302,10 @@ async function stopPerfCapture( ): Promise { const capture = session.perfCapture; if (!capture) return errorResponse('INVALID_ARGS', 'no active native perf capture'); + if (params.req.meta?.captureId && params.req.meta.captureId !== capture.clientCaptureId) + return errorResponse('INVALID_ARGS', 'native perf capture identity changed', { + reason: CAPTURE_IDENTITY_REASONS.mismatch.reason, + }); const snapshot = capture.handle.inspect(); const mismatchMessage = perfCaptureStopMismatch(snapshot, request); if (mismatchMessage) return errorResponse('INVALID_ARGS', mismatchMessage); @@ -315,7 +330,11 @@ async function stopPerfCapture( return { ok: true, data: withCaptureOutputOwnership( - { ...completion, ...(clientOutPath ? { clientOutPath } : {}) }, + { + ...completion, + ...(clientOutPath ? { clientOutPath } : {}), + ...(capture.clientCaptureId ? { clientCaptureId: capture.clientCaptureId } : {}), + }, capture.envelope.metadata?.remoteCaptureOutputPath === completion.outPath ? 'daemon' : 'caller', diff --git a/packages/kernel/src/contracts.ts b/packages/kernel/src/contracts.ts index a60e6774590..f3f6619c621 100644 --- a/packages/kernel/src/contracts.ts +++ b/packages/kernel/src/contracts.ts @@ -138,6 +138,8 @@ export type DaemonRequestMeta = { sessionIsolation?: SessionIsolationMode; uploadedArtifactId?: string; clientArtifactPaths?: Record; + /** Opaque caller capture identity; older daemons may ignore it. */ + captureId?: string; /** The ID a remote client minted for its `open --save-script`; each script version carries it. */ scriptPublicationId?: string; installSource?: DaemonInstallSource; diff --git a/packages/kernel/src/errors.ts b/packages/kernel/src/errors.ts index 6b820574013..85b69ce491b 100644 --- a/packages/kernel/src/errors.ts +++ b/packages/kernel/src/errors.ts @@ -496,6 +496,12 @@ export const DURABLE_RESOURCE_REASONS = { transportNotReattachable: { reason: 'transport-not-reattachable' }, } as const satisfies ReasonTable<'durable captures'>; +/** Refusals that identify the live trace or native perf capture without trusting an output path. */ +export const CAPTURE_IDENTITY_REASONS = { + alreadyActive: { reason: 'capture-already-active' }, + mismatch: { reason: 'capture-identity-mismatch' }, +} as const satisfies ReasonTable<'capture identity'>; + const REQUEST_CANCELED_HINT = 'The request was canceled intentionally (explicit cancel or client disconnect) — no retry is needed unless the cancellation was unintended.'; diff --git a/packages/remote/src/__tests__/capture-destination-record.test.ts b/packages/remote/src/__tests__/capture-destination-record.test.ts index 4f16409c1e6..f300e7a0e68 100644 --- a/packages/remote/src/__tests__/capture-destination-record.test.ts +++ b/packages/remote/src/__tests__/capture-destination-record.test.ts @@ -1,11 +1,19 @@ import { test, expect } from 'vitest'; import { createTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; import type { DaemonWireRequest } from '@agent-device/contracts/command'; -import { sendRemoteCapture, retireSuccessfulCaptureStop } from '../capture-destination-record.ts'; +import { + confirmedCaptureStopRequest, + sendRemoteCapture, + retireSuccessfulCaptureStop, +} from '../capture-destination-record.ts'; import { materializeRemoteArtifacts } from '../daemon-artifacts.ts'; const endpoint = 'https://capture.example.test/api'; const success = { ok: true as const, data: {} }; +const confirmed = (req: DaemonWireRequest) => ({ + ok: true as const, + data: { clientCaptureId: req.meta?.captureId }, +}); function request( action: 'start' | 'stop', @@ -43,7 +51,7 @@ test.each(['trace', 'perf'] as const)( endpoint, request('start', destination, { family }), stateDir, - async () => success, + async (req) => confirmed(req), ); const sent: DaemonWireRequest[] = []; await sendRemoteCapture( @@ -52,17 +60,22 @@ test.each(['trace', 'perf'] as const)( stateDir, async (req) => { sent.push(req); + const answer = confirmed(req); + expect( + (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + ).toBe(destination); await materializeRemoteArtifacts( { baseUrl: endpoint, token: 'test' }, req, - success, + answer, createTestHostEnvironment(), stateDir, ); - return success; + return answer; }, ); - expect(sent[0]?.meta?.clientArtifactPaths?.outPath).toBe(destination); + expect(sent[0]?.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + expect(sent[0]?.meta?.captureId).toBeTypeOf('string'); await sendRemoteCapture( endpoint, request('stop', undefined, { family }), @@ -78,18 +91,15 @@ test.each(['trace', 'perf'] as const)( test('a pathless new start invalidates an older destination before dispatch', async () => { const stateDir = mkdtempForTestSync('capture-destination-'); - await sendRemoteCapture( - endpoint, - request('start', '/client/old.trace'), - stateDir, - async () => success, + await sendRemoteCapture(endpoint, request('start', '/client/old.trace'), stateDir, async (req) => + confirmed(req), ); - await sendRemoteCapture(endpoint, request('start'), stateDir, async () => { + await sendRemoteCapture(endpoint, request('start'), stateDir, async (start) => { await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); return success; }); - return success; + return confirmed(start); }); await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); @@ -105,7 +115,7 @@ test.each(['returned', 'thrown'] as const)( endpoint, request('start', '/client/old.trace'), stateDir, - async () => success, + async (req) => confirmed(req), ); const start = sendRemoteCapture(endpoint, request('start'), stateDir, async () => { if (failure === 'thrown') throw { details: { dispatched: 'no' } }; @@ -124,13 +134,203 @@ test.each(['returned', 'thrown'] as const)( }, ); +test.each(['trace', 'perf'] as const)( + '%s rejected repeat start preserves the confirmed destination', + async (family) => { + const stateDir = mkdtempForTestSync('capture-destination-'); + let firstCaptureId: string | undefined; + await sendRemoteCapture( + endpoint, + request('start', '/client/first.trace', { family }), + stateDir, + async (req) => { + firstCaptureId = req.meta?.captureId; + return confirmed(req); + }, + ); + const refused = await sendRemoteCapture( + endpoint, + request('start', '/client/second.trace', { family }), + stateDir, + async () => ({ + ok: false, + error: { + code: 'INVALID_ARGS', + message: 'capture already active', + details: { reason: 'capture-already-active', clientCaptureId: firstCaptureId }, + }, + }), + ); + expect(refused.ok).toBe(false); + await sendRemoteCapture( + endpoint, + request('stop', undefined, { family }), + stateDir, + async (req) => { + const answer = confirmed(req); + expect( + (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + ).toBe('/client/first.trace'); + return answer; + }, + ); + }, +); + +test('a concurrent rejected start does not discard a newly confirmed start', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + let releaseFirst!: () => void; + const firstReachedDaemon = new Promise((resolve) => (releaseFirst = resolve)); + let finishFirst!: () => void; + const firstCanFinish = new Promise((resolve) => (finishFirst = resolve)); + const first = sendRemoteCapture( + endpoint, + request('start', '/client/first.trace'), + stateDir, + async (req) => { + releaseFirst(); + await firstCanFinish; + return confirmed(req); + }, + ); + await firstReachedDaemon; + const second = sendRemoteCapture( + endpoint, + request('start', '/client/second.trace'), + stateDir, + async () => ({ + ok: false, + error: { + code: 'INVALID_ARGS', + message: 'capture already active', + details: { reason: 'capture-already-active' }, + }, + }), + ); + await second; + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }); + finishFirst(); + await first; + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + const answer = confirmed(req); + expect( + (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + ).toBe('/client/first.trace'); + return answer; + }); +}); + +test('successful close retires destinations before the same session address is reused', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture(endpoint, request('start', '/client/old.trace'), stateDir, async (req) => + confirmed(req), + ); + await sendRemoteCapture( + endpoint, + { ...request('stop'), command: 'close', positionals: [] }, + stateDir, + async (req) => confirmed(req), + ); + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }); +}); + +test('failed close leaves the confirmed destination for a retry', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture(endpoint, request('start', '/client/old.trace'), stateDir, async (req) => + confirmed(req), + ); + await sendRemoteCapture( + endpoint, + { ...request('stop'), command: 'close', positionals: [] }, + stateDir, + async () => ({ ok: false, error: { code: 'COMMAND_FAILED', message: 'close failed' } }), + ); + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + const answer = confirmed(req); + expect( + (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + ).toBe('/client/old.trace'); + return answer; + }); +}); + +test('a different client can reuse the session name without authorizing the old destination', async () => { + const firstStateDir = mkdtempForTestSync('capture-destination-a-'); + const secondStateDir = mkdtempForTestSync('capture-destination-b-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/a.trace'), + firstStateDir, + async (req) => confirmed(req), + ); + await sendRemoteCapture( + endpoint, + { ...request('stop'), command: 'close', positionals: [] }, + secondStateDir, + async () => success, + ); + let secondCaptureId: string | undefined; + await sendRemoteCapture( + endpoint, + request('start', '/client/b.trace'), + secondStateDir, + async (req) => { + secondCaptureId = req.meta?.captureId; + return confirmed(req); + }, + ); + const oldStop = await sendRemoteCapture(endpoint, request('stop'), firstStateDir, async (req) => { + expect(req.meta?.captureId).not.toBe(secondCaptureId); + return { + ok: false, + error: { + code: 'INVALID_ARGS', + message: 'capture identity changed', + details: { reason: 'capture-identity-mismatch' }, + }, + }; + }); + expect(oldStop.ok).toBe(false); + await sendRemoteCapture(endpoint, request('stop'), firstStateDir, async (req) => { + expect(req.meta?.captureId).toBeUndefined(); + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }); +}); + +test('missing or mismatched stop confirmation cannot select a saved path', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/owned.trace'), + stateDir, + async (req) => confirmed(req), + ); + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect( + (await confirmedCaptureStopRequest(req, success)).meta?.clientArtifactPaths?.outPath, + ).toBeUndefined(); + expect( + (await confirmedCaptureStopRequest(req, { ok: true, data: { clientCaptureId: 'other' } })) + .meta?.clientArtifactPaths?.outPath, + ).toBeUndefined(); + return success; + }); +}); + test('scope and explicit stop path cannot borrow or override another capture destination', async () => { const stateDir = mkdtempForTestSync('capture-destination-'); await sendRemoteCapture( endpoint, request('start', '/client/owned.trace'), stateDir, - async () => success, + async (req) => confirmed(req), ); await sendRemoteCapture( endpoint, @@ -163,7 +363,7 @@ test('endpoint, tenant, run, lease, session, and capture kind each isolate desti endpoint, request('start', '/client/owned.trace', { family: 'perf' }), stateDir, - async () => success, + async (req) => confirmed(req), ); const variants = [ { baseUrl: `${endpoint}/other`, options: { family: 'perf' as const } }, @@ -185,8 +385,11 @@ test('endpoint, tenant, run, lease, session, and capture kind each isolate desti request('stop', undefined, { family: 'perf' }), stateDir, async (req) => { - expect(req.meta?.clientArtifactPaths?.outPath).toBe('/client/owned.trace'); - return success; + const answer = confirmed(req); + expect( + (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + ).toBe('/client/owned.trace'); + return answer; }, ); }); diff --git a/packages/remote/src/capture-destination-record.ts b/packages/remote/src/capture-destination-record.ts index f18ebf249c2..4179440a133 100644 --- a/packages/remote/src/capture-destination-record.ts +++ b/packages/remote/src/capture-destination-record.ts @@ -5,14 +5,13 @@ import type { DaemonWireRequest } from '@agent-device/contracts/command'; import { leaseScopeFromRequest } from '@agent-device/contracts/lease-scope'; import { parsePerfRuntimeRequest } from '@agent-device/capture-kit/perf-runtime-plan'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; +import { CAPTURE_IDENTITY_REASONS } from '@agent-device/kernel/errors'; import { acquireProcessLock, publishFileSync, withProcessLock } from '@agent-device/host-kit/file'; import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; type Capture = { action: 'start' | 'stop'; family: string }; -type Active = { state: 'active'; generation: string; destination: string }; -type Pending = { state: 'pending'; generation: string }; -type RecordState = Active | Pending; - +type Active = { generation: string; destination: string }; +type RecordState = { active?: Active; pending: string[] }; const stopGenerations = new WeakMap(); function captureOf(req: DaemonWireRequest): Capture | undefined { @@ -35,12 +34,7 @@ function captureOf(req: DaemonWireRequest): Capture | undefined { return undefined; } -function recordFile( - stateDir: string, - baseUrl: string, - req: DaemonWireRequest, - family: string, -): string { +function sessionRecordDir(stateDir: string, baseUrl: string, req: DaemonWireRequest): string { const scope = leaseScopeFromRequest(req); const key = crypto .createHash('sha256') @@ -51,11 +45,20 @@ function recordFile( scope.runId ?? null, scope.leaseId ?? null, req.session ?? null, - family, ]), ) .digest('hex'); - return path.join(stateDir, 'remote-connections', 'capture-destinations', `${key}.json`); + return path.join(stateDir, 'remote-connections', 'capture-destinations', key); +} + +function recordFile( + stateDir: string, + baseUrl: string, + req: DaemonWireRequest, + family: string, +): string { + const key = crypto.createHash('sha256').update(family).digest('hex'); + return path.join(sessionRecordDir(stateDir, baseUrl, req), `${key}.json`); } function readRecord(file: string): RecordState | undefined { @@ -67,14 +70,17 @@ function readRecord(file: string): RecordState | undefined { } if (typeof value !== 'object' || value === null) return undefined; const record = value as Partial; - if (typeof record.generation !== 'string') return undefined; - if (record.state === 'active') { - return typeof record.destination === 'string' && path.isAbsolute(record.destination) - ? { state: 'active', generation: record.generation, destination: record.destination } - : undefined; - } - if (record.state !== 'pending') return undefined; - return { state: 'pending', generation: record.generation }; + if (!Array.isArray(record.pending) || !record.pending.every((id) => typeof id === 'string')) + return undefined; + const active = record.active; + if ( + active !== undefined && + (typeof active.generation !== 'string' || + typeof active.destination !== 'string' || + !path.isAbsolute(active.destination)) + ) + return undefined; + return { ...(active ? { active } : {}), pending: record.pending }; } function writeRecord(file: string, record: RecordState): void { @@ -82,6 +88,11 @@ function writeRecord(file: string, record: RecordState): void { publishFileSync({ destination: file, contents: `${JSON.stringify(record)}\n`, mode: 0o600 }); } +function settleRecord(file: string, record: RecordState): void { + if (!record.active && record.pending.length === 0) fs.rmSync(file, { force: true }); + else writeRecord(file, record); +} + async function withRecordLock(file: string, task: () => Promise): Promise { fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); const { pid, startTime } = readCurrentOwnerIdentity(); @@ -105,43 +116,59 @@ export async function sendRemoteCapture( send: (req: DaemonWireRequest) => Promise, ): Promise { const capture = captureOf(req); - if (!capture) return await send(req); + if (!capture) { + const response = await send(req); + if (response.ok && req.command === 'close') + await retireClosedSessionCaptures(baseUrl, req, stateDir); + return response; + } const file = recordFile(stateDir, baseUrl, req, capture.family); if (capture.action === 'stop') { const active = await withRecordLock(file, async () => { const current = readRecord(file); - return current?.state === 'active' ? current : undefined; + return current?.pending.length === 0 ? current.active : undefined; }); if (!active) return await send(req); const hasExplicitPath = typeof req.meta?.clientArtifactPaths?.outPath === 'string'; const sent = hasExplicitPath ? req - : { - ...req, - meta: { - ...req.meta, - clientArtifactPaths: { ...req.meta?.clientArtifactPaths, outPath: active.destination }, - }, - }; + : { ...req, meta: { ...req.meta, captureId: active.generation } }; stopGenerations.set(sent, { file, generation: active.generation }); - return await send(sent); + const response = await send(sent); + if (!response.ok && response.error.details?.reason === CAPTURE_IDENTITY_REASONS.mismatch.reason) + await retireSuccessfulCaptureStop(sent); + return response; } const generation = crypto.randomUUID(); await withRecordLock(file, async () => { - writeRecord(file, { state: 'pending', generation }); + const current = readRecord(file); + writeRecord(file, { + ...(current?.active ? { active: current.active } : {}), + pending: [...(current?.pending ?? []), generation], + }); }); - const response = await send(req); - if (!response.ok) return response; + const response = await send({ ...req, meta: { ...req.meta, captureId: generation } }); + if ( + !response.ok && + response.error.details?.reason !== CAPTURE_IDENTITY_REASONS.alreadyActive.reason + ) + return response; const destination = req.meta?.clientArtifactPaths?.outPath; await withRecordLock(file, async () => { const current = readRecord(file); - if (current?.state !== 'pending' || current.generation !== generation) return; - if (typeof destination === 'string' && path.isAbsolute(destination)) { - writeRecord(file, { state: 'active', generation, destination }); - } else { - fs.rmSync(file, { force: true }); - } + if (!current?.pending.includes(generation)) return; + const pending = current.pending.filter((id) => id !== generation); + const active = response.ok + ? response.data?.clientCaptureId === generation && + typeof destination === 'string' && + path.isAbsolute(destination) + ? { generation, destination } + : undefined + : response.error.details?.clientCaptureId === current.active?.generation + ? current.active + : undefined; + settleRecord(file, { ...(active ? { active } : {}), pending }); }); return response; } @@ -153,8 +180,51 @@ export async function retireSuccessfulCaptureStop(req: DaemonWireRequest): Promi stopGenerations.delete(req); await withRecordLock(owned.file, async () => { const current = readRecord(owned.file); - if (current?.state === 'active' && current.generation === owned.generation) { - fs.rmSync(owned.file, { force: true }); - } + if (current?.active?.generation === owned.generation) + settleRecord(owned.file, { pending: current.pending }); + }); +} + +/** A response can use a saved path only when it confirms this client's live capture identity. */ +export async function confirmedCaptureStopRequest( + req: DaemonWireRequest, + response: Extract, +): Promise { + const owned = stopGenerations.get(req); + if (!owned || response.data?.clientCaptureId !== owned.generation) return req; + const active = await withRecordLock(owned.file, async () => { + const current = readRecord(owned.file); + return current?.pending.length === 0 && current.active?.generation === owned.generation + ? current.active + : undefined; }); + if (!active || typeof req.meta?.clientArtifactPaths?.outPath === 'string') return req; + return { + ...req, + meta: { + ...req.meta, + clientArtifactPaths: { ...req.meta?.clientArtifactPaths, outPath: active.destination }, + }, + }; +} + +/** A successful full close ends all captures attached to this session address. */ +export async function retireClosedSessionCaptures( + baseUrl: string, + req: DaemonWireRequest, + stateDir: string, +): Promise { + if (req.command !== 'close') return; + const dir = sessionRecordDir(stateDir, baseUrl, req); + let entries: string[]; + try { + entries = fs.readdirSync(dir).filter((entry) => entry.endsWith('.json')); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return; + throw error; + } + for (const entry of entries) { + const file = path.join(dir, entry); + await withRecordLock(file, async () => fs.rmSync(file, { force: true })); + } } diff --git a/packages/remote/src/daemon-artifacts.ts b/packages/remote/src/daemon-artifacts.ts index a4289e4f93f..cd632c59fd7 100644 --- a/packages/remote/src/daemon-artifacts.ts +++ b/packages/remote/src/daemon-artifacts.ts @@ -535,11 +535,12 @@ export async function materializeRemoteArtifacts( ): Promise { if (!info.baseUrl) return response; const captures = await import('./capture-destination-record.ts'); + const downloadRequest = await captures.confirmedCaptureStopRequest(req, response); await captures.retireSuccessfulCaptureStop(req); const endpoint = { baseUrl: info.baseUrl, token: info.token }; const artifacts = Array.isArray(response.data?.artifacts) ? response.data.artifacts : []; const download = (scripts?: SessionScriptDelivery) => - downloadResponseArtifacts(endpoint, req, response, host, scripts); + downloadResponseArtifacts(endpoint, downloadRequest, response, host, scripts); // A receipt is a delivery instruction of its own: a batch answer may carry one while naming no // publication and no script artifact of its own (#4595). if ( From f78867e22f95afa22ba306f700e50482f489c490 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 23:44:54 +0100 Subject: [PATCH 36/55] docs: record capture identity refusals and destination rules --- docs/agents/security.md | 21 ++++++++++----------- packages/kernel/src/errors.ts | 2 ++ website/docs/docs/error-reasons.md | 7 +++++++ 3 files changed, 19 insertions(+), 11 deletions(-) diff --git a/docs/agents/security.md b/docs/agents/security.md index 6c5c719c9ac..908b3478c94 100644 --- a/docs/agents/security.md +++ b/docs/agents/security.md @@ -1,16 +1,15 @@ # Security boundaries -The CLI client owns local destinations; it trusts a remote daemon only for data and validated IDs. -Scripts and remote record stops reject daemon-chosen paths (#4518). -Remote trace/perf uses caller paths. Unnamed captures get unique client cwd names. -For remote trace/native perf, key start paths by endpoint, tenant, run, lease, session, and kind. -Before each start, mark the new capture pending and keep the last confirmed destination. -If the daemon rejects a repeated start and names the same capture ID, restore the confirmed destination. -If a start has no clear outcome, do not use the confirmed destination for a pathless stop. -For a pathless stop, require the daemon to match the client capture ID before it stops the capture. -Before a remote download, require the stop response to confirm that ID and read the destination from client state. -If the daemon does not confirm the ID, use a unique client cwd name. -After a successful full close or stop, retire the confirmed destination. +The client owns local paths; the daemon supplies only data and validated IDs. +Reject daemon-chosen paths in scripts and remote record stops (#4518). +Trace/perf uses caller paths. Unnamed captures get unique cwd names. +Key trace/perf paths by endpoint, tenant, run, lease, session, and kind. +On start, mark identity pending. +Restore the path only after a same-ID rejection. +On pathless stop, send the client capture ID. +Use a saved path only after ID confirmation. +On unclear outcomes or ID mismatch, use a unique cwd name. +After close or stop, retire the path. The daemon admits its state directory. Nobody trusts the network or other local users. Out of scope: same uid, hostile root, ACLs, mounts, untrusted filesystems. ADR 0041 owns credential transport. diff --git a/packages/kernel/src/errors.ts b/packages/kernel/src/errors.ts index 85b69ce491b..b83d871028c 100644 --- a/packages/kernel/src/errors.ts +++ b/packages/kernel/src/errors.ts @@ -498,7 +498,9 @@ export const DURABLE_RESOURCE_REASONS = { /** Refusals that identify the live trace or native perf capture without trusting an output path. */ export const CAPTURE_IDENTITY_REASONS = { + // A capture already runs for this session; the response names its live capture ID. alreadyActive: { reason: 'capture-already-active' }, + // The requested capture ID differs from the live capture ID, so the stop is refused. mismatch: { reason: 'capture-identity-mismatch' }, } as const satisfies ReasonTable<'capture identity'>; diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index d294e026249..816cf54e17a 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -596,6 +596,13 @@ These reasons can come from more than one command. | `ARCHIVE_UNSAFE_ENTRY` | The archive holds a link, a special file, or an encrypted entry. | | `ARCHIVE_UNSAFE_PATH` | An archive entry's name is absolute, escaping, or otherwise not one relative path. | +### Capture identity + +| Reason | Meaning | +| --- | --- | +| `capture-already-active` | A capture already runs for this session; the response names its live capture ID. | +| `capture-identity-mismatch` | The requested capture ID differs from the live capture ID, so the stop is refused. | + ### Command flags | Reason | Meaning | From 250db806213705d4d56fb8254ce9affd54c687c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 23:45:54 +0100 Subject: [PATCH 37/55] fix(remote): bound uncertain capture start state --- .../capture-destination-record.test.ts | 78 +++++++++++++ .../remote/src/capture-destination-record.ts | 106 +++++++++++++----- 2 files changed, 156 insertions(+), 28 deletions(-) diff --git a/packages/remote/src/__tests__/capture-destination-record.test.ts b/packages/remote/src/__tests__/capture-destination-record.test.ts index f300e7a0e68..2865b60eed7 100644 --- a/packages/remote/src/__tests__/capture-destination-record.test.ts +++ b/packages/remote/src/__tests__/capture-destination-record.test.ts @@ -1,3 +1,5 @@ +import fs from 'node:fs'; +import path from 'node:path'; import { test, expect } from 'vitest'; import { createTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; import type { DaemonWireRequest } from '@agent-device/contracts/command'; @@ -324,6 +326,82 @@ test('missing or mismatched stop confirmation cannot select a saved path', async }); }); +test.each(['returned', 'thrown'] as const)( + 'repeated %s start failures keep one bounded fail-closed marker', + async (failure) => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/old.trace'), + stateDir, + async (req) => confirmed(req), + ); + for (let attempt = 0; attempt < 40; attempt += 1) { + const start = sendRemoteCapture( + endpoint, + request('start', '/client/new.trace'), + stateDir, + async () => { + if (failure === 'thrown') throw new Error('transport uncertain'); + return { ok: false as const, error: { code: 'COMMAND_FAILED', message: 'uncertain' } }; + }, + ); + if (failure === 'thrown') await expect(start).rejects.toThrow('transport uncertain'); + else expect((await start).ok).toBe(false); + } + const root = path.join(stateDir, 'remote-connections', 'capture-destinations'); + const [scope] = fs.readdirSync(root); + const [recordName] = fs.readdirSync(path.join(root, scope)); + const record = JSON.parse(fs.readFileSync(path.join(root, scope, recordName), 'utf8')); + expect(record.pending).toEqual([]); + expect(record.uncertain).toBe(true); + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.captureId).toBeUndefined(); + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }); + }, +); + +test('a late successful start cannot replace a newer confirmed destination', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + let releaseFirst!: () => void; + const firstStarted = new Promise((resolve) => (releaseFirst = resolve)); + let finishFirst!: () => void; + const firstCanFinish = new Promise((resolve) => (finishFirst = resolve)); + const first = sendRemoteCapture( + endpoint, + request('start', '/client/old.trace'), + stateDir, + async (req) => { + releaseFirst(); + await firstCanFinish; + return confirmed(req); + }, + ); + await firstStarted; + let newerCaptureId: string | undefined; + await sendRemoteCapture( + endpoint, + request('start', '/client/new.trace'), + stateDir, + async (req) => { + newerCaptureId = req.meta?.captureId; + return confirmed(req); + }, + ); + finishFirst(); + await first; + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.captureId).toBe(newerCaptureId); + const answer = confirmed(req); + expect( + (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + ).toBe('/client/new.trace'); + return answer; + }); +}); + test('scope and explicit stop path cannot borrow or override another capture destination', async () => { const stateDir = mkdtempForTestSync('capture-destination-'); await sendRemoteCapture( diff --git a/packages/remote/src/capture-destination-record.ts b/packages/remote/src/capture-destination-record.ts index 4179440a133..468a01790ad 100644 --- a/packages/remote/src/capture-destination-record.ts +++ b/packages/remote/src/capture-destination-record.ts @@ -10,8 +10,9 @@ import { acquireProcessLock, publishFileSync, withProcessLock } from '@agent-dev import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; type Capture = { action: 'start' | 'stop'; family: string }; -type Active = { generation: string; destination: string }; -type RecordState = { active?: Active; pending: string[] }; +type Active = { generation: string; destination: string; order: number }; +type Pending = { generation: string; order: number }; +type RecordState = { active?: Active; pending: Pending[]; uncertain: boolean; nextOrder: number }; const stopGenerations = new WeakMap(); function captureOf(req: DaemonWireRequest): Capture | undefined { @@ -70,17 +71,39 @@ function readRecord(file: string): RecordState | undefined { } if (typeof value !== 'object' || value === null) return undefined; const record = value as Partial; - if (!Array.isArray(record.pending) || !record.pending.every((id) => typeof id === 'string')) + if ( + !Array.isArray(record.pending) || + !record.pending.every( + (pending) => + typeof pending === 'object' && + pending !== null && + typeof pending.generation === 'string' && + Number.isSafeInteger(pending.order) && + pending.order > 0, + ) || + typeof record.uncertain !== 'boolean' || + typeof record.nextOrder !== 'number' || + !Number.isSafeInteger(record.nextOrder) || + record.nextOrder < 0 + ) return undefined; const active = record.active; if ( active !== undefined && - (typeof active.generation !== 'string' || + (active === null || + typeof active.generation !== 'string' || typeof active.destination !== 'string' || - !path.isAbsolute(active.destination)) + !path.isAbsolute(active.destination) || + !Number.isSafeInteger(active.order) || + active.order < 1) ) return undefined; - return { ...(active ? { active } : {}), pending: record.pending }; + return { + ...(active ? { active } : {}), + pending: record.pending, + uncertain: record.uncertain, + nextOrder: record.nextOrder, + }; } function writeRecord(file: string, record: RecordState): void { @@ -89,7 +112,8 @@ function writeRecord(file: string, record: RecordState): void { } function settleRecord(file: string, record: RecordState): void { - if (!record.active && record.pending.length === 0) fs.rmSync(file, { force: true }); + if (!record.active && record.pending.length === 0 && !record.uncertain) + fs.rmSync(file, { force: true }); else writeRecord(file, record); } @@ -126,7 +150,7 @@ export async function sendRemoteCapture( if (capture.action === 'stop') { const active = await withRecordLock(file, async () => { const current = readRecord(file); - return current?.pending.length === 0 ? current.active : undefined; + return current?.pending.length === 0 && !current.uncertain ? current.active : undefined; }); if (!active) return await send(req); const hasExplicitPath = typeof req.meta?.clientArtifactPaths?.outPath === 'string'; @@ -141,35 +165,55 @@ export async function sendRemoteCapture( } const generation = crypto.randomUUID(); - await withRecordLock(file, async () => { + const order = await withRecordLock(file, async () => { const current = readRecord(file); + const nextOrder = (current?.nextOrder ?? 0) + 1; writeRecord(file, { ...(current?.active ? { active: current.active } : {}), - pending: [...(current?.pending ?? []), generation], + pending: [...(current?.pending ?? []), { generation, order: nextOrder }], + uncertain: current?.uncertain ?? false, + nextOrder, }); + return nextOrder; }); - const response = await send({ ...req, meta: { ...req.meta, captureId: generation } }); - if ( - !response.ok && - response.error.details?.reason !== CAPTURE_IDENTITY_REASONS.alreadyActive.reason - ) - return response; + let response: DaemonResponse | undefined; + let failure: unknown; + let threw = false; + try { + response = await send({ ...req, meta: { ...req.meta, captureId: generation } }); + } catch (error) { + threw = true; + failure = error; + } const destination = req.meta?.clientArtifactPaths?.outPath; await withRecordLock(file, async () => { const current = readRecord(file); - if (!current?.pending.includes(generation)) return; - const pending = current.pending.filter((id) => id !== generation); - const active = response.ok - ? response.data?.clientCaptureId === generation && + if (!current?.pending.some((pending) => pending.generation === generation)) return; + const pending = current.pending.filter((candidate) => candidate.generation !== generation); + const refusedActive = + response?.ok === false && + response.error.details?.reason === CAPTURE_IDENTITY_REASONS.alreadyActive.reason; + const uncertain = current.uncertain || (!response?.ok && !refusedActive); + let active = current.active; + if (response?.ok && order >= (active?.order ?? 0)) { + active = + response.data?.clientCaptureId === generation && typeof destination === 'string' && path.isAbsolute(destination) - ? { generation, destination } - : undefined - : response.error.details?.clientCaptureId === current.active?.generation - ? current.active - : undefined; - settleRecord(file, { ...(active ? { active } : {}), pending }); + ? { generation, destination, order } + : undefined; + } else if (refusedActive && order >= (active?.order ?? 0)) { + active = response.error.details?.clientCaptureId === active?.generation ? active : undefined; + } + settleRecord(file, { + ...(active ? { active } : {}), + pending, + uncertain, + nextOrder: current.nextOrder, + }); }); + if (threw) throw failure; + if (!response) throw new TypeError('Capture start settled without a response'); return response; } @@ -181,7 +225,11 @@ export async function retireSuccessfulCaptureStop(req: DaemonWireRequest): Promi await withRecordLock(owned.file, async () => { const current = readRecord(owned.file); if (current?.active?.generation === owned.generation) - settleRecord(owned.file, { pending: current.pending }); + settleRecord(owned.file, { + pending: current.pending, + uncertain: current.uncertain, + nextOrder: current.nextOrder, + }); }); } @@ -194,7 +242,9 @@ export async function confirmedCaptureStopRequest( if (!owned || response.data?.clientCaptureId !== owned.generation) return req; const active = await withRecordLock(owned.file, async () => { const current = readRecord(owned.file); - return current?.pending.length === 0 && current.active?.generation === owned.generation + return current?.pending.length === 0 && + !current.uncertain && + current.active?.generation === owned.generation ? current.active : undefined; }); From bfa94377c3b7552b2d64a6f20fa1679f699c092a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 23:46:30 +0100 Subject: [PATCH 38/55] chore(gates): record additive capture identity wire changes --- test/wire-compat/ledger.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 64b02ff324d..976ebdb46ed 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -23,7 +23,7 @@ "packages/kernel/src/contracts.ts#DaemonInstallSource": "sha256:adfde90c81de72009bf0e092b95fcb41cece2ecd44e936dcb1f6beb220287f02", "packages/kernel/src/contracts.ts#DaemonLockPolicy": "sha256:f33d0ce7200a7d97c11e91bd2889b5d9bc7f35935a5370a29930118d091468f4", "packages/kernel/src/contracts.ts#DaemonRequest": "sha256:911d93245b8dc557db897c4cac051030db673711bf3af51baa8b82248d509c57", - "packages/kernel/src/contracts.ts#DaemonRequestMeta": "sha256:c2b14225388041f3a6e708c898c512f91b9b20e51a2656a1fa0d5bfa5989fa30", + "packages/kernel/src/contracts.ts#DaemonRequestMeta": "sha256:87fa7572b580917e89abc4a27ffbf72993ed562a0b7140c38211aa757d9b2b38", "packages/kernel/src/contracts.ts#DaemonResponse": "sha256:5f6cc08ed43f40c1cf17e33dd2b6b879dda1ac383de9c6c9a2c653929c21346b", "packages/kernel/src/contracts.ts#DaemonResponseData": "sha256:f16e61b7f0ea8cdae82349508383af2f97a4c16c8aa21952d833094673f86afc", "packages/kernel/src/contracts.ts#JsonRpcId": "sha256:5a5fdff1cd85971214117d69a8278d0ecaf21a6fa3f4582155d9b3d9cad1fbd0", @@ -159,7 +159,7 @@ "packages/remote/src/daemon-artifacts.ts#buildDaemonArtifactUrl": "sha256:06dcde057809b507f70f7bb5cdef9bde6515be84b67e45865cf19e70b8636208", "packages/remote/src/daemon-artifacts.ts#downloadRemoteArtifact": "sha256:3f3b6c01601c54ab2c76c8cb0946de623da4d24ba32254c75ae8a3993f66adcf", "packages/remote/src/daemon-artifacts.ts#isRemoteDaemon": "sha256:0f6a714c5f60ce4e8548d811b516d8b6241eca9f7e5414733732da395b8a00e7", - "packages/remote/src/daemon-artifacts.ts#materializeRemoteArtifacts": "sha256:35b77d752799782ae0082b3123f9572e222a67f7d59d18c294c484d4226aabb7", + "packages/remote/src/daemon-artifacts.ts#materializeRemoteArtifacts": "sha256:b7b4edcccfee11633ebcc96d302f389f644cf39ecea0e471ef31fc1082db5615", "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath": "sha256:0495174ab15a8c5a7c159eb957d3fc463a856b151c47a77cf0d567eb9843ee21", "packages/remote/src/daemon-artifacts.ts#resolveOrdinaryArtifactFallbackPath": "sha256:c0fdd490bb6e596adbbc2b9db35230eac5373c313fc5a230ac09ec70320694bb", "packages/remote/src/remote-request-diagnostics.ts#RemoteDaemonErrorPayload": "sha256:8fbcbcdf4bae7b66a08e465a72593794f36364759f18f1a814cd39dfdb76f309", @@ -269,8 +269,8 @@ "compatibleChanges": [ { "declaration": "packages/kernel/src/contracts.ts#DaemonRequestMeta", - "digest": "sha256:c2b14225388041f3a6e708c898c512f91b9b20e51a2656a1fa0d5bfa5989fa30", - "rationale": "Adds the optional developerDir field: a local client's DEVELOPER_DIR, overlaid on the env of commands the daemon spawns for that request. A released daemon ignores the unknown meta key and keeps its own environment, exactly as before; a released client never sends it, so the new daemon inherits its own environment for that request. The remote HTTP surface strips it. Also adds the optional leaseRetainOnClose field, sent only on lease_allocate when the caller opts in: a released daemon ignores the unknown meta key and releases the lease on session close as before, and a released client never sends it. Adds the optional providerCredentialFingerprint field: a digest of the local caller's provider credential variables, which the daemon compares with its own on lease_allocate. A released daemon ignores the unknown meta key and allocates as before; a released client never sends it, so the new daemon skips the comparison. The client sends it only to a local daemon, and the remote HTTP surface strips it. #4511 adds the optional scriptPublicationId string, which a new client sends only on a remote open --save-script to a daemon that reports the script-artifacts capability. Any other request keeps its previous meta." + "digest": "sha256:87fa7572b580917e89abc4a27ffbf72993ed562a0b7140c38211aa757d9b2b38", + "rationale": "Adds the optional developerDir field: a local client's DEVELOPER_DIR, overlaid on the env of commands the daemon spawns for that request. A released daemon ignores the unknown meta key and keeps its own environment, exactly as before; a released client never sends it, so the new daemon inherits its own environment for that request. The remote HTTP surface strips it. Also adds the optional leaseRetainOnClose field, sent only on lease_allocate when the caller opts in: a released daemon ignores the unknown meta key and releases the lease on session close as before, and a released client never sends it. Adds the optional providerCredentialFingerprint field: a digest of the local caller's provider credential variables, which the daemon compares with its own on lease_allocate. A released daemon ignores the unknown meta key and allocates as before; a released client never sends it, so the new daemon skips the comparison. The client sends it only to a local daemon, and the remote HTTP surface strips it. #4511 adds the optional scriptPublicationId string, which a new client sends only on a remote open --save-script to a daemon that reports the script-artifacts capability. Any other request keeps its previous meta. Adds optional captureId metadata on trace and native perf start/stop. A released daemon ignores the unknown meta key and keeps its prior capture behavior; a released client omits it, so the new daemon preserves that behavior. A new client reuses a saved destination only when the daemon response confirms the live capture identity. Routes, authentication, and framing are unchanged under ADR 0006." }, { "declaration": "packages/kernel/src/contracts.ts#DaemonArtifactKnownType", @@ -674,8 +674,8 @@ }, { "declaration": "packages/remote/src/daemon-artifacts.ts#materializeRemoteArtifacts", - "digest": "sha256:35b77d752799782ae0082b3123f9572e222a67f7d59d18c294c484d4226aabb7", - "rationale": "Passes the in-memory fetchRemoteArtifact to the session-script owner instead of the file download, and retires a client-local capture destination before downloading a successful stop's artifacts. A pathless stop can carry the existing optional meta.clientArtifactPaths.outPath from client state; an older daemon can ignore that hint or use it as before. An older client receives the same response and retains its fallback. The GET /artifacts/:id request, headers, artifact fields, and response framing are unchanged." + "digest": "sha256:b7b4edcccfee11633ebcc96d302f389f644cf39ecea0e471ef31fc1082db5615", + "rationale": "Passes the in-memory fetchRemoteArtifact to the session-script owner instead of the file download, and retires a client-local capture destination before downloading a successful stop's artifacts. A pathless stop can carry the existing optional meta.clientArtifactPaths.outPath from client state; an older daemon can ignore that hint or use it as before. An older client receives the same response and retains its fallback. A new client uses the destination recorded with the confirmed live capture ID for a pathless stop; an unconfirmed response gets a fresh client cwd name. A released daemon ignores optional captureId metadata, so this client-only destination choice does not change peer parsing. The GET /artifacts/:id request, headers, artifact fields, and response framing are unchanged." }, { "declaration": "packages/remote/src/script-version-publisher.ts#publishScriptVersion", From d0b0999dcf32ecb1eaaaa0933aea5c599f86452d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 23:50:05 +0100 Subject: [PATCH 39/55] fix(maestro): satisfy selector regex type and escape checks --- packages/maestro/src/internal/selector-regex.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index e46814958bc..c7f327a27c6 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -37,7 +37,7 @@ function matchesLiteral(value: string, matcher: LiteralMatcher): boolean { return matchesLongLiteralLine(value, matcher.literal); } matcher.lineRegex ??= new RegExp( - `^(?:${matcher.literal.replaceAll(/[\\^$.*+?()[\]{}|]/g, '\\$&')})$`, + `^(?:${matcher.literal.replaceAll(/[\\^$.*+?()[\]{}|]/g, String.raw`\$&`)})$`, 'im', ); return matcher.lineRegex.test(value); @@ -247,7 +247,7 @@ function quantifiedAtomsAreDisjoint( function isAsciiOnly(element: AST.QuantifiableElement): boolean { if (element.type === 'Character') return element.value < 128; if (element.type === 'CharacterSet') { - return !element.negate && (element.kind === 'digit' || element.kind === 'word'); + return (element.kind === 'digit' || element.kind === 'word') && !element.negate; } if (element.type !== 'CharacterClass' || element.negate) return false; return element.elements.every((part) => { From 61cc572ceea6244191ead127b93da13fb2bdd52d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 23:50:03 +0100 Subject: [PATCH 40/55] fix(remote): resolve capture CI type errors --- .../session-observability/internal/session-perf-runtime.ts | 3 +-- .../remote/src/__tests__/capture-destination-record.test.ts | 4 ++++ packages/remote/src/capture-destination-record.ts | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts b/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts index 9c91931b96e..493f08492f0 100644 --- a/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts +++ b/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts @@ -1,6 +1,5 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; -import { CAPTURE_IDENTITY_REASONS } from '@agent-device/kernel/errors'; import { expandSessionPath } from '@agent-device/host-kit/session-paths'; import path from 'node:path'; import { type PerfCaptureAdmissionLedger } from '@agent-device/capture-kit/perf-capture-admission-ledger'; @@ -27,7 +26,7 @@ import { PERF_AGGREGATE_REMOVED_ERROR_MESSAGE, } from '@agent-device/contracts/observability'; import { publicPlatformString } from '@agent-device/kernel/device'; -import { AppError, normalizeError } from '@agent-device/kernel/errors'; +import { AppError, CAPTURE_IDENTITY_REASONS, normalizeError } from '@agent-device/kernel/errors'; import { isRecord } from '@agent-device/kernel/record'; import type { BindDeviceRuntime, diff --git a/packages/remote/src/__tests__/capture-destination-record.test.ts b/packages/remote/src/__tests__/capture-destination-record.test.ts index 2865b60eed7..1103d9edcea 100644 --- a/packages/remote/src/__tests__/capture-destination-record.test.ts +++ b/packages/remote/src/__tests__/capture-destination-record.test.ts @@ -351,7 +351,11 @@ test.each(['returned', 'thrown'] as const)( } const root = path.join(stateDir, 'remote-connections', 'capture-destinations'); const [scope] = fs.readdirSync(root); + expect(scope).toBeDefined(); + if (!scope) throw new Error('Missing capture session record directory'); const [recordName] = fs.readdirSync(path.join(root, scope)); + expect(recordName).toBeDefined(); + if (!recordName) throw new Error('Missing capture record'); const record = JSON.parse(fs.readFileSync(path.join(root, scope, recordName), 'utf8')); expect(record.pending).toEqual([]); expect(record.uncertain).toBe(true); diff --git a/packages/remote/src/capture-destination-record.ts b/packages/remote/src/capture-destination-record.ts index 468a01790ad..f7c86ab01ef 100644 --- a/packages/remote/src/capture-destination-record.ts +++ b/packages/remote/src/capture-destination-record.ts @@ -202,7 +202,7 @@ export async function sendRemoteCapture( path.isAbsolute(destination) ? { generation, destination, order } : undefined; - } else if (refusedActive && order >= (active?.order ?? 0)) { + } else if (response?.ok === false && refusedActive && order >= (active?.order ?? 0)) { active = response.error.details?.clientCaptureId === active?.generation ? active : undefined; } settleRecord(file, { From 6a32e82379e81f83402b076860a4ee7e1722db3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 23:55:58 +0100 Subject: [PATCH 41/55] refactor(remote): simplify capture start settlement --- .../remote/src/capture-destination-record.ts | 78 +++++++++++++------ 1 file changed, 54 insertions(+), 24 deletions(-) diff --git a/packages/remote/src/capture-destination-record.ts b/packages/remote/src/capture-destination-record.ts index f7c86ab01ef..65a16969591 100644 --- a/packages/remote/src/capture-destination-record.ts +++ b/packages/remote/src/capture-destination-record.ts @@ -117,6 +117,58 @@ function settleRecord(file: string, record: RecordState): void { else writeRecord(file, record); } +function isActiveCaptureRefusal(response: DaemonResponse | undefined): boolean { + return ( + response?.ok === false && + response.error.details?.reason === CAPTURE_IDENTITY_REASONS.alreadyActive.reason + ); +} + +function confirmedStartDestination( + response: Extract, + generation: string, + destination: string | undefined, + order: number, +): Active | undefined { + return response.data?.clientCaptureId === generation && + typeof destination === 'string' && + path.isAbsolute(destination) + ? { generation, destination, order } + : undefined; +} + +function activeAfterStart( + current: RecordState, + response: DaemonResponse | undefined, + generation: string, + destination: string | undefined, + order: number, +): Active | undefined { + const active = current.active; + if (order < (active?.order ?? 0)) return active; + if (response?.ok === true) + return confirmedStartDestination(response, generation, destination, order); + if (response?.ok === false && isActiveCaptureRefusal(response)) + return response.error.details?.clientCaptureId === active?.generation ? active : undefined; + return active; +} + +function recordAfterStart( + current: RecordState, + response: DaemonResponse | undefined, + generation: string, + destination: string | undefined, + order: number, +): RecordState { + const active = activeAfterStart(current, response, generation, destination, order); + return { + ...(active ? { active } : {}), + pending: current.pending.filter((candidate) => candidate.generation !== generation), + uncertain: current.uncertain || (response?.ok !== true && !isActiveCaptureRefusal(response)), + nextOrder: current.nextOrder, + }; +} + async function withRecordLock(file: string, task: () => Promise): Promise { fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); const { pid, startTime } = readCurrentOwnerIdentity(); @@ -189,28 +241,7 @@ export async function sendRemoteCapture( await withRecordLock(file, async () => { const current = readRecord(file); if (!current?.pending.some((pending) => pending.generation === generation)) return; - const pending = current.pending.filter((candidate) => candidate.generation !== generation); - const refusedActive = - response?.ok === false && - response.error.details?.reason === CAPTURE_IDENTITY_REASONS.alreadyActive.reason; - const uncertain = current.uncertain || (!response?.ok && !refusedActive); - let active = current.active; - if (response?.ok && order >= (active?.order ?? 0)) { - active = - response.data?.clientCaptureId === generation && - typeof destination === 'string' && - path.isAbsolute(destination) - ? { generation, destination, order } - : undefined; - } else if (response?.ok === false && refusedActive && order >= (active?.order ?? 0)) { - active = response.error.details?.clientCaptureId === active?.generation ? active : undefined; - } - settleRecord(file, { - ...(active ? { active } : {}), - pending, - uncertain, - nextOrder: current.nextOrder, - }); + settleRecord(file, recordAfterStart(current, response, generation, destination, order)); }); if (threw) throw failure; if (!response) throw new TypeError('Capture start settled without a response'); @@ -258,8 +289,7 @@ export async function confirmedCaptureStopRequest( }; } -/** A successful full close ends all captures attached to this session address. */ -export async function retireClosedSessionCaptures( +async function retireClosedSessionCaptures( baseUrl: string, req: DaemonWireRequest, stateDir: string, From 0a4c09f88e194efddf29a96b84113006a3560d72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 00:26:20 +0100 Subject: [PATCH 42/55] fix(maestro): allow long exact selector text safely --- .../src/internal/__tests__/selector-regex.test.ts | 10 ++++++++++ packages/maestro/src/internal/selector-regex.ts | 7 +++++++ website/docs/docs/run-maestro-flows.md | 2 +- 3 files changed, 18 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 68d2229e30b..c0f9ee1acd9 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -89,6 +89,16 @@ test('long device labels retain literal and bounded regex matches', () => { expect(matchesMaestroRegex('item', 'item')).toBe(true); }); +test('a long regex-shaped selector matches exact text without executing its regex', () => { + const pattern = `Total: 12.5 ${'x'.repeat(300)}`; + expect(matchesMaestroRegex(` total: 12.5 ${'x'.repeat(300)} `, pattern)).toBe(true); + expect(() => matchesMaestroRegex(`${pattern} more`, pattern)).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); +}); + test('multiline regex matches whole values and individual lines without retrying every suffix', () => { expect(matchesMaestroRegex('start\nmiddle\nend', 'start.*end')).toBe(true); expect(matchesMaestroRegex('before\nReady\nafter', 'Ready')).toBe(true); diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index c7f327a27c6..eed6639d539 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -21,6 +21,13 @@ type Matcher = LiteralMatcher | { regex: RegExp; canSpanLines: boolean }; const matcherCache = new Map(); export function matchesMaestroRegex(value: string, pattern: string): boolean { + if ( + pattern.length > MAX_PATTERN_LENGTH && + hasRegexSyntax(pattern) && + normalizeText(value) === normalizeText(pattern) + ) { + return true; + } const matcher = matcherForPattern(pattern); if ('literal' in matcher) return matchesLiteral(value, matcher); if (normalizeText(value) === normalizeText(pattern)) return true; diff --git a/website/docs/docs/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index 12bda615194..f41c3f12c1e 100644 --- a/website/docs/docs/run-maestro-flows.md +++ b/website/docs/docs/run-maestro-flows.md @@ -30,7 +30,7 @@ Keep the target binding, such as `--platform ios`, on the `replay` or `test` com ## Boundaries -- Selector `id` and `text` match exact text before interpreting a safe pattern as a regular expression. A plain literal also matches one line of a multiline value. Regex patterns match a whole value or one line and can use groups, alternatives, character classes, and counted or disjoint repetitions. Backreferences, overlapping repetitions across literals or groups, quantified groups with alternatives or repetitions, excessive ambiguous groups, counted repetitions over 10,000, and regex patterns over 256 characters fail with `maestro_selector_regex_unsafe`. If a pattern could span lines but neither the whole value nor one line matches, the step fails with `maestro_selector_regex_indeterminate` rather than treating a possible partial cross-line match as absent. +- Selector `id` and `text` match exact text before interpreting a safe pattern as a regular expression. A plain literal also matches one line of a multiline value. Regex patterns match a whole value or one line and can use groups, alternatives, character classes, and counted or disjoint repetitions. Backreferences, overlapping repetitions across literals or groups, quantified groups with alternatives or repetitions, excessive ambiguous groups, and counted repetitions over 10,000 fail with `maestro_selector_regex_unsafe`. Regex patterns over 256 characters also fail unless the full selector equals normalized node text, in which case regex is not executed. If a pattern could span lines but neither the whole value nor one line matches, the step fails with `maestro_selector_regex_indeterminate` rather than treating a possible partial cross-line match as absent. - 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 6629a7582c1b7bc89ffd8baf84befd84c07afcbb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 01:28:04 +0100 Subject: [PATCH 43/55] fix(remote): settle capture destinations across refusals and close races --- .../capture-destination-record.test.ts | 165 ++++++++++++++++++ .../remote/src/capture-destination-record.ts | 72 +++++--- 2 files changed, 217 insertions(+), 20 deletions(-) diff --git a/packages/remote/src/__tests__/capture-destination-record.test.ts b/packages/remote/src/__tests__/capture-destination-record.test.ts index 1103d9edcea..fff57566962 100644 --- a/packages/remote/src/__tests__/capture-destination-record.test.ts +++ b/packages/remote/src/__tests__/capture-destination-record.test.ts @@ -3,6 +3,7 @@ import path from 'node:path'; import { test, expect } from 'vitest'; import { createTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; import type { DaemonWireRequest } from '@agent-device/contracts/command'; +import { AppError } from '@agent-device/kernel/errors'; import { confirmedCaptureStopRequest, sendRemoteCapture, @@ -179,6 +180,50 @@ test.each(['trace', 'perf'] as const)( }, ); +test.each(['trace', 'perf'] as const)( + '%s HTTP refusal of a repeat start preserves the confirmed destination and original error', + async (family) => { + const stateDir = mkdtempForTestSync('capture-destination-'); + let activeId: string | undefined; + await sendRemoteCapture( + endpoint, + request('start', '/client/first.trace', { family }), + stateDir, + async (req) => { + activeId = req.meta?.captureId; + return confirmed(req); + }, + ); + const refusal = new AppError('INVALID_ARGS', 'capture already active', { + reason: 'capture-already-active', + clientCaptureId: activeId, + }); + await expect( + sendRemoteCapture( + endpoint, + request('start', '/client/second.trace', { family }), + stateDir, + async () => { + throw refusal; + }, + ), + ).rejects.toBe(refusal); + await sendRemoteCapture( + endpoint, + request('stop', undefined, { family }), + stateDir, + async (req) => { + expect(req.meta?.captureId).toBe(activeId); + const answer = confirmed(req); + expect( + (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + ).toBe('/client/first.trace'); + return answer; + }, + ); + }, +); + test('a concurrent rejected start does not discard a newly confirmed start', async () => { const stateDir = mkdtempForTestSync('capture-destination-'); let releaseFirst!: () => void; @@ -306,6 +351,126 @@ test('a different client can reuse the session name without authorizing the old }); }); +test.each(['trace', 'perf'] as const)( + '%s HTTP identity mismatch retires only the rejected capture', + async (family) => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/stale.trace', { family }), + stateDir, + async (req) => confirmed(req), + ); + const refusal = new AppError('INVALID_ARGS', 'capture identity changed', { + reason: 'capture-identity-mismatch', + }); + await expect( + sendRemoteCapture(endpoint, request('stop', undefined, { family }), stateDir, async (req) => { + expect(req.meta?.captureId).toBeTypeOf('string'); + throw refusal; + }), + ).rejects.toBe(refusal); + await sendRemoteCapture( + endpoint, + request('stop', undefined, { family }), + stateDir, + async (req) => { + expect(req.meta?.captureId).toBeUndefined(); + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }, + ); + }, +); + +test('a later confirmed start clears an earlier uncertain start', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/failed.trace'), + stateDir, + async () => ({ ok: false, error: { code: 'SESSION_NOT_FOUND', message: 'not open' } }), + ); + await sendRemoteCapture( + endpoint, + request('start', '/client/current.trace'), + stateDir, + async (req) => confirmed(req), + ); + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + const answer = confirmed(req); + expect( + (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + ).toBe('/client/current.trace'); + return answer; + }); +}); + +test('a late failed start cannot make a newer confirmed destination uncertain', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + let firstSent!: () => void; + const firstReachedDaemon = new Promise((resolve) => (firstSent = resolve)); + let failFirst!: () => void; + const firstCanFail = new Promise((resolve) => (failFirst = resolve)); + const first = sendRemoteCapture( + endpoint, + request('start', '/client/old.trace'), + stateDir, + async () => { + firstSent(); + await firstCanFail; + return { ok: false, error: { code: 'COMMAND_FAILED', message: 'uncertain' } }; + }, + ); + await firstReachedDaemon; + await sendRemoteCapture(endpoint, request('start', '/client/new.trace'), stateDir, async (req) => + confirmed(req), + ); + failFirst(); + await first; + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + const answer = confirmed(req); + expect( + (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + ).toBe('/client/new.trace'); + return answer; + }); +}); + +test('a delayed close does not retire a capture confirmed after the close was sent', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture(endpoint, request('start', '/client/old.trace'), stateDir, async (req) => + confirmed(req), + ); + let releaseClose!: () => void; + const closeCanFinish = new Promise((resolve) => (releaseClose = resolve)); + let closeReachedDaemon!: () => void; + const closeWasSent = new Promise((resolve) => (closeReachedDaemon = resolve)); + const close = sendRemoteCapture( + endpoint, + { ...request('stop'), command: 'close', positionals: [] }, + stateDir, + async () => { + closeReachedDaemon(); + await closeCanFinish; + return success; + }, + ); + await closeWasSent; + await sendRemoteCapture(endpoint, request('start', '/client/new.trace'), stateDir, async (req) => + confirmed(req), + ); + releaseClose(); + await close; + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + const answer = confirmed(req); + expect( + (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + ).toBe('/client/new.trace'); + return answer; + }); +}); + test('missing or mismatched stop confirmation cannot select a saved path', async () => { const stateDir = mkdtempForTestSync('capture-destination-'); await sendRemoteCapture( diff --git a/packages/remote/src/capture-destination-record.ts b/packages/remote/src/capture-destination-record.ts index 65a16969591..d3eeafe8aae 100644 --- a/packages/remote/src/capture-destination-record.ts +++ b/packages/remote/src/capture-destination-record.ts @@ -5,7 +5,7 @@ import type { DaemonWireRequest } from '@agent-device/contracts/command'; import { leaseScopeFromRequest } from '@agent-device/contracts/lease-scope'; import { parsePerfRuntimeRequest } from '@agent-device/capture-kit/perf-runtime-plan'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; -import { CAPTURE_IDENTITY_REASONS } from '@agent-device/kernel/errors'; +import { AppError, CAPTURE_IDENTITY_REASONS } from '@agent-device/kernel/errors'; import { acquireProcessLock, publishFileSync, withProcessLock } from '@agent-device/host-kit/file'; import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; @@ -117,11 +117,9 @@ function settleRecord(file: string, record: RecordState): void { else writeRecord(file, record); } -function isActiveCaptureRefusal(response: DaemonResponse | undefined): boolean { - return ( - response?.ok === false && - response.error.details?.reason === CAPTURE_IDENTITY_REASONS.alreadyActive.reason - ); +function refusalDetails(response: DaemonResponse | undefined, failure: unknown) { + if (response?.ok === false) return response.error.details; + return failure instanceof AppError ? failure.details : undefined; } function confirmedStartDestination( @@ -140,6 +138,7 @@ function confirmedStartDestination( function activeAfterStart( current: RecordState, response: DaemonResponse | undefined, + failure: unknown, generation: string, destination: string | undefined, order: number, @@ -148,23 +147,32 @@ function activeAfterStart( if (order < (active?.order ?? 0)) return active; if (response?.ok === true) return confirmedStartDestination(response, generation, destination, order); - if (response?.ok === false && isActiveCaptureRefusal(response)) - return response.error.details?.clientCaptureId === active?.generation ? active : undefined; + const details = refusalDetails(response, failure); + if (details?.reason === CAPTURE_IDENTITY_REASONS.alreadyActive.reason) + return details.clientCaptureId === active?.generation ? active : undefined; return active; } function recordAfterStart( current: RecordState, response: DaemonResponse | undefined, + failure: unknown, generation: string, destination: string | undefined, order: number, ): RecordState { - const active = activeAfterStart(current, response, generation, destination, order); + const active = activeAfterStart(current, response, failure, generation, destination, order); + const details = refusalDetails(response, failure); + const confirmed = response?.ok === true && response.data?.clientCaptureId === generation; + const olderThanActive = order < (current.active?.order ?? 0); return { ...(active ? { active } : {}), pending: current.pending.filter((candidate) => candidate.generation !== generation), - uncertain: current.uncertain || (response?.ok !== true && !isActiveCaptureRefusal(response)), + uncertain: olderThanActive + ? current.uncertain + : confirmed + ? false + : current.uncertain || details?.reason !== CAPTURE_IDENTITY_REASONS.alreadyActive.reason, nextOrder: current.nextOrder, }; } @@ -193,9 +201,10 @@ export async function sendRemoteCapture( ): Promise { const capture = captureOf(req); if (!capture) { + const closedRecords = + req.command === 'close' ? await snapshotSessionCaptures(baseUrl, req, stateDir) : undefined; const response = await send(req); - if (response.ok && req.command === 'close') - await retireClosedSessionCaptures(baseUrl, req, stateDir); + if (response.ok && closedRecords) await retireClosedSessionCaptures(closedRecords); return response; } const file = recordFile(stateDir, baseUrl, req, capture.family); @@ -210,8 +219,15 @@ export async function sendRemoteCapture( ? req : { ...req, meta: { ...req.meta, captureId: active.generation } }; stopGenerations.set(sent, { file, generation: active.generation }); - const response = await send(sent); - if (!response.ok && response.error.details?.reason === CAPTURE_IDENTITY_REASONS.mismatch.reason) + let response: DaemonResponse; + try { + response = await send(sent); + } catch (error) { + if (refusalDetails(undefined, error)?.reason === CAPTURE_IDENTITY_REASONS.mismatch.reason) + await retireSuccessfulCaptureStop(sent); + throw error; + } + if (refusalDetails(response, undefined)?.reason === CAPTURE_IDENTITY_REASONS.mismatch.reason) await retireSuccessfulCaptureStop(sent); return response; } @@ -241,7 +257,10 @@ export async function sendRemoteCapture( await withRecordLock(file, async () => { const current = readRecord(file); if (!current?.pending.some((pending) => pending.generation === generation)) return; - settleRecord(file, recordAfterStart(current, response, generation, destination, order)); + settleRecord( + file, + recordAfterStart(current, response, failure, generation, destination, order), + ); }); if (threw) throw failure; if (!response) throw new TypeError('Capture start settled without a response'); @@ -289,22 +308,35 @@ export async function confirmedCaptureStopRequest( }; } -async function retireClosedSessionCaptures( +async function snapshotSessionCaptures( baseUrl: string, req: DaemonWireRequest, stateDir: string, -): Promise { - if (req.command !== 'close') return; +): Promise> { const dir = sessionRecordDir(stateDir, baseUrl, req); let entries: string[]; try { entries = fs.readdirSync(dir).filter((entry) => entry.endsWith('.json')); } catch (error) { - if ((error as NodeJS.ErrnoException).code === 'ENOENT') return; + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return new Map(); throw error; } + const records = new Map(); for (const entry of entries) { const file = path.join(dir, entry); - await withRecordLock(file, async () => fs.rmSync(file, { force: true })); + await withRecordLock(file, async () => { + const current = readRecord(file); + if (current) records.set(file, JSON.stringify(current)); + }); + } + return records; +} + +async function retireClosedSessionCaptures(records: ReadonlyMap): Promise { + for (const [file, beforeClose] of records) { + await withRecordLock(file, async () => { + const current = readRecord(file); + if (current && JSON.stringify(current) === beforeClose) fs.rmSync(file, { force: true }); + }); } } From 9515bb3619fbec71f91ff8e47efd776b6b1ed4a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 01:32:52 +0100 Subject: [PATCH 44/55] fix(maestro): bound multiline selector matching and preserve exact matches --- .../daemon-runtime-port-observation.ts | 1 + .../runtime-selector-resolution.test.ts | 52 ++++++++++++- .../__tests__/runtime-targets-typed.test.ts | 40 ++++++++++ .../internal/__tests__/selector-regex.test.ts | 21 ++++-- .../internal/runtime-selector-resolution.ts | 50 +++++++++++-- .../src/internal/runtime-target-policy.ts | 74 +++++++++++++++---- .../src/internal/runtime-target-ranking.ts | 22 ++++-- .../maestro/src/internal/runtime-targets.ts | 24 +++++- .../maestro/src/internal/selector-regex.ts | 68 ++++++++++++----- website/docs/docs/run-maestro-flows.md | 2 +- 10 files changed, 298 insertions(+), 56 deletions(-) diff --git a/packages/maestro/src/daemon-port/daemon-runtime-port-observation.ts b/packages/maestro/src/daemon-port/daemon-runtime-port-observation.ts index df6e7071427..c9d7ed5d8e8 100644 --- a/packages/maestro/src/daemon-port/daemon-runtime-port-observation.ts +++ b/packages/maestro/src/daemon-port/daemon-runtime-port-observation.ts @@ -118,6 +118,7 @@ function resolveTargetFromSnapshot(params: { params.platform, { interactiveBounds: params.mode === 'tap', + confirmedUnindexedExistence: params.mode === 'observe', presentation: presentation ? { snapshot: interactiveSnapshot, diff --git a/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts b/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts index 2add1b7953c..7da724862c1 100644 --- a/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts +++ b/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts @@ -55,14 +55,62 @@ test('rejects cyclic selector graphs explicitly', () => { expect(() => resolver.resolve(selector)).toThrow(/cannot contain cycles/); }); -test('refuses uncertain multiline regex candidates before ordered target selection', () => { +test('matches a complete interior multiline span before ordered target selection', () => { const snapshot = makeSnapshot([ { index: 0, label: 'prefix\nstart\nmiddle\nend\nsuffix' }, { index: 1, label: 'start\nend' }, ]); const resolver = createMaestroSnapshotResolver(snapshot); - expect(() => resolver.resolve({ text: 'start.*end', index: 0 })).toThrow( + expect( + resolver.resolve({ text: 'start.*end', index: 0 }).indexed.map((node) => node.index), + ).toEqual([0]); +}); + +test('a nonmatching multiline node does not prevent a later confirmed selector match', () => { + const resolver = createMaestroSnapshotResolver( + makeSnapshot([ + { index: 0, label: 'Welcome back\nPlease log in' }, + { index: 1, label: 'Sign in' }, + ]), + ); + expect(resolver.resolve({ text: '.*Sign in.*' }).matches.map((node) => node.index)).toEqual([1]); +}); + +test('an exact long selector checks every candidate before refusing regex execution', () => { + const pattern = `Total: 12.5 ${'x'.repeat(300)}`; + const resolver = createMaestroSnapshotResolver( + makeSnapshot([ + { index: 0, label: `${pattern} extra` }, + { index: 1, label: ` ${pattern} ` }, + ]), + ); + expect(resolver.resolve({ text: pattern }).matches.map((node) => node.index)).toEqual([1]); + expect(() => resolver.resolve({ text: `${pattern} missing` })).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); +}); + +test('a confirmed unindexed match wins over uncertainty but an index still refuses', () => { + const snapshot = makeSnapshot([ + { index: 0, label: 'Header\n'.repeat(10_000) }, + { index: 1, label: 'Ready' }, + { index: 2, label: 'Header\n'.repeat(10_000), identifier: 'Ready' }, + ]); + const resolver = createMaestroSnapshotResolver( + snapshot, + {}, + { confirmedUnindexedExistence: true }, + ); + expect(resolver.resolve({ text: '.*Ready.*' }).matches.map((node) => node.index)).toEqual([1, 2]); + expect(() => resolver.resolve({ text: '.*Ready.*', index: 0 })).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); + expect(() => createMaestroSnapshotResolver(snapshot).resolve({ text: '.*Ready.*' })).toThrow( expect.objectContaining({ details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), }), diff --git a/packages/maestro/src/internal/__tests__/runtime-targets-typed.test.ts b/packages/maestro/src/internal/__tests__/runtime-targets-typed.test.ts index 457bc2afb35..416df73a4fd 100644 --- a/packages/maestro/src/internal/__tests__/runtime-targets-typed.test.ts +++ b/packages/maestro/src/internal/__tests__/runtime-targets-typed.test.ts @@ -180,6 +180,46 @@ test('reports matched-but-invisible targets with a typed no-visible-match reason }); }); +test('a hidden confirmed match cannot hide uncertainty in a visible observation candidate', () => { + const snapshot = makeSnapshot([ + { index: 0, type: 'Application', rect: { x: 0, y: 0, width: 320, height: 640 } }, + { + index: 1, + parentIndex: 0, + label: 'Ready', + rect: { x: 16, y: 20, width: 120, height: 44 }, + visibleToUser: false, + }, + { + index: 2, + parentIndex: 0, + label: 'Header\n'.repeat(10_000), + rect: { x: 16, y: 80, width: 120, height: 44 }, + }, + ]); + + expect(() => + resolveMaestroTargetFromSnapshot(snapshot, { selector: { text: '.*Ready.*' } }, 'android', { + confirmedUnindexedExistence: true, + }), + ).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); + + const visibleMatch = makeSnapshot([ + snapshot.nodes[0]!, + { ...snapshot.nodes[1]!, visibleToUser: true }, + snapshot.nodes[2]!, + ]); + expect( + resolveMaestroTargetFromSnapshot(visibleMatch, { selector: { text: '.*Ready.*' } }, 'android', { + confirmedUnindexedExistence: true, + }), + ).toMatchObject({ ok: true, node: { index: 1 } }); +}); + test('keeps Maestro-visible app content matchable while a React Native overlay is present', () => { const snapshot = makeSnapshot([ { diff --git a/packages/maestro/src/internal/__tests__/selector-regex.test.ts b/packages/maestro/src/internal/__tests__/selector-regex.test.ts index c0f9ee1acd9..f89ed29412b 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -24,6 +24,8 @@ test('matches Maestro regex as case-insensitive full patterns', () => { test.each([ '(a+)+', '(a|aa)+', + '(?:(?:a|aa))*', + '(?:(?:a|ab)(?:c|bc))*', 'a*a*', 'a*b*a*', '.*a.*b', @@ -103,17 +105,26 @@ test('multiline regex matches whole values and individual lines without retrying expect(matchesMaestroRegex('start\nmiddle\nend', 'start.*end')).toBe(true); expect(matchesMaestroRegex('before\nReady\nafter', 'Ready')).toBe(true); expect(matchesMaestroRegex('before\nReady\nafter', '.*Ready.*')).toBe(true); + expect(matchesMaestroRegex('prefix\nstart\nmiddle\nend\nsuffix', 'start.*end')).toBe(true); + for (const pattern of ['.*Sign in.*', 'Sign.*', 'Item .', String.raw`Hello\s+World`]) { + expect(matchesMaestroRegex('Welcome back\nPlease log in', pattern)).toBe(false); + } + expect(matchesMaestroRegex('x\nx', '[^x]+')).toBe(false); expect(matchesMaestroRegex('a\n'.repeat(192_000), 'a+Z')).toBe(false); expect(() => matchesMaestroRegex('a\n'.repeat(192_000), '.*Z')).toThrow( expect.objectContaining({ details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), }), ); - expect(() => matchesMaestroRegex('prefix\nstart\nmiddle\nend\nsuffix', 'start.*end')).toThrow( - expect.objectContaining({ - details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), - }), - ); +}); + +test('invalid regex syntax uses whole-value literal equality', () => { + expect(matchesMaestroRegex('[', '[')).toBe(true); + expect(matchesMaestroRegex('prefix\n[\nsuffix', '[')).toBe(false); +}); + +test('CR and LF each provide a multiline anchor boundary', () => { + expect(matchesMaestroRegex('one\r\ntwo', '^$')).toBe(true); }); test('escaped brackets and braces match literal node text', () => { diff --git a/packages/maestro/src/internal/runtime-selector-resolution.ts b/packages/maestro/src/internal/runtime-selector-resolution.ts index c4b14cb9039..053db632d14 100644 --- a/packages/maestro/src/internal/runtime-selector-resolution.ts +++ b/packages/maestro/src/internal/runtime-selector-resolution.ts @@ -11,13 +11,17 @@ import { selectMaestroPositionMatches, type MaestroPositionRelation, } from './runtime-target-position.ts'; -import { matchesMaestroTypedSelector } from './runtime-target-policy.ts'; +import { + assertLongMaestroSelectorsHaveExactCandidates, + matchesMaestroTypedSelector, +} from './runtime-target-policy.ts'; export type MaestroSelectorResolution = { /** Relation-composed matches in snapshot order, before this selector's own index. */ readonly matches: SnapshotNode[]; /** Matches after applying this selector's own index or no-index ordering policy. */ readonly indexed: SnapshotNode[]; + readonly uncertain?: AppError; }; export type MaestroResolutionProbe = { @@ -31,6 +35,7 @@ export type MaestroResolutionProbe = { export type MaestroResolutionOptions = { orderUnindexed?: (matches: readonly SnapshotNode[]) => SnapshotNode[]; + confirmedUnindexedExistence?: boolean; }; export type MaestroSnapshotResolver = { @@ -54,6 +59,7 @@ export function createMaestroSnapshotResolver( probe.onVisibilityContextCreated?.(); const selectorCache = new WeakMap(); const resolving = new WeakSet(); + let resolutionDepth = 0; const ancestorIndexesByNode = new WeakMap>(); const positionCaches = new Map< MaestroPositionRelation, @@ -117,23 +123,31 @@ export function createMaestroSnapshotResolver( throw new AppError('INVALID_ARGS', 'Maestro selector relations cannot contain cycles.'); } resolving.add(selector); - probe.onSelectorComputed?.(selector); + const confirmedUnindexedExistence = + resolutionDepth === 0 && + options.confirmedUnindexedExistence === true && + selector.index === undefined; + resolutionDepth += 1; try { - const matches = resolveWithoutOwnIndex( + probe.onSelectorComputed?.(selector); + const { matches, uncertain } = resolveWithoutOwnIndex( snapshot, selector, parentOf, ancestorIndexes, resolve, resolvePositionIndexes, + confirmedUnindexedExistence, ); const resolution = { matches, indexed: selectMaestroIndexedMatches(matches, selector.index, options.orderUnindexed), + ...(uncertain ? { uncertain } : {}), }; selectorCache.set(selector, resolution); return resolution; } finally { + resolutionDepth -= 1; resolving.delete(selector); } }; @@ -154,7 +168,8 @@ function resolveWithoutOwnIndex( ancestorIndexes: (node: SnapshotNode) => ReadonlySet, resolve: ResolveSelector, resolvePositionIndexes: ResolvePositionIndexes, -): SnapshotNode[] { + confirmedUnindexedExistence: boolean, +): { matches: SnapshotNode[]; uncertain?: AppError } { const { index: _index, childOf, @@ -166,9 +181,27 @@ function resolveWithoutOwnIndex( containsDescendants, ...leaf } = selector; - let matches = hasMaestroLeafSelectorFields(leaf) - ? snapshot.nodes.filter((node) => matchesMaestroTypedSelector(node, leaf)) - : [...snapshot.nodes]; + let uncertain: AppError | undefined; + let matches: SnapshotNode[]; + if (hasMaestroLeafSelectorFields(leaf)) { + assertLongMaestroSelectorsHaveExactCandidates(snapshot.nodes, leaf); + matches = snapshot.nodes.filter((node) => { + try { + return matchesMaestroTypedSelector(node, leaf); + } catch (error) { + if ( + error instanceof AppError && + error.details?.reason === 'maestro_selector_regex_indeterminate' + ) { + uncertain ??= error; + return false; + } + throw error; + } + }); + } else { + matches = [...snapshot.nodes]; + } if (childOf) { const parentIndexes = new Set(resolve(childOf).indexed.map((node) => node.index)); @@ -195,7 +228,8 @@ function resolveWithoutOwnIndex( const relatedIndexes = resolvePositionIndexes(relation, anchor); matches = matches.filter((node) => relatedIndexes.has(node.index)); } - return matches; + if (uncertain && (!confirmedUnindexedExistence || matches.length === 0)) throw uncertain; + return { matches, ...(uncertain ? { uncertain } : {}) }; } function collectContainingAncestorIndexes( diff --git a/packages/maestro/src/internal/runtime-target-policy.ts b/packages/maestro/src/internal/runtime-target-policy.ts index a898d8be12b..11d3038e9c7 100644 --- a/packages/maestro/src/internal/runtime-target-policy.ts +++ b/packages/maestro/src/internal/runtime-target-policy.ts @@ -1,13 +1,14 @@ +import { AppError } from '@agent-device/kernel/errors'; +import type { SnapshotNode } from '@agent-device/kernel/snapshot'; +import type { SnapshotVisibility } from '@agent-device/contracts/snapshot'; import type { MaestroLeafSelector, MaestroRelationalSelectorFields } from './program-ir.ts'; +import { matchesMaestroRegex, requiresExactMaestroRegexMatch } from './selector-regex.ts'; +import { extractNodeText } from './shared.ts'; +import { isMaestroNodeVisible } from './snapshot-policy.ts'; export type MaestroFlatSelector = MaestroLeafSelector & { [Key in keyof MaestroRelationalSelectorFields]?: never; }; -import type { SnapshotNode } from '@agent-device/kernel/snapshot'; -import type { SnapshotVisibility } from '@agent-device/contracts/snapshot'; -import { matchesMaestroRegex } from './selector-regex.ts'; -import { extractNodeText } from './shared.ts'; -import { isMaestroNodeVisible } from './snapshot-policy.ts'; export type MaestroRuntimePlatform = 'ios' | 'android'; @@ -28,13 +29,13 @@ export function matchesMaestroTypedSelector( const textTerms = [ selector.id === undefined ? undefined - : matchesMaestroSelectorValue(node.identifier, selector.id), + : tryMatchMaestroSelectorValue(node.identifier, selector.id), selector.text === undefined ? undefined : matchesMaestroVisibleText(node, selector.text), - ].filter((matched): matched is boolean => matched !== undefined); + ].filter((matched): matched is boolean | AppError => matched !== undefined); if (textTerms.length === 0 && selector.enabled === undefined && selector.selected === undefined) { return false; } - if (textTerms.some((matched) => !matched)) return false; + if (textTerms.includes(false)) return false; if (selector.enabled !== undefined && Boolean(node.enabled !== false) !== selector.enabled) { return false; @@ -42,9 +43,34 @@ export function matchesMaestroTypedSelector( if (selector.selected !== undefined && Boolean(node.selected === true) !== selector.selected) { return false; } + const uncertain = textTerms.find((term): term is AppError => term instanceof AppError); + if (uncertain) throw uncertain; return true; } +export function assertLongMaestroSelectorsHaveExactCandidates( + nodes: readonly SnapshotNode[], + selector: MaestroFlatSelector, +): void { + const { id, text } = selector; + if ( + id !== undefined && + requiresExactMaestroRegexMatch(id) && + !nodes.some((node) => matchesMaestroRegex(node.identifier ?? '', id, true)) + ) { + matchesMaestroRegex('', id); + } + if ( + text !== undefined && + requiresExactMaestroRegexMatch(text) && + !nodes.some((node) => + visibleTextValues(node).some((value) => matchesMaestroRegex(value, text, true)), + ) + ) { + matchesMaestroRegex('', text); + } +} + export function filterVisibleMaestroMatches(params: { visibility: SnapshotVisibility; matches: SnapshotNode[]; @@ -55,12 +81,32 @@ export function filterVisibleMaestroMatches(params: { ); } -function matchesMaestroSelectorValue(value: string | undefined, query: string): boolean { - return matchesMaestroRegex(value ?? '', query); +function tryMatchMaestroSelectorValue(value: string | undefined, query: string): boolean | AppError { + try { + return matchesMaestroRegex(value ?? '', query, true); + } catch (error) { + if ( + error instanceof AppError && + error.details?.reason === 'maestro_selector_regex_indeterminate' + ) { + return error; + } + throw error; + } } -function matchesMaestroVisibleText(node: SnapshotNode, query: string): boolean { - return [node.label, extractNodeText(node), node.identifier] - .filter((value): value is string => Boolean(value)) - .some((value) => matchesMaestroSelectorValue(value, query)); +function visibleTextValues(node: SnapshotNode): string[] { + return [node.label, extractNodeText(node), node.identifier].filter( + (value): value is string => Boolean(value), + ); +} + +function matchesMaestroVisibleText(node: SnapshotNode, query: string): boolean | AppError { + let uncertain: AppError | undefined; + for (const value of visibleTextValues(node)) { + const result = tryMatchMaestroSelectorValue(value, query); + if (result === true) return true; + if (result instanceof AppError) uncertain ??= result; + } + return uncertain ?? false; } diff --git a/packages/maestro/src/internal/runtime-target-ranking.ts b/packages/maestro/src/internal/runtime-target-ranking.ts index 56619125d38..4ac762a7091 100644 --- a/packages/maestro/src/internal/runtime-target-ranking.ts +++ b/packages/maestro/src/internal/runtime-target-ranking.ts @@ -1,4 +1,5 @@ import type { Rect, SnapshotNode } from '@agent-device/kernel/snapshot'; +import type { AppError } from '@agent-device/kernel/errors'; import type { SnapshotState } from '@agent-device/contracts/snapshot-model'; import { isPositiveFiniteRect } from '@agent-device/kernel/rect'; import { normalizeType, type SnapshotVisibility } from '@agent-device/contracts/snapshot'; @@ -27,18 +28,23 @@ export type MaestroRankedCandidates = { readonly ranked: SnapshotNode[]; readonly parentMatched: boolean; readonly clickability: MaestroClickabilityDecision; + readonly uncertain?: AppError; }; -export type MaestroCandidateMatches = Pick; +export type MaestroCandidateMatches = Pick< + MaestroRankedCandidates, + 'matches' | 'parentMatched' | 'uncertain' +>; export function rankMaestroCandidates( snapshot: SnapshotState, selector: MaestroSelector, platform: MaestroRuntimePlatform, probe: MaestroResolutionProbe = {}, + confirmedUnindexedExistence = false, ): MaestroRankedCandidates { const clickability = resolveMaestroClickability(snapshot, platform); - const resolver = createMaestroResolver(snapshot, clickability, probe); + const resolver = createMaestroResolver(snapshot, clickability, probe, confirmedUnindexedExistence); const scoped = matchMaestroCandidatesWithResolver(selector, resolver); const visible = filterVisibleMaestroMatches({ visibility: resolver.visibility, @@ -63,23 +69,27 @@ export function matchMaestroCandidatesWithResolver( selector: MaestroSelector, resolver: MaestroSnapshotResolver, ): MaestroCandidateMatches { - const matches = resolver.resolve(selector).matches; + const { matches, uncertain } = resolver.resolve(selector); const parentMatched = selector.childOf === undefined || resolver.resolve(selector.childOf).indexed.length > 0; - return { matches, parentMatched }; + return { matches, parentMatched, ...(uncertain ? { uncertain } : {}) }; } export function createMaestroResolver( snapshot: SnapshotState, clickability: MaestroClickabilityDecision | undefined, probe: MaestroResolutionProbe = {}, + confirmedUnindexedExistence = false, ): MaestroSnapshotResolver { return createMaestroSnapshotResolver( snapshot, probe, clickability - ? { orderUnindexed: (matches) => orderMaestroClickableFirst(matches, clickability) } - : {}, + ? { + orderUnindexed: (matches) => orderMaestroClickableFirst(matches, clickability), + confirmedUnindexedExistence, + } + : { confirmedUnindexedExistence }, ); } diff --git a/packages/maestro/src/internal/runtime-targets.ts b/packages/maestro/src/internal/runtime-targets.ts index c904bbb5062..c325301e2bb 100644 --- a/packages/maestro/src/internal/runtime-targets.ts +++ b/packages/maestro/src/internal/runtime-targets.ts @@ -66,6 +66,7 @@ export function resolveMaestroTargetFromSnapshot( options: { interactiveBounds?: boolean; presentation?: MaestroInteractivePresentation; + confirmedUnindexedExistence?: boolean; } = {}, ): MaestroTargetResolution { const presentedNodes = @@ -73,8 +74,19 @@ export function resolveMaestroTargetFromSnapshot( ? createPresentedNodeLookup(options.presentation) : undefined; const candidates = presentedNodes - ? rankPresentedMaestroCandidates(snapshot, query, presentedNodes) - : rankMaestroCandidates(snapshot, query.selector, platform); + ? rankPresentedMaestroCandidates( + snapshot, + query, + presentedNodes, + options.confirmedUnindexedExistence, + ) + : rankMaestroCandidates( + snapshot, + query.selector, + platform, + {}, + options.confirmedUnindexedExistence, + ); if (!candidates.parentMatched) { return { ok: false, @@ -89,6 +101,7 @@ export function resolveMaestroTargetFromSnapshot( : selectMaestroSnapshotMatch(rankedMatches, query.selector.index)?.node; const evidence = buildMaestroTargetEvidence(query, matches, rankedMatches, target); if (!target) { + if (candidates.uncertain) throw candidates.uncertain; return failedTargetResolution(query, matches, rankedMatches, evidence); } const presentedTarget = presentedNodes @@ -99,6 +112,7 @@ export function resolveMaestroTargetFromSnapshot( ? (presentedTarget?.rect ?? semanticRect) : (semanticRect ?? presentedTarget?.rect); if (!rect) { + if (candidates.uncertain) throw candidates.uncertain; return { ok: false, message: 'Maestro target did not provide usable geometry.', @@ -156,12 +170,16 @@ function rankPresentedMaestroCandidates( snapshot: SnapshotState, query: MaestroSnapshotTargetQuery, presentedNodes: ReturnType, + confirmedUnindexedExistence = false, ): MaestroRankedCandidates { const clickability = resolveMaestroClickability(snapshot, 'ios'); const resolver = createMaestroSnapshotResolver( snapshot, {}, - { orderUnindexed: (matches) => orderMaestroClickableFirst(matches, clickability) }, + { + orderUnindexed: (matches) => orderMaestroClickableFirst(matches, clickability), + confirmedUnindexedExistence, + }, ); const scoped = matchMaestroCandidatesWithResolver(query.selector, resolver); const visible = scoped.matches.filter(presentedNodes.isVisible); diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index eed6639d539..a941ab49e5b 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -14,25 +14,33 @@ const MAX_PATTERN_LENGTH = 256; const MAX_COUNTED_REPETITION = 10_000; const MAX_CACHED_PATTERNS = 128; const MAX_PATTERN_PATHS = 32; +const MAX_MULTILINE_VALUE_LENGTH = 16_384; +const MAX_MULTILINE_WORK = 131_072; const parser = new RegExpParser(); type RegexElement = AST.Alternative['elements'][number]; -type LiteralMatcher = { literal: string; lineRegex?: RegExp }; -type Matcher = LiteralMatcher | { regex: RegExp; canSpanLines: boolean }; +type LiteralMatcher = { literal: string; wholeOnly: boolean; lineRegex?: RegExp }; +type Matcher = LiteralMatcher | { regex: RegExp; multilineRegex: RegExp; canSpanLines: boolean }; const matcherCache = new Map(); -export function matchesMaestroRegex(value: string, pattern: string): boolean { - if ( - pattern.length > MAX_PATTERN_LENGTH && - hasRegexSyntax(pattern) && - normalizeText(value) === normalizeText(pattern) - ) { - return true; +export function requiresExactMaestroRegexMatch(pattern: string): boolean { + return pattern.length > MAX_PATTERN_LENGTH && hasRegexSyntax(pattern); +} + +export function matchesMaestroRegex( + value: string, + pattern: string, + deferLongPatternRefusal = false, +): boolean { + if (requiresExactMaestroRegexMatch(pattern)) { + if (normalizeText(value) === normalizeText(pattern)) return true; + if (deferLongPatternRefusal) return false; + unsafeMaestroRegex(); } const matcher = matcherForPattern(pattern); if ('literal' in matcher) return matchesLiteral(value, matcher); if (normalizeText(value) === normalizeText(pattern)) return true; - if (matcher.regex.test(value)) return true; - if (!hasLineTerminator(value)) return false; + if (!hasLineTerminator(value)) return matcher.regex.test(value); + if (boundedMultilineWork(value)) return matcher.multilineRegex.test(value); if (matchesAnyLine(value, matcher.regex)) return true; if (matcher.canSpanLines) indeterminateMaestroRegex(); return false; @@ -40,6 +48,7 @@ export function matchesMaestroRegex(value: string, pattern: string): boolean { function matchesLiteral(value: string, matcher: LiteralMatcher): boolean { if (normalizeText(value) === normalizeText(matcher.literal)) return true; + if (matcher.wholeOnly) return false; if (matcher.literal.length > MAX_PATTERN_LENGTH) { return matchesLongLiteralLine(value, matcher.literal); } @@ -89,12 +98,21 @@ function hasLineTerminator(value: string): boolean { return /[\n\r\u2028\u2029]/.test(value); } +function boundedMultilineWork(value: string): boolean { + if (value.length > MAX_MULTILINE_VALUE_LENGTH) return false; + let boundaries = 1; + for (const character of value) { + if (isLineTerminator(character)) boundaries += 1; + if (boundaries * value.length > MAX_MULTILINE_WORK) return false; + } + return true; +} + function matchesAnyLine(value: string, regex: RegExp): boolean { let start = 0; for (let index = 0; index < value.length; index += 1) { if (!isLineTerminator(value[index])) continue; if (regex.test(value.slice(start, index))) return true; - if (value[index] === '\r' && value[index + 1] === '\n') index += 1; start = index + 1; } return regex.test(value.slice(start)); @@ -106,12 +124,22 @@ function matcherForPattern(pattern: string): Matcher { const literal = literalFromMaestroRegex(pattern); let matcher: Matcher; if (literal !== undefined) { - matcher = { literal }; + let wholeOnly = false; + try { + new RegExp(pattern); + } catch { + wholeOnly = true; + } + matcher = { literal, wholeOnly }; } else { if (pattern.length > MAX_PATTERN_LENGTH) unsafeMaestroRegex(); const canSpanLines = assertBoundedMaestroPattern(pattern); try { - matcher = { regex: new RegExp(`^(?:${pattern})$`, 'is'), canSpanLines }; + matcher = { + regex: new RegExp(`^(?:${pattern})$`, 'is'), + multilineRegex: new RegExp(`^(?:${pattern})$`, 'ims'), + canSpanLines, + }; } catch { unsafeMaestroRegex(); } @@ -152,9 +180,15 @@ function assertBoundedMaestroPattern(pattern: string): boolean { ) { unsafeMaestroRegex(); } - if (node.element.type !== 'Group' && node.element.type !== 'CapturingGroup') return; - if (node.element.alternatives.length > 1) unsafeMaestroRegex(); - visitRegExpAST(node.element, { onQuantifierEnter: unsafeMaestroRegex }); + visitRegExpAST(node.element, { + onGroupEnter(group) { + if (group.alternatives.length > 1) unsafeMaestroRegex(); + }, + onCapturingGroupEnter(group) { + if (group.alternatives.length > 1) unsafeMaestroRegex(); + }, + onQuantifierEnter: unsafeMaestroRegex, + }); }, }); for (const alternative of parsed.alternatives) { diff --git a/website/docs/docs/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index f41c3f12c1e..96be0195221 100644 --- a/website/docs/docs/run-maestro-flows.md +++ b/website/docs/docs/run-maestro-flows.md @@ -30,7 +30,7 @@ Keep the target binding, such as `--platform ios`, on the `replay` or `test` com ## Boundaries -- Selector `id` and `text` match exact text before interpreting a safe pattern as a regular expression. A plain literal also matches one line of a multiline value. Regex patterns match a whole value or one line and can use groups, alternatives, character classes, and counted or disjoint repetitions. Backreferences, overlapping repetitions across literals or groups, quantified groups with alternatives or repetitions, excessive ambiguous groups, and counted repetitions over 10,000 fail with `maestro_selector_regex_unsafe`. Regex patterns over 256 characters also fail unless the full selector equals normalized node text, in which case regex is not executed. If a pattern could span lines but neither the whole value nor one line matches, the step fails with `maestro_selector_regex_indeterminate` rather than treating a possible partial cross-line match as absent. +- Selector `id` and `text` match exact text before interpreting a safe pattern as a regular expression. A plain literal also matches one line of a multiline value, while invalid regex syntax uses whole-value literal equality. Regex patterns match complete spans between line boundaries within a bounded value and can use groups, alternatives, character classes, and counted or disjoint repetitions. Backreferences, overlapping repetitions across literals or groups, quantified groups containing alternatives or repetitions at any depth, excessive ambiguous groups, and counted repetitions over 10,000 fail with `maestro_selector_regex_unsafe`. Regex patterns over 256 characters also fail unless the full selector equals normalized text in a snapshot node, in which case regex is not executed. When a line-spanning pattern exceeds the bounded multiline work budget, the step fails with `maestro_selector_regex_indeterminate` if no confirmed match settles the unindexed selector. - 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 624c3f2c0d5eee68f07ce5fe828e023f5f9f558d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 01:55:56 +0100 Subject: [PATCH 45/55] refactor(remote): separate capture dispatch paths --- .../remote/src/capture-destination-record.ts | 80 ++++++++++++------- 1 file changed, 51 insertions(+), 29 deletions(-) diff --git a/packages/remote/src/capture-destination-record.ts b/packages/remote/src/capture-destination-record.ts index d3eeafe8aae..73f16b752c0 100644 --- a/packages/remote/src/capture-destination-record.ts +++ b/packages/remote/src/capture-destination-record.ts @@ -10,6 +10,7 @@ import { acquireProcessLock, publishFileSync, withProcessLock } from '@agent-dev import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; type Capture = { action: 'start' | 'stop'; family: string }; +type Send = (req: DaemonWireRequest) => Promise; type Active = { generation: string; destination: string; order: number }; type Pending = { generation: string; order: number }; type RecordState = { active?: Active; pending: Pending[]; uncertain: boolean; nextOrder: number }; @@ -197,41 +198,62 @@ export async function sendRemoteCapture( baseUrl: string, req: DaemonWireRequest, stateDir: string, - send: (req: DaemonWireRequest) => Promise, + send: Send, ): Promise { const capture = captureOf(req); - if (!capture) { - const closedRecords = - req.command === 'close' ? await snapshotSessionCaptures(baseUrl, req, stateDir) : undefined; - const response = await send(req); - if (response.ok && closedRecords) await retireClosedSessionCaptures(closedRecords); - return response; - } + if (!capture) return await sendWithoutCapture(baseUrl, req, stateDir, send); const file = recordFile(stateDir, baseUrl, req, capture.family); - if (capture.action === 'stop') { - const active = await withRecordLock(file, async () => { - const current = readRecord(file); - return current?.pending.length === 0 && !current.uncertain ? current.active : undefined; - }); - if (!active) return await send(req); - const hasExplicitPath = typeof req.meta?.clientArtifactPaths?.outPath === 'string'; - const sent = hasExplicitPath - ? req - : { ...req, meta: { ...req.meta, captureId: active.generation } }; - stopGenerations.set(sent, { file, generation: active.generation }); - let response: DaemonResponse; - try { - response = await send(sent); - } catch (error) { - if (refusalDetails(undefined, error)?.reason === CAPTURE_IDENTITY_REASONS.mismatch.reason) - await retireSuccessfulCaptureStop(sent); - throw error; - } - if (refusalDetails(response, undefined)?.reason === CAPTURE_IDENTITY_REASONS.mismatch.reason) + return capture.action === 'stop' + ? await sendCaptureStop(file, req, send) + : await sendCaptureStart(file, req, send); +} + +async function sendWithoutCapture( + baseUrl: string, + req: DaemonWireRequest, + stateDir: string, + send: Send, +): Promise { + const closedRecords = + req.command === 'close' ? await snapshotSessionCaptures(baseUrl, req, stateDir) : undefined; + const response = await send(req); + if (response.ok && closedRecords) await retireClosedSessionCaptures(closedRecords); + return response; +} + +async function sendCaptureStop( + file: string, + req: DaemonWireRequest, + send: Send, +): Promise { + const active = await withRecordLock(file, async () => { + const current = readRecord(file); + return current?.pending.length === 0 && !current.uncertain ? current.active : undefined; + }); + if (!active) return await send(req); + const hasExplicitPath = typeof req.meta?.clientArtifactPaths?.outPath === 'string'; + const sent = hasExplicitPath + ? req + : { ...req, meta: { ...req.meta, captureId: active.generation } }; + stopGenerations.set(sent, { file, generation: active.generation }); + let response: DaemonResponse; + try { + response = await send(sent); + } catch (error) { + if (refusalDetails(undefined, error)?.reason === CAPTURE_IDENTITY_REASONS.mismatch.reason) await retireSuccessfulCaptureStop(sent); - return response; + throw error; } + if (refusalDetails(response, undefined)?.reason === CAPTURE_IDENTITY_REASONS.mismatch.reason) + await retireSuccessfulCaptureStop(sent); + return response; +} +async function sendCaptureStart( + file: string, + req: DaemonWireRequest, + send: Send, +): Promise { const generation = crypto.randomUUID(); const order = await withRecordLock(file, async () => { const current = readRecord(file); From 9a3762354354edf4ea452f77d06c122e36cc0add Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 01:56:05 +0100 Subject: [PATCH 46/55] chore(gates): isolate Maestro target ranking decisions --- .../src/internal/runtime-target-policy.ts | 9 ++- .../src/internal/runtime-target-ranking.ts | 7 +- .../maestro/src/internal/runtime-targets.ts | 75 +++++++++++++------ 3 files changed, 66 insertions(+), 25 deletions(-) diff --git a/packages/maestro/src/internal/runtime-target-policy.ts b/packages/maestro/src/internal/runtime-target-policy.ts index 11d3038e9c7..741aabc14a2 100644 --- a/packages/maestro/src/internal/runtime-target-policy.ts +++ b/packages/maestro/src/internal/runtime-target-policy.ts @@ -81,7 +81,10 @@ export function filterVisibleMaestroMatches(params: { ); } -function tryMatchMaestroSelectorValue(value: string | undefined, query: string): boolean | AppError { +function tryMatchMaestroSelectorValue( + value: string | undefined, + query: string, +): boolean | AppError { try { return matchesMaestroRegex(value ?? '', query, true); } catch (error) { @@ -96,8 +99,8 @@ function tryMatchMaestroSelectorValue(value: string | undefined, query: string): } function visibleTextValues(node: SnapshotNode): string[] { - return [node.label, extractNodeText(node), node.identifier].filter( - (value): value is string => Boolean(value), + return [node.label, extractNodeText(node), node.identifier].filter((value): value is string => + Boolean(value), ); } diff --git a/packages/maestro/src/internal/runtime-target-ranking.ts b/packages/maestro/src/internal/runtime-target-ranking.ts index 4ac762a7091..5326b0f3fb3 100644 --- a/packages/maestro/src/internal/runtime-target-ranking.ts +++ b/packages/maestro/src/internal/runtime-target-ranking.ts @@ -44,7 +44,12 @@ export function rankMaestroCandidates( confirmedUnindexedExistence = false, ): MaestroRankedCandidates { const clickability = resolveMaestroClickability(snapshot, platform); - const resolver = createMaestroResolver(snapshot, clickability, probe, confirmedUnindexedExistence); + const resolver = createMaestroResolver( + snapshot, + clickability, + probe, + confirmedUnindexedExistence, + ); const scoped = matchMaestroCandidatesWithResolver(selector, resolver); const visible = filterVisibleMaestroMatches({ visibility: resolver.visibility, diff --git a/packages/maestro/src/internal/runtime-targets.ts b/packages/maestro/src/internal/runtime-targets.ts index c325301e2bb..9462b5f3975 100644 --- a/packages/maestro/src/internal/runtime-targets.ts +++ b/packages/maestro/src/internal/runtime-targets.ts @@ -43,6 +43,8 @@ type MaestroInteractivePresentation = { presentedIndexesBySourceIndex: ReadonlyMap; }; +type PresentedNodeLookup = ReturnType; + export type MaestroTargetResolution = | { ok: true; @@ -73,20 +75,13 @@ export function resolveMaestroTargetFromSnapshot( platform === 'ios' && options.presentation ? createPresentedNodeLookup(options.presentation) : undefined; - const candidates = presentedNodes - ? rankPresentedMaestroCandidates( - snapshot, - query, - presentedNodes, - options.confirmedUnindexedExistence, - ) - : rankMaestroCandidates( - snapshot, - query.selector, - platform, - {}, - options.confirmedUnindexedExistence, - ); + const candidates = rankTargetCandidates( + snapshot, + query, + platform, + presentedNodes, + options.confirmedUnindexedExistence, + ); if (!candidates.parentMatched) { return { ok: false, @@ -126,17 +121,55 @@ export function resolveMaestroTargetFromSnapshot( node: target, rect, matches: rankedMatches.length, - dispatchCandidates: - platform === 'ios' && - query.allowAtomicSelectorDispatch && - !hasMaestroRecursiveRelations(query.selector) && - presentedNodes - ? countInteractionDispatchCandidates(semanticRect, rankedMatches, presentedTarget) - : 0, + dispatchCandidates: atomicDispatchCandidates( + platform, + query, + presentedNodes, + semanticRect, + rankedMatches, + presentedTarget, + ), evidence, }; } +function rankTargetCandidates( + snapshot: SnapshotState, + query: MaestroSnapshotTargetQuery, + platform: MaestroRuntimePlatform, + presentedNodes: PresentedNodeLookup | undefined, + confirmedUnindexedExistence: boolean | undefined, +): MaestroRankedCandidates { + if (presentedNodes) { + return rankPresentedMaestroCandidates( + snapshot, + query, + presentedNodes, + confirmedUnindexedExistence, + ); + } + return rankMaestroCandidates(snapshot, query.selector, platform, {}, confirmedUnindexedExistence); +} + +function atomicDispatchCandidates( + platform: MaestroRuntimePlatform, + query: MaestroSnapshotTargetQuery, + presentedNodes: PresentedNodeLookup | undefined, + semanticRect: Rect | undefined, + rankedMatches: SnapshotNode[], + presentedTarget: { node: SnapshotNode; rect: Rect } | null, +): number { + if ( + platform !== 'ios' || + !query.allowAtomicSelectorDispatch || + hasMaestroRecursiveRelations(query.selector) || + !presentedNodes + ) { + return 0; + } + return countInteractionDispatchCandidates(semanticRect, rankedMatches, presentedTarget); +} + export const hasMaestroRecursiveRelations = hasRecursiveRelations; function createPresentedNodeLookup(presentation: MaestroInteractivePresentation): { From ae98615e7a5fb4b23123e9a5659dad5ac0ec7b80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 03:26:08 +0100 Subject: [PATCH 47/55] fix(maestro): preserve bounded whole-value multiline matches --- packages/maestro/src/internal/__tests__/selector-regex.test.ts | 3 +++ packages/maestro/src/internal/selector-regex.ts | 3 +++ 2 files changed, 6 insertions(+) diff --git a/packages/maestro/src/internal/__tests__/selector-regex.test.ts b/packages/maestro/src/internal/__tests__/selector-regex.test.ts index f89ed29412b..e760292141c 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -106,6 +106,9 @@ test('multiline regex matches whole values and individual lines without retrying expect(matchesMaestroRegex('before\nReady\nafter', 'Ready')).toBe(true); expect(matchesMaestroRegex('before\nReady\nafter', '.*Ready.*')).toBe(true); expect(matchesMaestroRegex('prefix\nstart\nmiddle\nend\nsuffix', 'start.*end')).toBe(true); + const wholeValuePastRestartBudget = `start${'\ndetails'.repeat(150)}\nend`; + expect(wholeValuePastRestartBudget.length).toBe(1209); + expect(matchesMaestroRegex(wholeValuePastRestartBudget, 'start.*end')).toBe(true); for (const pattern of ['.*Sign in.*', 'Sign.*', 'Item .', String.raw`Hello\s+World`]) { expect(matchesMaestroRegex('Welcome back\nPlease log in', pattern)).toBe(false); } diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index a941ab49e5b..64e033dd186 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -40,6 +40,9 @@ export function matchesMaestroRegex( if ('literal' in matcher) return matchesLiteral(value, matcher); if (normalizeText(value) === normalizeText(pattern)) return true; if (!hasLineTerminator(value)) return matcher.regex.test(value); + // A whole-value match has one anchored start. The work budget below limits how many + // line-boundary starts the multiline engine may try, not this bounded single start. + if (value.length <= MAX_MULTILINE_VALUE_LENGTH && matcher.regex.test(value)) return true; if (boundedMultilineWork(value)) return matcher.multilineRegex.test(value); if (matchesAnyLine(value, matcher.regex)) return true; if (matcher.canSpanLines) indeterminateMaestroRegex(); From 46650fa501e612c0a5c966440d5d91d488ef7804 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 04:57:09 +0100 Subject: [PATCH 48/55] fix(security): align guidance and focused assertions --- docs/agents/security.md | 8 +++++--- .../maestro/src/internal/__tests__/selector-regex.test.ts | 2 ++ .../proxy/src/daemon-proxy-credential-transport.test.ts | 4 +++- website/docs/docs/run-maestro-flows.md | 2 +- website/docs/docs/security-trust.md | 2 +- 5 files changed, 12 insertions(+), 6 deletions(-) diff --git a/docs/agents/security.md b/docs/agents/security.md index 908b3478c94..2f1f6d679a0 100644 --- a/docs/agents/security.md +++ b/docs/agents/security.md @@ -5,9 +5,9 @@ Reject daemon-chosen paths in scripts and remote record stops (#4518). Trace/perf uses caller paths. Unnamed captures get unique cwd names. Key trace/perf paths by endpoint, tenant, run, lease, session, and kind. On start, mark identity pending. -Restore the path only after a same-ID rejection. +If the daemon rejects a start with the same capture ID, restore the saved path. On pathless stop, send the client capture ID. -Use a saved path only after ID confirmation. +If the daemon confirms the live capture ID on stop, use the saved path. On unclear outcomes or ID mismatch, use a unique cwd name. After close or stop, retire the path. The daemon admits its state directory. Nobody trusts the network or other local users. @@ -18,5 +18,7 @@ ADR 0016 owns script destination writes and delivery limits. ## Proposed in #4669 -#4669's credential/state private-write proposal needs approval. +Until #4669 is approved, do not apply its credential and state private-write proposal. +The proposal creates credential, client state, and daemon state files under a verified state root. +It never writes through a link at the final name. Do not apply ADR 0016's path walk to screenshot `--out`, contact sheets, JUnit, traces, or recordings. diff --git a/packages/maestro/src/internal/__tests__/selector-regex.test.ts b/packages/maestro/src/internal/__tests__/selector-regex.test.ts index e760292141c..96baf1aff09 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -128,6 +128,8 @@ test('invalid regex syntax uses whole-value literal equality', () => { test('CR and LF each provide a multiline anchor boundary', () => { expect(matchesMaestroRegex('one\r\ntwo', '^$')).toBe(true); + expect(matchesMaestroRegex('one\rtwo', '^two$')).toBe(true); + expect(matchesMaestroRegex('one\ntwo', '^two$')).toBe(true); }); test('escaped brackets and braces match literal node text', () => { diff --git a/packages/proxy/src/daemon-proxy-credential-transport.test.ts b/packages/proxy/src/daemon-proxy-credential-transport.test.ts index 7bb2e997dff..6db49dd22f0 100644 --- a/packages/proxy/src/daemon-proxy-credential-transport.test.ts +++ b/packages/proxy/src/daemon-proxy-credential-transport.test.ts @@ -37,7 +37,9 @@ test('plain http upstream off loopback is refused ahead of any send', async () = const proxy = proxyFor('http://upstream.example.test:4310'); const response = await proxy.handle(health()); expect(response.status).toBe(400); - expect(await response.text()).not.toMatch(/daemon-secret/); + const body = await response.text(); + expect(JSON.parse(body)).toMatchObject({ ok: false, code: 'INVALID_ARGS' }); + expect(body).not.toMatch(/daemon-secret/); expect(atSend).toEqual([]); expect(stderr).not.toMatch(/daemon-secret|AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT/); }); diff --git a/website/docs/docs/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index 96be0195221..d99dacb17af 100644 --- a/website/docs/docs/run-maestro-flows.md +++ b/website/docs/docs/run-maestro-flows.md @@ -30,7 +30,7 @@ Keep the target binding, such as `--platform ios`, on the `replay` or `test` com ## Boundaries -- Selector `id` and `text` match exact text before interpreting a safe pattern as a regular expression. A plain literal also matches one line of a multiline value, while invalid regex syntax uses whole-value literal equality. Regex patterns match complete spans between line boundaries within a bounded value and can use groups, alternatives, character classes, and counted or disjoint repetitions. Backreferences, overlapping repetitions across literals or groups, quantified groups containing alternatives or repetitions at any depth, excessive ambiguous groups, and counted repetitions over 10,000 fail with `maestro_selector_regex_unsafe`. Regex patterns over 256 characters also fail unless the full selector equals normalized text in a snapshot node, in which case regex is not executed. When a line-spanning pattern exceeds the bounded multiline work budget, the step fails with `maestro_selector_regex_indeterminate` if no confirmed match settles the unindexed selector. +- Selector `id` and `text` match exact text before interpreting a safe pattern as a regular expression. A plain literal also matches one line of a multiline value, while invalid regex syntax uses whole-value literal equality. Regex patterns match complete spans between line boundaries within a bounded value and can use groups, alternatives, character classes, and counted or disjoint repetitions. Backreferences, lookahead and lookbehind assertions, overlapping repetitions across literals or groups, quantified groups containing alternatives or repetitions at any depth, excessive ambiguous groups, and counted repetitions over 10,000 fail with `maestro_selector_regex_unsafe`. Regex patterns over 256 characters also fail unless the full selector equals normalized text in a snapshot node, in which case regex is not executed. When a line-spanning pattern exceeds the bounded multiline work budget, the step fails with `maestro_selector_regex_indeterminate` if no confirmed match settles the unindexed selector. - 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. diff --git a/website/docs/docs/security-trust.md b/website/docs/docs/security-trust.md index a2db1ad9ae9..cb5e7391ac1 100644 --- a/website/docs/docs/security-trust.md +++ b/website/docs/docs/security-trust.md @@ -43,7 +43,7 @@ The supported remote setup keeps the daemon and proxy HTTP listeners on `127.0.0 In this setup the token and your device traffic travel between the two machines only inside TLS or SSH. See [Remote proxy setup](./remote-proxy.md) for the commands. -Before agent-device sends a credential to a plain `http://` URL whose host is not loopback (`localhost`, `127.0.0.0/8`, or `::1`), it refuses the connection with reason `insecure_credential_transport`. This applies to the remote daemon URL, the cloud URL, the Metro bridge URL, and the upstream URL of [`@agent-device/proxy`](https://www.npmjs.com/package/@agent-device/proxy) with its default transport. Upload tickets are already refused: if a ticket points to plain HTTP, for example because `--public-origin` is missing, the client does not use it and uploads through the daemon URL instead. +Before agent-device sends a credential to a plain `http://` URL whose host is not loopback (`localhost`, `127.0.0.0/8`, or `::1`), it refuses the connection with reason `insecure_credential_transport`. This applies to the remote daemon URL, the cloud URL, the Metro bridge URL, and the upstream URL of [`@agent-device/proxy`](https://www.npmjs.com/package/@agent-device/proxy) with its default transport. Upload tickets are already refused: if a ticket points to plain HTTP, for example because `--public-origin` is missing, the client does not use it and uploads through the daemon URL instead, unless `AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1` is set in the client process. If your network already encrypts the route, for example a WireGuard or Tailscale address, you can allow plain HTTP in the client process that sends the credential with `AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1`. This lifts the refusal. With this setting, anyone who can read the network path can read your token. Prefer Tailscale Serve or `ssh -L`, which need no override. `@agent-device/proxy` does not read this setting: give its default transport an https or loopback upstream, or supply your own `upstreamFetch`. From 650b06c662cd57fbd8fd55951de1cfdf1d576351 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 04:58:17 +0100 Subject: [PATCH 49/55] chore(gates): prove bundled workspace dev dependencies --- .../__tests__/package-closure-audit.test.ts | 33 +++++++++++++++++++ scripts/check-package.ts | 16 ++++++--- scripts/lib/shipped-imports.ts | 20 +++++++++++ 3 files changed, 64 insertions(+), 5 deletions(-) diff --git a/scripts/__tests__/package-closure-audit.test.ts b/scripts/__tests__/package-closure-audit.test.ts index 45c0e95855c..b91c790d268 100644 --- a/scripts/__tests__/package-closure-audit.test.ts +++ b/scripts/__tests__/package-closure-audit.test.ts @@ -20,9 +20,42 @@ import { afterEach, test } from 'vitest'; import { auditDependencyClosure, assertBundledWorkspaceDependencies, + bundledWorkspaceDependencyNames, type PackedManifest, } from '../lib/shipped-imports.ts'; +test('bundled workspace proof includes package devDependencies', () => { + const names = bundledWorkspaceDependencyNames( + new Map([ + [ + 'packages/maestro/package.json', + JSON.stringify({ + dependencies: { + '@eslint-community/regexpp': '4.12.2', + '@agent-device/kernel': 'workspace:*', + }, + devDependencies: { + '@limrun/api': '^0.69.1', + '@eslint-community/regexpp': 'workspace:*', + 'test-only': '1.0.0', + }, + }), + ], + ]), + new Set(['@eslint-community/regexpp', '@limrun/api', '@agent-device/kernel']), + ); + assert.deepEqual([...names].sort(), ['@eslint-community/regexpp', '@limrun/api']); + assert.throws( + () => + assertBundledWorkspaceDependencies( + names, + new Set(['@eslint-community/regexpp@4.12.2 (MIT)']), + new Map(), + ), + /does not attribute rendered @limrun\/api modules/, + ); +}); + test('a bundled workspace dependency needs rendered notice attribution', () => { assert.throws( () => assertBundledWorkspaceDependencies(new Set(['regexpp']), new Set(), new Map()), diff --git a/scripts/check-package.ts b/scripts/check-package.ts index fe002a11893..778fa7009df 100644 --- a/scripts/check-package.ts +++ b/scripts/check-package.ts @@ -9,7 +9,8 @@ * 1. `publint` — packaging metadata against the packed tarball (exports/bin/types conditions). * 2. `attw` — declaration resolution for the module systems this package supports. * 3. runtime dependency closure — every bare specifier the shipped files import is a Node builtin - * or a declared `dependencies` entry, and every declared entry is actually imported. + * or a declared `dependencies` entry, every declared entry is imported, and every bundled + * workspace dependency is attributed in the packed artifact without a runtime import. * 4. every `exports` subpath imports, and the `bin` runs, from outside the workspace. * 5. the installed tree carries no daemon source, which is what lets an installed * client treat its version as the whole of its code identity (#2458). @@ -29,12 +30,13 @@ import path from 'node:path'; import { auditDependencyClosure, assertBundledWorkspaceDependencies, + bundledWorkspaceDependencyNames, type PackedManifest as PackedDependencies, } from './lib/shipped-imports.ts'; import { assertInstalledSnapshotBridge } from './size-report-install.mjs'; import { readLicenseNotices } from './size-report-package-notices.mjs'; import { bundledDependencyNames } from './bundled-dependency-names.ts'; -import { readWorkspacePackages } from './layering/package-boundaries.ts'; +import { listTrackedPackageManifests } from './layering/tracked-sources.ts'; import { assertBundledLicenseNotices, BUNDLED_LICENSE_NOTICES_PATH, @@ -291,10 +293,14 @@ try { // tsdown bundles it. The notices plugin attributes only modules rendered into the artifact. // Check that proof for every such dependency in the installed tarball, not only today's regexpp. const bundled = new Set(bundledDependencyNames); - const bundledWorkspaceDependencies = new Set( - readWorkspacePackages(repoRoot).flatMap((pkg) => - [...pkg.externalDependencies.keys()].filter((name) => bundled.has(name)), + const bundledWorkspaceDependencies = bundledWorkspaceDependencyNames( + new Map( + listTrackedPackageManifests(repoRoot).map((file) => [ + file, + fs.readFileSync(path.join(repoRoot, file), 'utf8'), + ]), ), + bundled, ); const notices = readLicenseNotices( fs.readFileSync(path.join(installedRoot, BUNDLED_LICENSE_NOTICES_PATH), 'utf8'), diff --git a/scripts/lib/shipped-imports.ts b/scripts/lib/shipped-imports.ts index 339ae370549..7dd6a08531a 100644 --- a/scripts/lib/shipped-imports.ts +++ b/scripts/lib/shipped-imports.ts @@ -59,6 +59,26 @@ export type PackedManifest = { peerDependencies?: Record; }; +/** Bundled external dependencies declared by tracked workspace package manifests. */ +export function bundledWorkspaceDependencyNames( + manifests: ReadonlyMap, + bundledNames: ReadonlySet, +): Set { + const names = new Set(); + for (const source of manifests.values()) { + const manifest = JSON.parse(source) as { + dependencies?: Record; + devDependencies?: Record; + }; + for (const field of [manifest.dependencies, manifest.devDependencies]) { + for (const [name, range] of Object.entries(field ?? {})) { + if (bundledNames.has(name) && !range.startsWith('workspace:')) names.add(name); + } + } + } + return names; +} + /** Prove that a workspace runtime dependency omitted from the root manifest is in the packed code. */ export function assertBundledWorkspaceDependencies( names: ReadonlySet, From fd9dc6d85d829e2f04a0811338ffda8ef9919bc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 05:02:15 +0100 Subject: [PATCH 50/55] fix(capture): refuse foreign and invalid destination state --- packages/contracts/src/recording.ts | 2 + .../src/core/capture-identity-refusal.ts | 30 ++++ .../src/sessions/handlers/trace-runtime.ts | 16 +- .../internal/session-perf-runtime.ts | 16 +- packages/kernel/src/errors.ts | 4 +- .../capture-destination-record.test.ts | 85 ++++++++++- .../remote/src/capture-destination-record.ts | 140 +++++++++++------- website/docs/docs/error-reasons.md | 3 +- 8 files changed, 225 insertions(+), 71 deletions(-) create mode 100644 packages/daemon/src/core/capture-identity-refusal.ts diff --git a/packages/contracts/src/recording.ts b/packages/contracts/src/recording.ts index bad1c4e1ad9..9002dc82f0a 100644 --- a/packages/contracts/src/recording.ts +++ b/packages/contracts/src/recording.ts @@ -69,9 +69,11 @@ export type TraceCommandResult = | { trace: 'started'; outPath: string; + clientCaptureId?: string; } | { trace: 'stopped'; outPath: string; artifacts: DaemonArtifact[]; + clientCaptureId?: string; }; diff --git a/packages/daemon/src/core/capture-identity-refusal.ts b/packages/daemon/src/core/capture-identity-refusal.ts new file mode 100644 index 00000000000..f21621efe46 --- /dev/null +++ b/packages/daemon/src/core/capture-identity-refusal.ts @@ -0,0 +1,30 @@ +import { errorResponse, type DaemonResponse } from '@agent-device/kernel/contracts'; +import { CAPTURE_IDENTITY_REASONS } from '@agent-device/kernel/errors'; + +type CaptureKind = 'trace' | 'native perf'; +type CaptureRefusal = 'already-active' | 'mismatch'; + +const messages = { + trace: { + 'already-active': 'trace already in progress', + mismatch: 'trace capture identity changed', + }, + 'native perf': { + 'already-active': 'native perf capture already in progress', + mismatch: 'native perf capture identity changed', + }, +} as const; + +export function captureIdentityRefusal( + kind: CaptureKind, + refusal: CaptureRefusal, + clientCaptureId?: string, +): DaemonResponse { + return errorResponse('INVALID_ARGS', messages[kind][refusal], { + reason: + refusal === 'already-active' + ? CAPTURE_IDENTITY_REASONS.alreadyActive.reason + : CAPTURE_IDENTITY_REASONS.mismatch.reason, + ...(refusal === 'already-active' ? { clientCaptureId } : {}), + }); +} diff --git a/packages/daemon/src/sessions/handlers/trace-runtime.ts b/packages/daemon/src/sessions/handlers/trace-runtime.ts index cefd28ce593..846fbd18ed1 100644 --- a/packages/daemon/src/sessions/handlers/trace-runtime.ts +++ b/packages/daemon/src/sessions/handlers/trace-runtime.ts @@ -1,6 +1,5 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; -import { CAPTURE_IDENTITY_REASONS } from '@agent-device/kernel/errors'; import { expandSessionPath } from '@agent-device/host-kit/session-paths'; import fs from 'node:fs'; import path from 'node:path'; @@ -12,6 +11,8 @@ import type { SessionRef } from '../../core/session-state.ts'; import { recordSessionAction } from '../../core/session-action-recorder.ts'; import { errorResponse } from '@agent-device/kernel/contracts'; import { withCaptureOutputOwnership } from '../../core/capture-output-ownership.ts'; +import { captureIdentityRefusal } from '../../core/capture-identity-refusal.ts'; +import type { TraceCommandResult } from '@agent-device/contracts/recording'; export function handleTraceCommand(params: { host: HostEnvironment; @@ -36,10 +37,7 @@ function startTrace( ): DaemonResponse { const session = sessionStore.requireCurrent(ref); if (session.trace) - return errorResponse('INVALID_ARGS', 'trace already in progress', { - reason: CAPTURE_IDENTITY_REASONS.alreadyActive.reason, - clientCaptureId: session.trace.clientCaptureId, - }); + return captureIdentityRefusal('trace', 'already-active', session.trace.clientCaptureId); const outPath = expandSessionPath( req.positionals?.[1] ?? sessionStore.defaultTracePath(session), requestCwd(req, host), @@ -61,7 +59,7 @@ function startTrace( trace: 'started', outPath, ...(req.meta?.captureId ? { clientCaptureId: req.meta.captureId } : {}), - }, + } satisfies TraceCommandResult, }; } @@ -74,9 +72,7 @@ function stopTrace( const session = sessionStore.requireCurrent(ref); if (!session.trace) return errorResponse('INVALID_ARGS', 'no active trace'); if (req.meta?.captureId && req.meta.captureId !== session.trace.clientCaptureId) - return errorResponse('INVALID_ARGS', 'trace capture identity changed', { - reason: CAPTURE_IDENTITY_REASONS.mismatch.reason, - }); + return captureIdentityRefusal('trace', 'mismatch'); const clientCaptureId = session.trace.clientCaptureId; const outPath = relocateTraceOutput( requestCwd(req, host), @@ -107,7 +103,7 @@ function stopTrace( fileName: path.basename(clientOutPath ?? outPath), }, ], - }, + } satisfies TraceCommandResult, daemonOwned ? 'daemon' : 'caller', tenantId, ), diff --git a/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts b/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts index 493f08492f0..ec7f87ee317 100644 --- a/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts +++ b/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts @@ -26,7 +26,7 @@ import { PERF_AGGREGATE_REMOVED_ERROR_MESSAGE, } from '@agent-device/contracts/observability'; import { publicPlatformString } from '@agent-device/kernel/device'; -import { AppError, CAPTURE_IDENTITY_REASONS, normalizeError } from '@agent-device/kernel/errors'; +import { AppError, normalizeError } from '@agent-device/kernel/errors'; import { isRecord } from '@agent-device/kernel/record'; import type { BindDeviceRuntime, @@ -38,6 +38,7 @@ import { requestCwd } from '../../../core/context.ts'; import type { SessionRef, SessionState } from '../../../core/session-state.ts'; import { bindSessionPerfCapture } from '../../../core/session-capture-binding.ts'; import { withCaptureOutputOwnership } from '../../../core/capture-output-ownership.ts'; +import { captureIdentityRefusal } from '../../../core/capture-identity-refusal.ts'; import { recordSessionAction } from '../../../core/session-action-recorder.ts'; import { admitRuntimePlan, @@ -215,10 +216,11 @@ async function startPerfCapture( request: Extract, ): Promise { if (session.perfCapture) { - return errorResponse('INVALID_ARGS', 'native perf capture already in progress', { - reason: CAPTURE_IDENTITY_REASONS.alreadyActive.reason, - clientCaptureId: session.perfCapture.clientCaptureId, - }); + return captureIdentityRefusal( + 'native perf', + 'already-active', + session.perfCapture.clientCaptureId, + ); } if (!session.appBundleId) { return errorResponse('COMMAND_FAILED', 'No app is associated with this session.', { @@ -302,9 +304,7 @@ async function stopPerfCapture( const capture = session.perfCapture; if (!capture) return errorResponse('INVALID_ARGS', 'no active native perf capture'); if (params.req.meta?.captureId && params.req.meta.captureId !== capture.clientCaptureId) - return errorResponse('INVALID_ARGS', 'native perf capture identity changed', { - reason: CAPTURE_IDENTITY_REASONS.mismatch.reason, - }); + return captureIdentityRefusal('native perf', 'mismatch'); const snapshot = capture.handle.inspect(); const mismatchMessage = perfCaptureStopMismatch(snapshot, request); if (mismatchMessage) return errorResponse('INVALID_ARGS', mismatchMessage); diff --git a/packages/kernel/src/errors.ts b/packages/kernel/src/errors.ts index b83d871028c..3e57ee8d9b4 100644 --- a/packages/kernel/src/errors.ts +++ b/packages/kernel/src/errors.ts @@ -498,10 +498,12 @@ export const DURABLE_RESOURCE_REASONS = { /** Refusals that identify the live trace or native perf capture without trusting an output path. */ export const CAPTURE_IDENTITY_REASONS = { - // A capture already runs for this session; the response names its live capture ID. + // A capture already runs for this session; the response names its live capture ID when present. alreadyActive: { reason: 'capture-already-active' }, // The requested capture ID differs from the live capture ID, so the stop is refused. mismatch: { reason: 'capture-identity-mismatch' }, + // A local capture record cannot be trusted, so no remote capture command is sent. + recordInvalid: { reason: 'capture-record-invalid' }, } as const satisfies ReasonTable<'capture identity'>; const REQUEST_CANCELED_HINT = diff --git a/packages/remote/src/__tests__/capture-destination-record.test.ts b/packages/remote/src/__tests__/capture-destination-record.test.ts index fff57566962..b7ef9e12dc0 100644 --- a/packages/remote/src/__tests__/capture-destination-record.test.ts +++ b/packages/remote/src/__tests__/capture-destination-record.test.ts @@ -45,6 +45,15 @@ function request( }; } +function captureRecordPath(stateDir: string): string { + const root = path.join(stateDir, 'remote-connections', 'capture-destinations'); + const [scope] = fs.readdirSync(root); + if (!scope) throw new Error('Missing capture session record directory'); + const [recordName] = fs.readdirSync(path.join(root, scope)); + if (!recordName) throw new Error('Missing capture record'); + return path.join(root, scope, recordName); +} + test.each(['trace', 'perf'] as const)( '%s stop replays its own start path and retires it', async (family) => { @@ -89,6 +98,7 @@ test.each(['trace', 'perf'] as const)( }, ); expect(sent[1]?.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + expect(sent[1]?.meta?.captureId).toBeUndefined(); }, ); @@ -99,12 +109,14 @@ test('a pathless new start invalidates an older destination before dispatch', as ); await sendRemoteCapture(endpoint, request('start'), stateDir, async (start) => { await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.captureId).toBeUndefined(); expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); return success; }); return confirmed(start); }); await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.captureId).toBeUndefined(); expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); return success; }); @@ -131,6 +143,7 @@ test.each(['returned', 'thrown'] as const)( await expect(start).rejects.toMatchObject({ details: { dispatched: 'no' } }); else expect((await start).ok).toBe(false); await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.captureId).toBeUndefined(); expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); return success; }); @@ -224,6 +237,71 @@ test.each(['trace', 'perf'] as const)( }, ); +test.each(['trace', 'perf'] as const)( + '%s refuses a pathless stop after a foreign capture claims the session', + async (family) => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/owned.trace', { family }), + stateDir, + async (req) => confirmed(req), + ); + const refusal = await sendRemoteCapture( + endpoint, + request('start', '/client/new.trace', { family }), + stateDir, + async () => ({ + ok: false, + error: { + code: 'INVALID_ARGS', + message: 'capture already active', + details: { reason: 'capture-already-active', clientCaptureId: 'foreign-capture' }, + }, + }), + ); + expect(refusal.ok).toBe(false); + expect(JSON.parse(fs.readFileSync(captureRecordPath(stateDir), 'utf8')).certainty).toBe( + 'foreign', + ); + let dispatched = false; + await expect( + sendRemoteCapture(endpoint, request('stop', undefined, { family }), stateDir, async () => { + dispatched = true; + return success; + }), + ).rejects.toMatchObject({ details: { reason: 'capture-identity-mismatch' } }); + expect(dispatched).toBe(false); + }, +); + +test('a malformed capture record refuses start and stop before dispatch', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/owned.trace'), + stateDir, + async (req) => confirmed(req), + ); + const file = captureRecordPath(stateDir); + fs.writeFileSync(file, '{invalid'); + let dispatched = false; + const send = async () => { + dispatched = true; + return success; + }; + await expect(sendRemoteCapture(endpoint, request('stop'), stateDir, send)).rejects.toMatchObject({ + details: { reason: 'capture-record-invalid' }, + }); + await expect(sendRemoteCapture(endpoint, request('start'), stateDir, send)).rejects.toMatchObject( + { + details: { reason: 'capture-record-invalid' }, + }, + ); + expect(dispatched).toBe(false); + expect(fs.readFileSync(file, 'utf8')).toBe('{invalid'); +}); + test('a concurrent rejected start does not discard a newly confirmed start', async () => { const stateDir = mkdtempForTestSync('capture-destination-'); let releaseFirst!: () => void; @@ -256,6 +334,7 @@ test('a concurrent rejected start does not discard a newly confirmed start', asy ); await second; await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.captureId).toBeUndefined(); expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); return success; }); @@ -282,6 +361,7 @@ test('successful close retires destinations before the same session address is r async (req) => confirmed(req), ); await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.captureId).toBeUndefined(); expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); return success; }); @@ -523,7 +603,7 @@ test.each(['returned', 'thrown'] as const)( if (!recordName) throw new Error('Missing capture record'); const record = JSON.parse(fs.readFileSync(path.join(root, scope, recordName), 'utf8')); expect(record.pending).toEqual([]); - expect(record.uncertain).toBe(true); + expect(record.certainty).toBe('unknown'); await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { expect(req.meta?.captureId).toBeUndefined(); expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); @@ -584,6 +664,7 @@ test('scope and explicit stop path cannot borrow or override another capture des request('stop', undefined, { tenantId: 'tenant-b' }), stateDir, async (req) => { + expect(req.meta?.captureId).toBeUndefined(); expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); return success; }, @@ -599,6 +680,7 @@ test('scope and explicit stop path cannot borrow or override another capture des }, ); await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.captureId).toBeUndefined(); expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); return success; }); @@ -623,6 +705,7 @@ test('endpoint, tenant, run, lease, session, and capture kind each isolate desti ]; for (const { baseUrl, options } of variants) { await sendRemoteCapture(baseUrl, request('stop', undefined, options), stateDir, async (req) => { + expect(req.meta?.captureId).toBeUndefined(); expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); return success; }); diff --git a/packages/remote/src/capture-destination-record.ts b/packages/remote/src/capture-destination-record.ts index 73f16b752c0..d14903e0ebe 100644 --- a/packages/remote/src/capture-destination-record.ts +++ b/packages/remote/src/capture-destination-record.ts @@ -13,7 +13,13 @@ type Capture = { action: 'start' | 'stop'; family: string }; type Send = (req: DaemonWireRequest) => Promise; type Active = { generation: string; destination: string; order: number }; type Pending = { generation: string; order: number }; -type RecordState = { active?: Active; pending: Pending[]; uncertain: boolean; nextOrder: number }; +type CaptureCertainty = 'settled' | 'unknown' | 'foreign'; +type RecordState = { + active?: Active; + pending: Pending[]; + certainty: CaptureCertainty; + nextOrder: number; +}; const stopGenerations = new WeakMap(); function captureOf(req: DaemonWireRequest): Capture | undefined { @@ -64,47 +70,64 @@ function recordFile( } function readRecord(file: string): RecordState | undefined { + let serialized: string; + try { + serialized = fs.readFileSync(file, 'utf8'); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; + throw error; + } let value: unknown; try { - value = JSON.parse(fs.readFileSync(file, 'utf8')); + value = JSON.parse(serialized); } catch { - return undefined; + invalidRecord(); } - if (typeof value !== 'object' || value === null) return undefined; + if (!isRecordState(value)) invalidRecord(); + return value; +} + +function isPending(value: unknown): value is Pending { + if (typeof value !== 'object' || value === null) return false; + const pending = value as Partial; + return ( + typeof pending.generation === 'string' && + Number.isSafeInteger(pending.order) && + (pending.order ?? 0) > 0 + ); +} + +function isActive(value: unknown): value is Active { + if (typeof value !== 'object' || value === null) return false; + const active = value as Partial; + return ( + typeof active.generation === 'string' && + typeof active.destination === 'string' && + path.isAbsolute(active.destination) && + Number.isSafeInteger(active.order) && + (active.order ?? 0) > 0 + ); +} + +function isRecordState(value: unknown): value is RecordState { + if (typeof value !== 'object' || value === null) return false; const record = value as Partial; - if ( - !Array.isArray(record.pending) || - !record.pending.every( - (pending) => - typeof pending === 'object' && - pending !== null && - typeof pending.generation === 'string' && - Number.isSafeInteger(pending.order) && - pending.order > 0, - ) || - typeof record.uncertain !== 'boolean' || - typeof record.nextOrder !== 'number' || - !Number.isSafeInteger(record.nextOrder) || - record.nextOrder < 0 - ) - return undefined; - const active = record.active; - if ( - active !== undefined && - (active === null || - typeof active.generation !== 'string' || - typeof active.destination !== 'string' || - !path.isAbsolute(active.destination) || - !Number.isSafeInteger(active.order) || - active.order < 1) - ) - return undefined; - return { - ...(active ? { active } : {}), - pending: record.pending, - uncertain: record.uncertain, - nextOrder: record.nextOrder, - }; + return ( + Array.isArray(record.pending) && + record.pending.every(isPending) && + (record.certainty === 'settled' || + record.certainty === 'unknown' || + record.certainty === 'foreign') && + Number.isSafeInteger(record.nextOrder) && + (record.nextOrder ?? -1) >= 0 && + (record.active === undefined || isActive(record.active)) + ); +} + +function invalidRecord(): never { + throw new AppError('COMMAND_FAILED', 'Remote capture destination record is invalid', { + reason: CAPTURE_IDENTITY_REASONS.recordInvalid.reason, + }); } function writeRecord(file: string, record: RecordState): void { @@ -113,7 +136,7 @@ function writeRecord(file: string, record: RecordState): void { } function settleRecord(file: string, record: RecordState): void { - if (!record.active && record.pending.length === 0 && !record.uncertain) + if (!record.active && record.pending.length === 0 && record.certainty === 'settled') fs.rmSync(file, { force: true }); else writeRecord(file, record); } @@ -163,21 +186,32 @@ function recordAfterStart( order: number, ): RecordState { const active = activeAfterStart(current, response, failure, generation, destination, order); - const details = refusalDetails(response, failure); - const confirmed = response?.ok === true && response.data?.clientCaptureId === generation; - const olderThanActive = order < (current.active?.order ?? 0); return { ...(active ? { active } : {}), pending: current.pending.filter((candidate) => candidate.generation !== generation), - uncertain: olderThanActive - ? current.uncertain - : confirmed - ? false - : current.uncertain || details?.reason !== CAPTURE_IDENTITY_REASONS.alreadyActive.reason, + certainty: certaintyAfterStart(current, response, failure, generation, order), nextOrder: current.nextOrder, }; } +function certaintyAfterStart( + current: RecordState, + response: DaemonResponse | undefined, + failure: unknown, + generation: string, + order: number, +): CaptureCertainty { + if (order < (current.active?.order ?? 0)) return current.certainty; + if (response?.ok === true && response.data?.clientCaptureId === generation) return 'settled'; + const details = refusalDetails(response, failure); + if (details?.reason === CAPTURE_IDENTITY_REASONS.alreadyActive.reason) { + if (current.active && details.clientCaptureId === current.active.generation) + return current.certainty; + if (typeof details.clientCaptureId === 'string') return 'foreign'; + } + return current.certainty === 'foreign' ? 'foreign' : 'unknown'; +} + async function withRecordLock(file: string, task: () => Promise): Promise { fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); const { pid, startTime } = readCurrentOwnerIdentity(); @@ -228,7 +262,13 @@ async function sendCaptureStop( ): Promise { const active = await withRecordLock(file, async () => { const current = readRecord(file); - return current?.pending.length === 0 && !current.uncertain ? current.active : undefined; + if (current?.certainty === 'foreign') + throw new AppError('INVALID_ARGS', 'Remote capture identity changed', { + reason: CAPTURE_IDENTITY_REASONS.mismatch.reason, + }); + return current?.pending.length === 0 && current.certainty === 'settled' + ? current.active + : undefined; }); if (!active) return await send(req); const hasExplicitPath = typeof req.meta?.clientArtifactPaths?.outPath === 'string'; @@ -261,7 +301,7 @@ async function sendCaptureStart( writeRecord(file, { ...(current?.active ? { active: current.active } : {}), pending: [...(current?.pending ?? []), { generation, order: nextOrder }], - uncertain: current?.uncertain ?? false, + certainty: current?.certainty ?? 'settled', nextOrder, }); return nextOrder; @@ -299,7 +339,7 @@ export async function retireSuccessfulCaptureStop(req: DaemonWireRequest): Promi if (current?.active?.generation === owned.generation) settleRecord(owned.file, { pending: current.pending, - uncertain: current.uncertain, + certainty: current.certainty, nextOrder: current.nextOrder, }); }); @@ -315,7 +355,7 @@ export async function confirmedCaptureStopRequest( const active = await withRecordLock(owned.file, async () => { const current = readRecord(owned.file); return current?.pending.length === 0 && - !current.uncertain && + current.certainty === 'settled' && current.active?.generation === owned.generation ? current.active : undefined; diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 816cf54e17a..59e122f6169 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -600,8 +600,9 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | -| `capture-already-active` | A capture already runs for this session; the response names its live capture ID. | +| `capture-already-active` | A capture already runs for this session; the response names its live capture ID when one was minted. | | `capture-identity-mismatch` | The requested capture ID differs from the live capture ID, so the stop is refused. | +| `capture-record-invalid` | The local capture destination record is unreadable or malformed, so no remote capture command is sent. | ### Command flags From 189035691e454324abe54ae84ef2a011271e4ec7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 05:05:15 +0100 Subject: [PATCH 51/55] fix(capture): type unreadable record refusals --- docs/agents/security.md | 4 ++- .../capture-destination-record.test.ts | 25 +++++++++++++++++++ .../remote/src/capture-destination-record.ts | 17 +++++++------ website/docs/docs/error-reasons.md | 2 +- 4 files changed, 39 insertions(+), 9 deletions(-) diff --git a/docs/agents/security.md b/docs/agents/security.md index 2f1f6d679a0..c0fcfef5066 100644 --- a/docs/agents/security.md +++ b/docs/agents/security.md @@ -8,7 +8,9 @@ On start, mark identity pending. If the daemon rejects a start with the same capture ID, restore the saved path. On pathless stop, send the client capture ID. If the daemon confirms the live capture ID on stop, use the saved path. -On unclear outcomes or ID mismatch, use a unique cwd name. +If a start reports a different live capture ID, refuse a pathless stop before dispatch. +If a stop reports an ID mismatch, retire the saved path and use a unique cwd name for a later retry. +If the outcome is unclear, use a unique cwd name. After close or stop, retire the path. The daemon admits its state directory. Nobody trusts the network or other local users. Out of scope: same uid, hostile root, ACLs, mounts, untrusted filesystems. diff --git a/packages/remote/src/__tests__/capture-destination-record.test.ts b/packages/remote/src/__tests__/capture-destination-record.test.ts index b7ef9e12dc0..f9f0d859f62 100644 --- a/packages/remote/src/__tests__/capture-destination-record.test.ts +++ b/packages/remote/src/__tests__/capture-destination-record.test.ts @@ -302,6 +302,31 @@ test('a malformed capture record refuses start and stop before dispatch', async expect(fs.readFileSync(file, 'utf8')).toBe('{invalid'); }); +test('an unreadable capture record refuses start and stop before dispatch', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/owned.trace'), + stateDir, + async (req) => confirmed(req), + ); + const file = captureRecordPath(stateDir); + fs.rmSync(file); + fs.mkdirSync(file); + let dispatched = false; + const send = async () => { + dispatched = true; + return success; + }; + await expect(sendRemoteCapture(endpoint, request('stop'), stateDir, send)).rejects.toMatchObject({ + details: { reason: 'capture-record-invalid' }, + }); + await expect(sendRemoteCapture(endpoint, request('start'), stateDir, send)).rejects.toMatchObject( + { details: { reason: 'capture-record-invalid' } }, + ); + expect(dispatched).toBe(false); +}); + test('a concurrent rejected start does not discard a newly confirmed start', async () => { const stateDir = mkdtempForTestSync('capture-destination-'); let releaseFirst!: () => void; diff --git a/packages/remote/src/capture-destination-record.ts b/packages/remote/src/capture-destination-record.ts index d14903e0ebe..52d94d720a1 100644 --- a/packages/remote/src/capture-destination-record.ts +++ b/packages/remote/src/capture-destination-record.ts @@ -75,13 +75,13 @@ function readRecord(file: string): RecordState | undefined { serialized = fs.readFileSync(file, 'utf8'); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; - throw error; + invalidRecord(error); } let value: unknown; try { value = JSON.parse(serialized); - } catch { - invalidRecord(); + } catch (error) { + invalidRecord(error); } if (!isRecordState(value)) invalidRecord(); return value; @@ -124,10 +124,13 @@ function isRecordState(value: unknown): value is RecordState { ); } -function invalidRecord(): never { - throw new AppError('COMMAND_FAILED', 'Remote capture destination record is invalid', { - reason: CAPTURE_IDENTITY_REASONS.recordInvalid.reason, - }); +function invalidRecord(cause?: unknown): never { + throw new AppError( + 'COMMAND_FAILED', + 'Remote capture destination record is invalid', + { reason: CAPTURE_IDENTITY_REASONS.recordInvalid.reason }, + cause, + ); } function writeRecord(file: string, record: RecordState): void { diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 59e122f6169..ca88db4f3e2 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -601,7 +601,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | | `capture-already-active` | A capture already runs for this session; the response names its live capture ID when one was minted. | -| `capture-identity-mismatch` | The requested capture ID differs from the live capture ID, so the stop is refused. | +| `capture-identity-mismatch` | The daemon refuses a stop with the wrong capture ID. The client also refuses a pathless stop after a start reports a foreign live ID. | | `capture-record-invalid` | The local capture destination record is unreadable or malformed, so no remote capture command is sent. | ### Command flags From dfd7fc9e723f353304ec9725ea60afe3953e6d78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 05:11:30 +0100 Subject: [PATCH 52/55] chore(gates): align capture guidance with reason source --- docs/agents/security.md | 26 ++++++++++++-------------- packages/kernel/src/errors.ts | 6 +++--- 2 files changed, 15 insertions(+), 17 deletions(-) diff --git a/docs/agents/security.md b/docs/agents/security.md index c0fcfef5066..f64a54fdcb1 100644 --- a/docs/agents/security.md +++ b/docs/agents/security.md @@ -1,18 +1,17 @@ # Security boundaries -The client owns local paths; the daemon supplies only data and validated IDs. Reject daemon-chosen paths in scripts and remote record stops (#4518). -Trace/perf uses caller paths. Unnamed captures get unique cwd names. -Key trace/perf paths by endpoint, tenant, run, lease, session, and kind. -On start, mark identity pending. -If the daemon rejects a start with the same capture ID, restore the saved path. -On pathless stop, send the client capture ID. -If the daemon confirms the live capture ID on stop, use the saved path. -If a start reports a different live capture ID, refuse a pathless stop before dispatch. -If a stop reports an ID mismatch, retire the saved path and use a unique cwd name for a later retry. +Use caller paths for trace/perf. Give unnamed captures unique cwd names. +Key saved paths by endpoint, tenant, run, lease, session, and kind. +On start, mark ID pending. +If start rejects the same ID, keep the saved path. +If start names a foreign ID, refuse pathless stop before dispatch. +On pathless stop, send the client ID. +If stop confirms the ID, use the saved path. +If stop rejects the ID, retire the saved path and retry with a unique cwd name. If the outcome is unclear, use a unique cwd name. -After close or stop, retire the path. -The daemon admits its state directory. Nobody trusts the network or other local users. +After close or stop, retire the saved path. +The daemon admits state; trust neither network nor other local users. Out of scope: same uid, hostile root, ACLs, mounts, untrusted filesystems. ADR 0041 owns credential transport. @@ -20,7 +19,6 @@ ADR 0016 owns script destination writes and delivery limits. ## Proposed in #4669 -Until #4669 is approved, do not apply its credential and state private-write proposal. -The proposal creates credential, client state, and daemon state files under a verified state root. -It never writes through a link at the final name. +Until #4669 is approved, do not apply its private-write proposal. +It creates credentials and client/daemon state under a verified root without following a final-name link. Do not apply ADR 0016's path walk to screenshot `--out`, contact sheets, JUnit, traces, or recordings. diff --git a/packages/kernel/src/errors.ts b/packages/kernel/src/errors.ts index 3e57ee8d9b4..7f3461401d0 100644 --- a/packages/kernel/src/errors.ts +++ b/packages/kernel/src/errors.ts @@ -498,11 +498,11 @@ export const DURABLE_RESOURCE_REASONS = { /** Refusals that identify the live trace or native perf capture without trusting an output path. */ export const CAPTURE_IDENTITY_REASONS = { - // A capture already runs for this session; the response names its live capture ID when present. + // A capture already runs for this session; the response names its live capture ID when one was minted. alreadyActive: { reason: 'capture-already-active' }, - // The requested capture ID differs from the live capture ID, so the stop is refused. + // The daemon refuses a stop with the wrong capture ID. The client also refuses a pathless stop after a start reports a foreign live ID. mismatch: { reason: 'capture-identity-mismatch' }, - // A local capture record cannot be trusted, so no remote capture command is sent. + // The local capture destination record is unreadable or malformed, so no remote capture command is sent. recordInvalid: { reason: 'capture-record-invalid' }, } as const satisfies ReasonTable<'capture identity'>; From efaf61b3e782d6cd70f56f2001f8f1b5b89e7697 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 06:29:00 +0100 Subject: [PATCH 53/55] fix(capture): distinguish own and foreign live captures --- docs/agents/security.md | 5 +- packages/kernel/src/errors.ts | 4 +- .../capture-destination-record.test.ts | 184 +++++++++++++++++- .../remote/src/capture-destination-record.ts | 60 ++++-- website/docs/docs/error-reasons.md | 2 +- 5 files changed, 228 insertions(+), 27 deletions(-) diff --git a/docs/agents/security.md b/docs/agents/security.md index f64a54fdcb1..57518ff5ae3 100644 --- a/docs/agents/security.md +++ b/docs/agents/security.md @@ -2,13 +2,14 @@ Reject daemon-chosen paths in scripts and remote record stops (#4518). Use caller paths for trace/perf. Give unnamed captures unique cwd names. -Key saved paths by endpoint, tenant, run, lease, session, and kind. +Key paths by endpoint, tenant, run, lease, session, and kind. On start, mark ID pending. If start rejects the same ID, keep the saved path. -If start names a foreign ID, refuse pathless stop before dispatch. +If settled state names a foreign ID, refuse pathless stop. On pathless stop, send the client ID. If stop confirms the ID, use the saved path. If stop rejects the ID, retire the saved path and retry with a unique cwd name. +If an explicit stop succeeds, clear unchanged foreign state. If the outcome is unclear, use a unique cwd name. After close or stop, retire the saved path. The daemon admits state; trust neither network nor other local users. diff --git a/packages/kernel/src/errors.ts b/packages/kernel/src/errors.ts index 7f3461401d0..75b9654f375 100644 --- a/packages/kernel/src/errors.ts +++ b/packages/kernel/src/errors.ts @@ -500,7 +500,9 @@ export const DURABLE_RESOURCE_REASONS = { export const CAPTURE_IDENTITY_REASONS = { // A capture already runs for this session; the response names its live capture ID when one was minted. alreadyActive: { reason: 'capture-already-active' }, - // The daemon refuses a stop with the wrong capture ID. The client also refuses a pathless stop after a start reports a foreign live ID. + // The daemon refuses a stop with the wrong capture ID. + // The client also refuses a pathless stop when a settled record identifies a foreign live capture. + // An explicit caller path can still stop it. mismatch: { reason: 'capture-identity-mismatch' }, // The local capture destination record is unreadable or malformed, so no remote capture command is sent. recordInvalid: { reason: 'capture-record-invalid' }, diff --git a/packages/remote/src/__tests__/capture-destination-record.test.ts b/packages/remote/src/__tests__/capture-destination-record.test.ts index f9f0d859f62..07e642d817d 100644 --- a/packages/remote/src/__tests__/capture-destination-record.test.ts +++ b/packages/remote/src/__tests__/capture-destination-record.test.ts @@ -102,12 +102,14 @@ test.each(['trace', 'perf'] as const)( }, ); -test('a pathless new start invalidates an older destination before dispatch', async () => { +test('a pathless new start replaces an older destination without reusing its path', async () => { const stateDir = mkdtempForTestSync('capture-destination-'); await sendRemoteCapture(endpoint, request('start', '/client/old.trace'), stateDir, async (req) => confirmed(req), ); + let newCaptureId: string | undefined; await sendRemoteCapture(endpoint, request('start'), stateDir, async (start) => { + newCaptureId = start.meta?.captureId; await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { expect(req.meta?.captureId).toBeUndefined(); expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); @@ -116,7 +118,7 @@ test('a pathless new start invalidates an older destination before dispatch', as return confirmed(start); }); await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { - expect(req.meta?.captureId).toBeUndefined(); + expect(req.meta?.captureId).toBe(newCaptureId); expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); return success; }); @@ -272,6 +274,180 @@ test.each(['trace', 'perf'] as const)( }), ).rejects.toMatchObject({ details: { reason: 'capture-identity-mismatch' } }); expect(dispatched).toBe(false); + const failedExplicitStop = await sendRemoteCapture( + endpoint, + request('stop', '/client/explicit.trace', { family }), + stateDir, + async () => ({ ok: false, error: { code: 'COMMAND_FAILED', message: 'stop failed' } }), + ); + expect(failedExplicitStop.ok).toBe(false); + await expect( + sendRemoteCapture(endpoint, request('stop', undefined, { family }), stateDir, async () => { + dispatched = true; + return success; + }), + ).rejects.toMatchObject({ details: { reason: 'capture-identity-mismatch' } }); + expect(dispatched).toBe(false); + await sendRemoteCapture( + endpoint, + request('stop', '/client/explicit.trace', { family }), + stateDir, + async (req) => { + expect(req.meta?.captureId).toBeUndefined(); + expect(req.meta?.clientArtifactPaths?.outPath).toBe('/client/explicit.trace'); + return success; + }, + ); + await sendRemoteCapture( + endpoint, + request('stop', undefined, { family }), + stateDir, + async (req) => { + expect(req.meta?.captureId).toBeUndefined(); + return success; + }, + ); + }, +); + +test('a late explicit-stop reply cannot clear a newer confirmed capture', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture(endpoint, request('start', '/client/old.trace'), stateDir, async (req) => + confirmed(req), + ); + await sendRemoteCapture( + endpoint, + request('start', '/client/retry.trace'), + stateDir, + async () => ({ + ok: false, + error: { + code: 'INVALID_ARGS', + message: 'capture already active', + details: { reason: 'capture-already-active', clientCaptureId: 'foreign-capture' }, + }, + }), + ); + let stopSent!: () => void; + const stopReachedDaemon = new Promise((resolve) => (stopSent = resolve)); + let finishStop!: () => void; + const stopCanFinish = new Promise((resolve) => (finishStop = resolve)); + const explicitStop = sendRemoteCapture( + endpoint, + request('stop', '/client/explicit.trace'), + stateDir, + async () => { + stopSent(); + await stopCanFinish; + return success; + }, + ); + await stopReachedDaemon; + let newerId: string | undefined; + await sendRemoteCapture( + endpoint, + request('start', '/client/new.trace'), + stateDir, + async (req) => { + newerId = req.meta?.captureId; + return confirmed(req); + }, + ); + finishStop(); + await explicitStop; + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.captureId).toBe(newerId); + const answer = confirmed(req); + expect( + (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + ).toBe('/client/new.trace'); + return answer; + }); +}); + +test.each(['trace', 'perf'] as const)( + '%s keeps a timed-out own start unknown when a retry names its ID', + async (family) => { + const stateDir = mkdtempForTestSync('capture-destination-'); + let firstId: string | undefined; + await expect( + sendRemoteCapture( + endpoint, + request('start', '/client/owned.trace', { family }), + stateDir, + async (req) => { + firstId = req.meta?.captureId; + throw new Error('timeout after dispatch'); + }, + ), + ).rejects.toThrow('timeout after dispatch'); + expect(firstId).toBeTypeOf('string'); + await sendRemoteCapture( + endpoint, + request('start', '/client/retry.trace', { family }), + stateDir, + async () => ({ + ok: false, + error: { + code: 'INVALID_ARGS', + message: 'capture already active', + details: { reason: 'capture-already-active', clientCaptureId: firstId }, + }, + }), + ); + await sendRemoteCapture( + endpoint, + request('stop', undefined, { family }), + stateDir, + async (req) => { + expect(req.meta?.captureId).toBeUndefined(); + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }, + ); + }, +); + +test.each(['trace', 'perf'] as const)( + '%s retains a confirmed unnamed capture ID across repeat-start refusal', + async (family) => { + const stateDir = mkdtempForTestSync('capture-destination-'); + let activeId: string | undefined; + await sendRemoteCapture( + endpoint, + request('start', undefined, { family }), + stateDir, + async (req) => { + activeId = req.meta?.captureId; + return confirmed(req); + }, + ); + await sendRemoteCapture( + endpoint, + request('start', undefined, { family }), + stateDir, + async () => ({ + ok: false, + error: { + code: 'INVALID_ARGS', + message: 'capture already active', + details: { reason: 'capture-already-active', clientCaptureId: activeId }, + }, + }), + ); + await sendRemoteCapture( + endpoint, + request('stop', undefined, { family }), + stateDir, + async (req) => { + expect(req.meta?.captureId).toBe(activeId); + const answer = confirmed(req); + expect( + (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + ).toBeUndefined(); + return answer; + }, + ); }, ); @@ -333,11 +509,13 @@ test('a concurrent rejected start does not discard a newly confirmed start', asy const firstReachedDaemon = new Promise((resolve) => (releaseFirst = resolve)); let finishFirst!: () => void; const firstCanFinish = new Promise((resolve) => (finishFirst = resolve)); + let firstId: string | undefined; const first = sendRemoteCapture( endpoint, request('start', '/client/first.trace'), stateDir, async (req) => { + firstId = req.meta?.captureId; releaseFirst(); await firstCanFinish; return confirmed(req); @@ -353,7 +531,7 @@ test('a concurrent rejected start does not discard a newly confirmed start', asy error: { code: 'INVALID_ARGS', message: 'capture already active', - details: { reason: 'capture-already-active' }, + details: { reason: 'capture-already-active', clientCaptureId: firstId }, }, }), ); diff --git a/packages/remote/src/capture-destination-record.ts b/packages/remote/src/capture-destination-record.ts index 52d94d720a1..ed362eed76a 100644 --- a/packages/remote/src/capture-destination-record.ts +++ b/packages/remote/src/capture-destination-record.ts @@ -11,7 +11,7 @@ import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; type Capture = { action: 'start' | 'stop'; family: string }; type Send = (req: DaemonWireRequest) => Promise; -type Active = { generation: string; destination: string; order: number }; +type Active = { generation: string; destination?: string; order: number }; type Pending = { generation: string; order: number }; type CaptureCertainty = 'settled' | 'unknown' | 'foreign'; type RecordState = { @@ -102,8 +102,8 @@ function isActive(value: unknown): value is Active { const active = value as Partial; return ( typeof active.generation === 'string' && - typeof active.destination === 'string' && - path.isAbsolute(active.destination) && + (active.destination === undefined || + (typeof active.destination === 'string' && path.isAbsolute(active.destination))) && Number.isSafeInteger(active.order) && (active.order ?? 0) > 0 ); @@ -149,17 +149,18 @@ function refusalDetails(response: DaemonResponse | undefined, failure: unknown) return failure instanceof AppError ? failure.details : undefined; } -function confirmedStartDestination( +function confirmedStartCapture( response: Extract, generation: string, destination: string | undefined, order: number, ): Active | undefined { - return response.data?.clientCaptureId === generation && - typeof destination === 'string' && - path.isAbsolute(destination) - ? { generation, destination, order } - : undefined; + if (response.data?.clientCaptureId !== generation) return undefined; + return { + generation, + ...(typeof destination === 'string' && path.isAbsolute(destination) ? { destination } : {}), + order, + }; } function activeAfterStart( @@ -172,8 +173,7 @@ function activeAfterStart( ): Active | undefined { const active = current.active; if (order < (active?.order ?? 0)) return active; - if (response?.ok === true) - return confirmedStartDestination(response, generation, destination, order); + if (response?.ok === true) return confirmedStartCapture(response, generation, destination, order); const details = refusalDetails(response, failure); if (details?.reason === CAPTURE_IDENTITY_REASONS.alreadyActive.reason) return details.clientCaptureId === active?.generation ? active : undefined; @@ -210,7 +210,10 @@ function certaintyAfterStart( if (details?.reason === CAPTURE_IDENTITY_REASONS.alreadyActive.reason) { if (current.active && details.clientCaptureId === current.active.generation) return current.certainty; - if (typeof details.clientCaptureId === 'string') return 'foreign'; + if (current.pending.some((pending) => pending.generation === details.clientCaptureId)) + return current.certainty === 'foreign' ? 'foreign' : 'unknown'; + if (current.certainty === 'settled' && typeof details.clientCaptureId === 'string') + return 'foreign'; } return current.certainty === 'foreign' ? 'foreign' : 'unknown'; } @@ -263,18 +266,26 @@ async function sendCaptureStop( req: DaemonWireRequest, send: Send, ): Promise { - const active = await withRecordLock(file, async () => { + const hasExplicitPath = typeof req.meta?.clientArtifactPaths?.outPath === 'string'; + const { active, foreignBeforeStop } = await withRecordLock(file, async () => { const current = readRecord(file); - if (current?.certainty === 'foreign') + if (current?.certainty === 'foreign' && !hasExplicitPath) throw new AppError('INVALID_ARGS', 'Remote capture identity changed', { reason: CAPTURE_IDENTITY_REASONS.mismatch.reason, }); - return current?.pending.length === 0 && current.certainty === 'settled' - ? current.active - : undefined; + return { + active: + current?.pending.length === 0 && current.certainty === 'settled' + ? current.active + : undefined, + foreignBeforeStop: current?.certainty === 'foreign' ? JSON.stringify(current) : undefined, + }; }); - if (!active) return await send(req); - const hasExplicitPath = typeof req.meta?.clientArtifactPaths?.outPath === 'string'; + if (!active) { + const response = await send(req); + if (response.ok && foreignBeforeStop) await clearForeignAfterStop(file, foreignBeforeStop); + return response; + } const sent = hasExplicitPath ? req : { ...req, meta: { ...req.meta, captureId: active.generation } }; @@ -292,6 +303,14 @@ async function sendCaptureStop( return response; } +async function clearForeignAfterStop(file: string, beforeStop: string): Promise { + await withRecordLock(file, async () => { + const current = readRecord(file); + if (current?.certainty === 'foreign' && JSON.stringify(current) === beforeStop) + settleRecord(file, { ...current, certainty: 'settled' }); + }); +} + async function sendCaptureStart( file: string, req: DaemonWireRequest, @@ -363,7 +382,8 @@ export async function confirmedCaptureStopRequest( ? current.active : undefined; }); - if (!active || typeof req.meta?.clientArtifactPaths?.outPath === 'string') return req; + if (!active?.destination || typeof req.meta?.clientArtifactPaths?.outPath === 'string') + return req; return { ...req, meta: { diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index ca88db4f3e2..ff2fba3c84c 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -601,7 +601,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | | `capture-already-active` | A capture already runs for this session; the response names its live capture ID when one was minted. | -| `capture-identity-mismatch` | The daemon refuses a stop with the wrong capture ID. The client also refuses a pathless stop after a start reports a foreign live ID. | +| `capture-identity-mismatch` | The daemon refuses a stop with the wrong capture ID. The client also refuses a pathless stop when a settled record identifies a foreign live capture. An explicit caller path can still stop it. | | `capture-record-invalid` | The local capture destination record is unreadable or malformed, so no remote capture command is sent. | ### Command flags From b6696bbd85286240beb777bd03d1a35474d7b061 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 07:00:01 +0100 Subject: [PATCH 54/55] fix: preserve maestro failure reporting for unsafe selectors --- ...cade-execution-failure-suggestions.test.ts | 9 +++++++++ .../maestro/src/internal/facade-execution.ts | 20 +++++++++++++++---- .../maestro/src/internal/selector-regex.ts | 2 +- 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/packages/maestro/src/internal/__tests__/facade-execution-failure-suggestions.test.ts b/packages/maestro/src/internal/__tests__/facade-execution-failure-suggestions.test.ts index 852ec9a81f1..f356b97a8bd 100644 --- a/packages/maestro/src/internal/__tests__/facade-execution-failure-suggestions.test.ts +++ b/packages/maestro/src/internal/__tests__/facade-execution-failure-suggestions.test.ts @@ -68,6 +68,15 @@ describe('Maestro failure suggestion queries', () => { expect(suggestions.map(({ node, basis }) => [node.ref, basis])).toEqual([['e1', 'id']]); }); + test('an unsafe failed selector yields no suggestions', async () => { + const suggestions = await suggestionsFor( + ['appId: com.example.app', '---', '- tapOn:', ' id: (a+)+$', ''].join('\n'), + 'android', + [{ ...saveButton, identifier: 'a'.repeat(4096) }], + ); + expect(suggestions).toEqual([]); + }); + test('a coordinate tapOn has no selector to suggest from', async () => { const suggestions = await suggestionsFor( ['appId: com.example.app', '---', '- tapOn:', ' point: 50%,50%', ''].join('\n'), diff --git a/packages/maestro/src/internal/facade-execution.ts b/packages/maestro/src/internal/facade-execution.ts index 7295fde20c8..8e318c54290 100644 --- a/packages/maestro/src/internal/facade-execution.ts +++ b/packages/maestro/src/internal/facade-execution.ts @@ -1,5 +1,6 @@ import path from 'node:path'; import { isDeepLinkTarget } from '@agent-device/contracts/command'; +import { AppError } from '@agent-device/kernel/errors'; import type { SessionRuntimeHints } from '@agent-device/kernel/contracts'; import type { SnapshotNode } from '@agent-device/kernel/snapshot'; import type { SnapshotState } from '@agent-device/contracts/snapshot-model'; @@ -28,6 +29,7 @@ import { import type { MaestroReplayPlan } from './replay-plan-types.ts'; import { matchesMaestroTypedSelector } from './runtime-target-policy.ts'; import { rankMaestroCandidates } from './runtime-target-ranking.ts'; +import { MAESTRO_SELECTOR_REGEX_REASONS } from './selector-regex.ts'; const flowProgram = Symbol('maestroFlowProgram'); const failureCommand = Symbol('maestroFailureCommand'); @@ -190,10 +192,20 @@ 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) { + if ( + error instanceof AppError && + (error.details?.reason === MAESTRO_SELECTOR_REGEX_REASONS.unsafe.reason || + error.details?.reason === MAESTRO_SELECTOR_REGEX_REASONS.indeterminate.reason) + ) + return []; + throw error; + } } function createObserver( diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index 64e033dd186..71dc73873a5 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -2,7 +2,7 @@ import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { RegExpParser, visitRegExpAST, type AST } from '@eslint-community/regexpp'; import { normalizeText } from './shared.ts'; -const MAESTRO_SELECTOR_REGEX_REASONS = { +export const MAESTRO_SELECTOR_REGEX_REASONS = { // The selector pattern uses constructs that the bounded matcher cannot safely execute. unsafe: { reason: 'maestro_selector_regex_unsafe' }, // A multiline value might match across partial lines, so absence cannot be confirmed safely. From 7f9c92c2e8be82951557d3525c2d417dc6dcdac5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 07:00:10 +0100 Subject: [PATCH 55/55] fix: reduce capture certainty branch complexity --- .../remote/src/capture-destination-record.ts | 21 ++++++++++++------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/packages/remote/src/capture-destination-record.ts b/packages/remote/src/capture-destination-record.ts index ed362eed76a..20ffe65394b 100644 --- a/packages/remote/src/capture-destination-record.ts +++ b/packages/remote/src/capture-destination-record.ts @@ -207,14 +207,19 @@ function certaintyAfterStart( if (order < (current.active?.order ?? 0)) return current.certainty; if (response?.ok === true && response.data?.clientCaptureId === generation) return 'settled'; const details = refusalDetails(response, failure); - if (details?.reason === CAPTURE_IDENTITY_REASONS.alreadyActive.reason) { - if (current.active && details.clientCaptureId === current.active.generation) - return current.certainty; - if (current.pending.some((pending) => pending.generation === details.clientCaptureId)) - return current.certainty === 'foreign' ? 'foreign' : 'unknown'; - if (current.certainty === 'settled' && typeof details.clientCaptureId === 'string') - return 'foreign'; - } + if (details?.reason === CAPTURE_IDENTITY_REASONS.alreadyActive.reason) + return certaintyAfterAlreadyActive(current, details.clientCaptureId); + return current.certainty === 'foreign' ? 'foreign' : 'unknown'; +} + +function certaintyAfterAlreadyActive( + current: RecordState, + clientCaptureId: unknown, +): CaptureCertainty { + if (current.active && clientCaptureId === current.active.generation) return current.certainty; + if (current.pending.some((pending) => pending.generation === clientCaptureId)) + return current.certainty === 'foreign' ? 'foreign' : 'unknown'; + if (current.certainty === 'settled' && typeof clientCaptureId === 'string') return 'foreign'; return current.certainty === 'foreign' ? 'foreign' : 'unknown'; }