diff --git a/docs/adr/0041-credential-transport.md b/docs/adr/0041-credential-transport.md index c37b9a024da..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 has not shipped yet; it is tracked in #5182. +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 f64ef197f22..57518ff5ae3 100644 --- a/docs/agents/security.md +++ b/docs/agents/security.md @@ -1,20 +1,25 @@ # Security boundaries -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. -The daemon admits its state directory. Nobody trusts the network or other local users. +Reject daemon-chosen paths in scripts and remote record stops (#4518). +Use caller paths for trace/perf. Give unnamed captures unique cwd names. +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 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. 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 owns script destination writes and delivery limits. ## 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. +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/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/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-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..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 @@ -1,46 +1,37 @@ -// 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'); +test('a plain http daemon off loopback is refused before the token leaves', async () => { + const request = vi.spyOn(http, 'request').mockImplementation(() => { + throw new Error('insecure request reached the transport'); }); - 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 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 +41,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/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/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/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..846fbd18ed1 100644 --- a/packages/daemon/src/sessions/handlers/trace-runtime.ts +++ b/packages/daemon/src/sessions/handlers/trace-runtime.ts @@ -3,11 +3,7 @@ import type { DaemonResponse } from '@agent-device/kernel/contracts'; 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'; @@ -15,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; @@ -38,7 +36,8 @@ 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 captureIdentityRefusal('trace', 'already-active', session.trace.clientCaptureId); const outPath = expandSessionPath( req.positionals?.[1] ?? sessionStore.defaultTracePath(session), requestCwd(req, host), @@ -47,6 +46,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 +55,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 } : {}), + } satisfies TraceCommandResult, }; } @@ -67,6 +71,9 @@ 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 captureIdentityRefusal('trace', 'mismatch'); + const clientCaptureId = session.trace.clientCaptureId; const outPath = relocateTraceOutput( requestCwd(req, host), session.trace.outPath, @@ -86,6 +93,7 @@ function stopTrace( { trace: 'stopped', outPath, + ...(clientCaptureId ? { clientCaptureId } : {}), artifacts: [ { field: 'outPath', 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..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 @@ -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,7 +216,11 @@ async function startPerfCapture( request: Extract, ): Promise { if (session.perfCapture) { - return errorResponse('INVALID_ARGS', 'native perf capture already in progress'); + return captureIdentityRefusal( + 'native perf', + 'already-active', + session.perfCapture.clientCaptureId, + ); } if (!session.appBundleId) { return errorResponse('COMMAND_FAILED', 'No app is associated with this session.', { @@ -241,6 +246,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 +278,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 +303,8 @@ 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 captureIdentityRefusal('native perf', 'mismatch'); const snapshot = capture.handle.inspect(); const mismatchMessage = perfCaptureStopMismatch(snapshot, request); if (mismatchMessage) return errorResponse('INVALID_ARGS', mismatchMessage); @@ -315,7 +329,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/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/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..75b9654f375 100644 --- a/packages/kernel/src/errors.ts +++ b/packages/kernel/src/errors.ts @@ -496,6 +496,18 @@ 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 = { + // 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 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' }, +} 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/maestro/package.json b/packages/maestro/package.json index e21431628e5..5737d6edcf9 100644 --- a/packages/maestro/package.json +++ b/packages/maestro/package.json @@ -13,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/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__/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/__tests__/runtime-selector-resolution.test.ts b/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts index acec5e12a9e..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,6 +55,68 @@ test('rejects cyclic selector graphs explicitly', () => { expect(() => resolver.resolve(selector)).toThrow(/cannot contain cycles/); }); +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 }).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' }), + }), + ); +}); + 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__/runtime-target-policy.test.ts b/packages/maestro/src/internal/__tests__/runtime-target-policy.test.ts index e2a5972c4d3..664e4071c4d 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', () => { @@ -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__/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 ef53e98949b..96baf1aff09 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -1,10 +1,74 @@ -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`)).toBe(true); 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); + 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); + 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([ + '(a+)+', + '(a|aa)+', + '(?:(?:a|aa))*', + '(?:(?:a|ab)(?:c|bc))*', + 'a*a*', + 'a*b*a*', + '.*a.*b', + '.*x.*y.*z', + '.*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', + '(?:a+)a+b', + '(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('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('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', () => { @@ -12,4 +76,118 @@ test('extracts only patterns that are exact literals', () => { 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 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(`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); +}); + +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); + 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); + } + 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' }), + }), + ); +}); + +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); + expect(matchesMaestroRegex('one\rtwo', '^two$')).toBe(true); + expect(matchesMaestroRegex('one\ntwo', '^two$')).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}`)).toBe(false); +}); + +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( + 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|b)', '(a|b)')).toBe(true); + expect(matchesMaestroRegex('Terms ', 'Terms | Privacy')).toBe(true); + 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( + 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' }), + }), + ); +}); + +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/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/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/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 bc025276802..741aabc14a2 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, normalizeText } 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,16 +81,35 @@ 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); +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 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 { - return [node.label, extractNodeText(node), node.identifier] - .filter((value): value is string => Boolean(value)) - .some((value) => matchesMaestroSelectorValue(value, query)); +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..5326b0f3fb3 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,28 @@ 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 +74,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..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; @@ -66,15 +68,20 @@ export function resolveMaestroTargetFromSnapshot( options: { interactiveBounds?: boolean; presentation?: MaestroInteractivePresentation; + confirmedUnindexedExistence?: boolean; } = {}, ): MaestroTargetResolution { const presentedNodes = platform === 'ios' && options.presentation ? createPresentedNodeLookup(options.presentation) : undefined; - const candidates = presentedNodes - ? rankPresentedMaestroCandidates(snapshot, query, presentedNodes) - : rankMaestroCandidates(snapshot, query.selector, platform); + const candidates = rankTargetCandidates( + snapshot, + query, + platform, + presentedNodes, + options.confirmedUnindexedExistence, + ); if (!candidates.parentMatched) { return { ok: false, @@ -89,6 +96,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 +107,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.', @@ -112,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): { @@ -156,12 +203,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 b03d0982561..71dc73873a5 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -1,20 +1,345 @@ +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; +import { RegExpParser, visitRegExpAST, type AST } from '@eslint-community/regexpp'; +import { normalizeText } from './shared.ts'; + +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. + 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 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; wholeOnly: boolean; lineRegex?: RegExp }; +type Matcher = LiteralMatcher | { regex: RegExp; multilineRegex: RegExp; canSpanLines: boolean }; +const matcherCache = new Map(); + +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 (!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(); + return false; +} + +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); + } + matcher.lineRegex ??= new RegExp( + `^(?:${matcher.literal.replaceAll(/[\\^$.*+?()[\]{}|]/g, String.raw`\$&`)})$`, + 'im', + ); + return matcher.lineRegex.test(value); +} + +function matchesLongLiteralLine(value: string, literal: string): boolean { + const text = value.toLowerCase(); + const query = literal.toLowerCase(); + 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 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; + start = index + 1; + } + return regex.test(value.slice(start)); +} -export function matchesMaestroRegex(value: string, pattern: string): boolean { +function matcherForPattern(pattern: string): Matcher { + const cached = matcherCache.get(pattern); + if (cached) return cached; + const literal = literalFromMaestroRegex(pattern); + let matcher: Matcher; + if (literal !== undefined) { + 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'), + multilineRegex: new RegExp(`^(?:${pattern})$`, 'ims'), + canSpanLines, + }; + } catch { + unsafeMaestroRegex(); + } + } + if (matcherCache.size >= MAX_CACHED_PATTERNS) { + matcherCache.delete(matcherCache.keys().next().value!); + } + matcherCache.set(pattern, matcher); + return matcher; +} + +function assertBoundedMaestroPattern(pattern: string): boolean { + let parsed: AST.Pattern; try { - return new RegExp(`^(?:${pattern})$`, 'ims').test(value); + parsed = parser.parsePattern(pattern); } catch { - return value.toLocaleLowerCase() === pattern.toLocaleLowerCase(); + unsafeMaestroRegex(); + } + let ambiguousGroups = 0; + const countAlternatives = (count: number): void => { + if (count > 1 && ++ambiguousGroups > 4) unsafeMaestroRegex(); + }; + visitRegExpAST(parsed, { + onBackreferenceEnter: unsafeMaestroRegex, + onAssertionEnter(node) { + if ('alternatives' in node) unsafeMaestroRegex(); + }, + onGroupEnter(node) { + countAlternatives(node.alternatives.length); + }, + onCapturingGroupEnter(node) { + countAlternatives(node.alternatives.length); + }, + onQuantifierEnter(node) { + if ( + node.min > MAX_COUNTED_REPETITION || + (Number.isFinite(node.max) && node.max > MAX_COUNTED_REPETITION) + ) { + 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) { + 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[][] { + let paths: RegexElement[][] = [[]]; + for (const element of elements) { + paths = appendElement(paths, element); + } + return paths; +} + +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(); + } + } + return next; +} + +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 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 === 'Group' || + left.type === 'CapturingGroup' || + right.type === 'Group' || + right.type === 'CapturingGroup' + ) { + return false; } + 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.kind === 'digit' || element.kind === 'word') && !element.negate; + } + if (element.type !== 'CharacterClass' || element.negate) return false; + return element.elements.every((part) => { + if (part.type === 'Character') return part.value < 128; + if (part.type === 'CharacterClassRange') return part.max.value < 128; + return part.type === 'CharacterSet' && isAsciiOnly(part); + }); +} + +function unsafeMaestroRegex(): never { + throw new AppError('INVALID_ARGS', 'Maestro selector regular expression is too complex.', { + reason: MAESTRO_SELECTOR_REGEX_REASONS.unsafe.reason, + retriable: false, + }); +} + +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; + } try { new RegExp(pattern); } catch { 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/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..6db49dd22f0 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,12 @@ 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); + const body = await response.text(); + expect(JSON.parse(body)).toMatchObject({ ok: false, code: 'INVALID_ARGS' }); + expect(body).not.toMatch(/daemon-secret/); 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__/capture-destination-record.test.ts b/packages/remote/src/__tests__/capture-destination-record.test.ts new file mode 100644 index 00000000000..07e642d817d --- /dev/null +++ b/packages/remote/src/__tests__/capture-destination-record.test.ts @@ -0,0 +1,928 @@ +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'; +import { AppError } from '@agent-device/kernel/errors'; +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', + 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 } } : {}), + }, + }; +} + +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) => { + const stateDir = mkdtempForTestSync('capture-destination-'); + const destination = '/client/captures/owned.trace'; + await sendRemoteCapture( + endpoint, + request('start', destination, { family }), + stateDir, + async (req) => confirmed(req), + ); + const sent: DaemonWireRequest[] = []; + await sendRemoteCapture( + endpoint, + request('stop', undefined, { family }), + 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, + answer, + createTestHostEnvironment(), + stateDir, + ); + return answer; + }, + ); + expect(sent[0]?.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + expect(sent[0]?.meta?.captureId).toBeTypeOf('string'); + await sendRemoteCapture( + endpoint, + request('stop', undefined, { family }), + stateDir, + async (req) => { + sent.push(req); + return success; + }, + ); + expect(sent[1]?.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + expect(sent[1]?.meta?.captureId).toBeUndefined(); + }, +); + +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(); + return success; + }); + return confirmed(start); + }); + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.captureId).toBe(newCaptureId); + 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 (req) => confirmed(req), + ); + 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?.captureId).toBeUndefined(); + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }); + }, +); + +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.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.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); + 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; + }, + ); + }, +); + +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('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; + 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); + }, + ); + 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', clientCaptureId: firstId }, + }, + }), + ); + await second; + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.captureId).toBeUndefined(); + 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?.captureId).toBeUndefined(); + 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.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( + 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.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); + 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.certainty).toBe('unknown'); + 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( + endpoint, + request('start', '/client/owned.trace'), + stateDir, + async (req) => confirmed(req), + ); + await sendRemoteCapture( + endpoint, + request('stop', undefined, { tenantId: 'tenant-b' }), + stateDir, + async (req) => { + expect(req.meta?.captureId).toBeUndefined(); + 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?.captureId).toBeUndefined(); + 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 (req) => confirmed(req), + ); + 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?.captureId).toBeUndefined(); + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }); + } + await sendRemoteCapture( + endpoint, + request('stop', undefined, { family: 'perf' }), + stateDir, + async (req) => { + const answer = confirmed(req); + expect( + (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + ).toBe('/client/owned.trace'); + return answer; + }, + ); +}); diff --git a/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts b/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts index 4698ce5a51b..6937762fbed 100644 --- a/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts +++ b/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts @@ -81,8 +81,10 @@ type MaterializationCase = { localPath: string; field?: string; fileName?: string; + artifactType?: string; expected?: string; generatedName?: RegExp; + protectedPath?: string; }; const posixNameCases: MaterializationCase[] = [ @@ -91,7 +93,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', @@ -99,7 +101,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}$/, }, ]; @@ -113,11 +115,34 @@ 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: '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: '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', @@ -129,7 +154,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', @@ -137,21 +162,35 @@ 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 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', + }, + { + 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; 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 { @@ -175,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 }), @@ -190,9 +229,11 @@ 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'); expect(fs.existsSync(inRoot('outside'))).toBe(false); } finally { await closeLoopbackServer(server); @@ -222,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/__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/capture-destination-record.ts b/packages/remote/src/capture-destination-record.ts new file mode 100644 index 00000000000..20ffe65394b --- /dev/null +++ b/packages/remote/src/capture-destination-record.ts @@ -0,0 +1,432 @@ +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 { 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'; + +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 CaptureCertainty = 'settled' | 'unknown' | 'foreign'; +type RecordState = { + active?: Active; + pending: Pending[]; + certainty: CaptureCertainty; + nextOrder: number; +}; +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 sessionRecordDir(stateDir: string, baseUrl: string, req: DaemonWireRequest): 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, + ]), + ) + .digest('hex'); + 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 { + let serialized: string; + try { + serialized = fs.readFileSync(file, 'utf8'); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; + invalidRecord(error); + } + let value: unknown; + try { + value = JSON.parse(serialized); + } catch (error) { + invalidRecord(error); + } + 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' && + (active.destination === undefined || + (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; + 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(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 { + fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); + publishFileSync({ destination: file, contents: `${JSON.stringify(record)}\n`, mode: 0o600 }); +} + +function settleRecord(file: string, record: RecordState): void { + if (!record.active && record.pending.length === 0 && record.certainty === 'settled') + fs.rmSync(file, { force: true }); + else writeRecord(file, record); +} + +function refusalDetails(response: DaemonResponse | undefined, failure: unknown) { + if (response?.ok === false) return response.error.details; + return failure instanceof AppError ? failure.details : undefined; +} + +function confirmedStartCapture( + response: Extract, + generation: string, + destination: string | undefined, + order: number, +): Active | undefined { + if (response.data?.clientCaptureId !== generation) return undefined; + return { + generation, + ...(typeof destination === 'string' && path.isAbsolute(destination) ? { destination } : {}), + order, + }; +} + +function activeAfterStart( + current: RecordState, + response: DaemonResponse | undefined, + failure: unknown, + 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 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; + return active; +} + +function recordAfterStart( + current: RecordState, + response: DaemonResponse | undefined, + failure: unknown, + generation: string, + destination: string | undefined, + order: number, +): RecordState { + const active = activeAfterStart(current, response, failure, generation, destination, order); + return { + ...(active ? { active } : {}), + pending: current.pending.filter((candidate) => candidate.generation !== generation), + 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) + 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'; +} + +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: Send, +): Promise { + const capture = captureOf(req); + if (!capture) return await sendWithoutCapture(baseUrl, req, stateDir, send); + const file = recordFile(stateDir, baseUrl, req, capture.family); + 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 hasExplicitPath = typeof req.meta?.clientArtifactPaths?.outPath === 'string'; + const { active, foreignBeforeStop } = await withRecordLock(file, async () => { + const current = readRecord(file); + if (current?.certainty === 'foreign' && !hasExplicitPath) + throw new AppError('INVALID_ARGS', 'Remote capture identity changed', { + reason: CAPTURE_IDENTITY_REASONS.mismatch.reason, + }); + return { + active: + current?.pending.length === 0 && current.certainty === 'settled' + ? current.active + : undefined, + foreignBeforeStop: current?.certainty === 'foreign' ? JSON.stringify(current) : undefined, + }; + }); + 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 } }; + 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) + await retireSuccessfulCaptureStop(sent); + 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, + send: Send, +): Promise { + const generation = crypto.randomUUID(); + 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, order: nextOrder }], + certainty: current?.certainty ?? 'settled', + nextOrder, + }); + return nextOrder; + }); + 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.some((pending) => pending.generation === generation)) return; + settleRecord( + file, + recordAfterStart(current, response, failure, generation, destination, order), + ); + }); + if (threw) throw failure; + if (!response) throw new TypeError('Capture start settled without a response'); + 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?.active?.generation === owned.generation) + settleRecord(owned.file, { + pending: current.pending, + certainty: current.certainty, + nextOrder: current.nextOrder, + }); + }); +} + +/** 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.certainty === 'settled' && + current.active?.generation === owned.generation + ? current.active + : undefined; + }); + if (!active?.destination || typeof req.meta?.clientArtifactPaths?.outPath === 'string') + return req; + return { + ...req, + meta: { + ...req.meta, + clientArtifactPaths: { ...req.meta?.clientArtifactPaths, outPath: active.destination }, + }, + }; +} + +async function snapshotSessionCaptures( + baseUrl: string, + req: DaemonWireRequest, + stateDir: string, +): 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 new Map(); + throw error; + } + const records = new Map(); + for (const entry of entries) { + const file = path.join(dir, entry); + 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 }); + }); + } +} diff --git a/packages/remote/src/daemon-artifacts.ts b/packages/remote/src/daemon-artifacts.ts index 8d6d546aed8..cd632c59fd7 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,10 +534,13 @@ export async function materializeRemoteArtifacts( stateDir: string, ): 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 ( @@ -604,11 +615,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); @@ -722,29 +735,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 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( @@ -761,13 +757,33 @@ 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 }; - } - if (hasNonEmptyString(artifact.localPath) && finishesEarlierClientCapture(req)) { - return { path: artifact.localPath, fallback: false }; + 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: fallbackPath, fallback: false } : undefined; + return fallbackPath + ? { path: uniqueClientArtifactPath(fallbackPath), fallback: false } + : undefined; +} + +function uniqueClientArtifactPath(candidate: string): string { + const rawExtension = path.extname(candidate); + 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; + 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; + stemBytes += nextBytes; + } + return path.join(path.dirname(candidate), `${stem || 'artifact'}${suffix}`); } function resolveOrdinaryArtifactFallbackPath( @@ -782,7 +798,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); } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 311e223d79e..26c5fca09e6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -737,6 +737,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 diff --git a/scripts/__tests__/package-closure-audit.test.ts b/scripts/__tests__/package-closure-audit.test.ts index 4f2742eb26e..b91c790d268 100644 --- a/scripts/__tests__/package-closure-audit.test.ts +++ b/scripts/__tests__/package-closure-audit.test.ts @@ -17,7 +17,70 @@ 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, + 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()), + /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/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..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). @@ -28,11 +29,17 @@ import os from 'node:os'; 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 { listTrackedPackageManifests } from './layering/tracked-sources.ts'; import { assertBundledLicenseNotices, + BUNDLED_LICENSE_NOTICES_PATH, parseNpmPackOutput, type NpmPackEntry, } from './size-report-package.mjs'; @@ -282,6 +289,30 @@ 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 = 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'), + ); + assertBundledWorkspaceDependencies( + bundledWorkspaceDependencies, + new Set(notices.attributions.map(({ label }) => label)), + importedBy, + ); + 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/scripts/lib/shipped-imports.ts b/scripts/lib/shipped-imports.ts index 6acf2b83abb..7dd6a08531a 100644 --- a/scripts/lib/shipped-imports.ts +++ b/scripts/lib/shipped-imports.ts @@ -59,6 +59,42 @@ 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, + 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.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/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/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-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 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/integration/provider-scenarios/provider-device-runtime.test.ts b/test/integration/provider-scenarios/provider-device-runtime.test.ts index 98443f6abde..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,7 +155,11 @@ 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.equal(details.failedPlugins, undefined); + assert.equal( + error.hint, + 'Restart the daemon with testmu configured, 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 ca2e0a2d1f4..bfbd23526c0 100644 --- a/test/integration/provider-scenarios/remote-daemon-client.test.ts +++ b/test/integration/provider-scenarios/remote-daemon-client.test.ts @@ -549,11 +549,15 @@ 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]{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 new file mode 100644 index 00000000000..5911943cc9a --- /dev/null +++ b/test/repo-guards/maestro-regex-owner.test.ts @@ -0,0 +1,213 @@ +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; + 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 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; + } + 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 ?? []) 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); + } + } + 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); + } + } + } + function isRegexBypass(node: Node, scope: Scope): boolean { + if (node.type !== 'NewExpression' && node.type !== 'CallExpression') return false; + if (isRegexReference(node.callee, scope)) return true; + 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 ( + (name === 'match' || name === 'matchAll' || name === 'search') && + node.arguments?.[0]?.regex === undefined + ); + } + function scopeForNode(node: Node, scope: Scope): Scope { + 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; + } + 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; + } + 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}`); + } + for (const child of Object.values(node)) visit(child, local); + } + visit(parsed.program, { bindings: new Map() }); + 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)", + '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, 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/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 4b09ff1ba14..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,9 +159,9 @@ "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#resolveMaterializedArtifactPath": "sha256:06dc215c06a9d2ea5a3821faf31b297a2e2f63928672c08c637b132beee726be", - "packages/remote/src/daemon-artifacts.ts#resolveOrdinaryArtifactFallbackPath": "sha256:e8b1cb5243194e1d4fc7e376979ca5aae3aaf55cfdd33102e1410b2033fb3a4f", + "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", "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", @@ -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", @@ -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", @@ -539,8 +549,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: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", @@ -664,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: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", diff --git a/tsdown.config.ts b/tsdown.config.ts index 5412d1a2040..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,38 +87,7 @@ export default defineConfig({ entry: buildEntries, deps: { alwaysBundle: [/^@agent-device\//], - onlyBundle: [ - '@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: { diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 2c391391f6d..ff2fba3c84c 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -596,6 +596,14 @@ 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 when one was minted. | +| `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 | Reason | Meaning | @@ -873,6 +881,13 @@ 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. | +| `maestro_selector_regex_indeterminate` | A multiline value might match across partial lines, so absence cannot be confirmed safely. | + ### Metro reload | Reason | Meaning | @@ -935,7 +950,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/remote-proxy.md b/website/docs/docs/remote-proxy.md index 0a71f2c0a50..1d2bf1e9942 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 @@ -94,14 +94,15 @@ 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 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. +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 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/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index fdf4e5d7606..d99dacb17af 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` 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 2be64326234..cb5e7391ac1 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, 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 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 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: