diff --git a/packages/command-registry/src/flag-definitions-connection.ts b/packages/command-registry/src/flag-definitions-connection.ts index eb2e90ff9d..9a02452cbb 100644 --- a/packages/command-registry/src/flag-definitions-connection.ts +++ b/packages/command-registry/src/flag-definitions-connection.ts @@ -309,7 +309,7 @@ export const CONNECTION_FLAG_DEFINITIONS: readonly FlagDefinition[] = [ type: 'boolean', usageLabel: '--provider-network-logs', usageDescription: - 'Limrun: capture session network traffic into a live HAR file on the daemon host; artifacts and close print its path and any tunnel failures. Pass --provider-network-hosts with your app API hosts. Captured traffic exits through the daemon host, the HAR holds raw headers and bodies, certificate-pinned hosts fail, and DNS-over-HTTPS bypasses the capture', + 'Limrun: capture session network traffic; artifacts and close write it as a HAR file on the daemon host and print its path and any capture failures. Pass --provider-network-hosts with your app API hosts. Captured traffic exits through the daemon host, the HAR holds raw headers and bodies, certificate-pinned hosts and HTTPS hosts without HTTP/2 fail to connect, and DNS-over-HTTPS bypasses the capture', projectConfig: false, recorded: false, }, diff --git a/packages/contracts/src/remote-config-fields.ts b/packages/contracts/src/remote-config-fields.ts index b2f7d32d4d..8e0e0065ab 100644 --- a/packages/contracts/src/remote-config-fields.ts +++ b/packages/contracts/src/remote-config-fields.ts @@ -43,7 +43,7 @@ export type CloudProviderProfileFields = { providerNoResignApp?: boolean; /** * Asks a provider that supports it to capture session network traffic and deliver it as a HAR - * artifact. On Limrun the HAR is a live file the session writes while it runs. + * artifact. */ providerNetworkLogs?: boolean; /** With `providerNetworkLogs`: comma-separated tunnel selectors replacing the default capture list. */ diff --git a/packages/provider-limrun/src/network-har.test.ts b/packages/provider-limrun/src/network-har.test.ts deleted file mode 100644 index bb9f2b7d47..0000000000 --- a/packages/provider-limrun/src/network-har.test.ts +++ /dev/null @@ -1,349 +0,0 @@ -import assert from 'node:assert/strict'; -import { test, vi } from 'vitest'; -import fs from 'node:fs'; -import path from 'node:path'; -import type { DestinationTunnelInspectionEvent } from '@limrun/api/destination-tunnel-inspection'; -import { DestinationTunnelSessionError } from '@limrun/api/destination-tunnel-dialer'; -import { mkdtempForTestSync } from './tmp-dir.fixtures.ts'; -import { - DEFAULT_LIMRUN_HAR_SELECTORS, - HAR_MAX_BYTES, - startLimrunHarCapture, -} from './network-har.ts'; - -function harEntry(url: string, error?: string, comment?: string): DestinationTunnelInspectionEvent { - return { - type: 'complete', - sequence: 1, - requestId: `req-${url}`, - data: { - startedDateTime: new Date().toISOString(), - time: 12, - request: { - method: 'GET', - url, - httpVersion: 'HTTP/1.1', - cookies: [], - headers: [], - queryString: [], - headersSize: -1, - bodySize: 0, - }, - ...(comment ? { comment } : {}), - response: { - // The tunnel reports a request it could not complete with status 0. - status: error ? 0 : 200, - statusText: error ? '' : 'OK', - httpVersion: 'HTTP/1.1', - cookies: [], - headers: [], - content: { size: 0, mimeType: 'application/json' }, - redirectURL: '', - headersSize: -1, - bodySize: 0, - }, - cache: {}, - timings: { send: 0, wait: 10, receive: 2 }, - _limrun: { tunnelId: 't1', selectorId: 's1', ...(error ? { error } : {}) }, - }, - } as unknown as DestinationTunnelInspectionEvent; -} - -function fakeTunnelClient( - lastDialFailure?: { - tunnelId: string; - selectorId: string; - reason: string; - osCode?: string; - }, - tunnelClose: () => void = () => {}, -) { - const started: { - selectors: string[]; - onEvent?: (e: DestinationTunnelInspectionEvent) => void; - onError?: (error: Error) => void; - }[] = []; - return { - started, - client: { - startTunnel: async (options: { - selectors: string[]; - onInspectionEvent?: (event: DestinationTunnelInspectionEvent) => void; - onInspectionError?: (error: Error) => void; - }) => { - started.push({ - selectors: options.selectors, - onEvent: options.onInspectionEvent, - onError: options.onInspectionError, - }); - return { - tunnelId: 't1', - selectors: [{ id: 's1', kind: 'domain', value: '*.com' }], - close: tunnelClose, - } as never; - }, - getTunnelStatus: async () => (lastDialFailure ? { lastDialFailure } : {}), - }, - }; -} - -function tempHarPath(): string { - return path.join(mkdtempForTestSync('limrun-har-'), 'session', 'har.har'); -} - -test('the default capture selectors carry the public wildcards and the Metro route', () => { - assert.ok(DEFAULT_LIMRUN_HAR_SELECTORS.includes('*.com')); - // One tunnel per instance: the Metro/companion route must ride this same tunnel. - assert.ok(DEFAULT_LIMRUN_HAR_SELECTORS.includes('localhost:8081')); -}); - -function readEntries(harPath: string): { response: { status: number } }[] { - return ( - JSON.parse(fs.readFileSync(harPath, 'utf8')) as { - log: { entries: { response: { status: number } }[] }; - } - ).log.entries; -} - -function readEntryCount(harPath: string): number { - return readEntries(harPath).length; -} - -test('completed requests reach the live HAR in one coalesced, owner-only write', async () => { - const fake = fakeTunnelClient(); - const harPath = tempHarPath(); - // An existing, wider directory is tightened too. - fs.mkdirSync(path.dirname(harPath), { recursive: true, mode: 0o755 }); - const result = await startLimrunHarCapture(fake.client, { harPath }); - assert.equal(result.ok, true); - if (!result.ok) return; - const emit = fake.started[0]?.onEvent; - assert.ok(emit); - emit(harEntry('https://example.com/a')); - emit(harEntry('https://example.com/b')); - assert.equal(readEntryCount(harPath), 0); - - await vi.waitFor(() => assert.equal(readEntryCount(harPath), 2)); - const document = JSON.parse(fs.readFileSync(harPath, 'utf8')) as { - log: { version: string; entries: unknown[] }; - }; - assert.equal(document.log.version, '1.2'); - assert.equal(document.log.entries.length, 2); - assert.equal(fs.statSync(harPath).mode & 0o777, 0o600); - assert.equal(fs.statSync(path.dirname(harPath)).mode & 0o777, 0o700); - - // Close flushes a request that is still inside the coalescing window. - emit(harEntry('https://example.com/c')); - await result.capture.close(); - assert.equal(readEntryCount(harPath), 3); - assert.deepEqual( - fs.readdirSync(path.dirname(harPath)).filter((name) => name.endsWith('.tmp')), - [], - ); -}); - -test('the HAR keeps the newest entries under its size cap and reports the dropped ones', async () => { - const fake = fakeTunnelClient(); - const harPath = tempHarPath(); - const result = await startLimrunHarCapture(fake.client, { harPath }); - assert.equal(result.ok, true); - if (!result.ok) return; - const emit = fake.started[0]?.onEvent; - assert.ok(emit); - // Two UTF-8 bytes per character: a quarter of the cap in bytes, an eighth in string length. - const large = 'é'.repeat(Math.ceil(HAR_MAX_BYTES / 8)); - for (let index = 0; index < 6; index += 1) { - emit(harEntry(`https://example.com/${index}`, undefined, large)); - } - await result.capture.close(); - - const urls = ( - JSON.parse(fs.readFileSync(harPath, 'utf8')) as { - log: { entries: { request: { url: string } }[] }; - } - ).log.entries.map((entry) => entry.request.url); - assert.deepEqual(urls, [ - 'https://example.com/3', - 'https://example.com/4', - 'https://example.com/5', - ]); - assert.ok(fs.statSync(harPath).size <= HAR_MAX_BYTES); - const report = await result.capture.failures(); - assert.equal(report.byKind['har-truncated']?.count, 3); -}); - -test('a relative HAR path is refused before any directory is touched', async () => { - const fake = fakeTunnelClient(); - const result = await startLimrunHarCapture(fake.client, { harPath: 'capture.har' }); - assert.equal(result.ok, false); - if (result.ok) return; - assert.equal(result.reason, 'tunnel-start-failed'); - assert.equal(fake.started.length, 0); -}); - -test('a capture whose HAR cannot be written refuses before the tunnel opens', async () => { - const fake = fakeTunnelClient(); - const harPath = tempHarPath(); - // A non-empty directory where the HAR belongs: the rename into place fails. - fs.mkdirSync(harPath, { recursive: true }); - fs.writeFileSync(path.join(harPath, 'occupied'), ''); - const result = await startLimrunHarCapture(fake.client, { harPath }); - assert.equal(result.ok, false); - if (result.ok) return; - assert.equal(result.reason, 'tunnel-start-failed'); - assert.equal(fake.started.length, 0); - assert.deepEqual(fs.readdirSync(path.dirname(harPath)), [path.basename(harPath)]); -}); - -test('a tunnel that refuses to close still gets its HAR written, and a later close retries', async () => { - let closeAttempts = 0; - const fake = fakeTunnelClient(undefined, () => { - closeAttempts += 1; - if (closeAttempts === 1) throw new Error('socket busy'); - }); - const harPath = tempHarPath(); - const result = await startLimrunHarCapture(fake.client, { harPath }); - assert.equal(result.ok, true); - if (!result.ok) return; - fake.started[0]?.onEvent?.(harEntry('https://example.com/a')); - - await assert.rejects(() => result.capture.close(), /socket busy/); - assert.equal(readEntryCount(harPath), 1); - await result.capture.close(); - await result.capture.close(); - assert.equal(closeAttempts, 2); -}); - -test('tunnel failures are counted, with the latest endpoints and the typed dial reason', async () => { - const fake = fakeTunnelClient({ - tunnelId: 't1', - selectorId: 's1', - reason: 'dns_not_found', - osCode: 'ENOTFOUND', - }); - const result = await startLimrunHarCapture(fake.client, { harPath: tempHarPath() }); - assert.equal(result.ok, true); - if (!result.ok) return; - const started = fake.started[0]; - assert.ok(started?.onEvent && started.onError); - started.onEvent(harEntry('https://example.com/ok')); - started.onEvent( - harEntry('https://missing.example.com/a', 'tunnel client could not open the destination'), - ); - started.onEvent({ - type: 'inspection_error', - sequence: 3, - data: { host: 'pinned.example.com', port: 443, message: 'terminate app TLS: EOF' }, - }); - started.onEvent({ - type: 'gap', - sequence: 9, - data: { fromSequence: 4, toSequence: 8, message: 'events dropped' }, - }); - started.onError(new Error('inspection stream closed')); - - const report = await result.capture.failures(); - assert.equal(report.total, 4); - const endpoints = Object.fromEntries( - Object.entries(report.byKind).map(([kind, entry]) => [ - kind, - { count: entry.count, latest: entry.latest.map(({ host, port }) => ({ host, port })) }, - ]), - ); - assert.deepEqual(endpoints, { - 'request-failed': { count: 1, latest: [{ host: 'missing.example.com', port: 443 }] }, - 'inspection-error': { count: 1, latest: [{ host: 'pinned.example.com', port: 443 }] }, - 'inspection-gap': { count: 1, latest: [{ host: undefined, port: undefined }] }, - 'inspection-stream-error': { count: 1, latest: [{ host: undefined, port: undefined }] }, - }); - assert.deepEqual(report.lastDialFailure, { - reason: 'dns_not_found', - osCode: 'ENOTFOUND', - selector: '*.com', - }); - // The failed request stays in the HAR, as a status-0 entry. - await result.capture.close(); - assert.deepEqual( - readEntries(result.capture.harPath).map((entry) => entry.response.status), - [200, 0], - ); -}); - -test('inspection errors from pinned hosts do not evict failed requests', async () => { - const fake = fakeTunnelClient(); - const result = await startLimrunHarCapture(fake.client, { harPath: tempHarPath() }); - assert.equal(result.ok, true); - if (!result.ok) return; - const emit = fake.started[0]?.onEvent; - assert.ok(emit); - emit(harEntry('https://api.example.com/login', 'client_dial_failed')); - for (let sequence = 0; sequence < 20; sequence += 1) { - emit({ - type: 'inspection_error', - sequence, - data: { host: 'pinned.example.com', port: 443, message: 'terminate app TLS: EOF' }, - }); - } - const report = await result.capture.failures(); - assert.equal(report.total, 21); - assert.equal(report.byKind['inspection-error']?.count, 20); - assert.equal(report.byKind['inspection-error']?.latest.length, 5); - assert.equal(report.byKind['request-failed']?.latest[0]?.host, 'api.example.com'); - await result.capture.close(); -}); - -test("another tunnel's dial failure is not reported as this capture's", async () => { - const fake = fakeTunnelClient({ tunnelId: 'older', selectorId: 's1', reason: 'client_timeout' }); - const result = await startLimrunHarCapture(fake.client, { harPath: tempHarPath() }); - assert.equal(result.ok, true); - if (!result.ok) return; - const report = await result.capture.failures(); - assert.equal(report.total, 0); - assert.equal(report.lastDialFailure, undefined); - await result.capture.close(); -}); - -test('a tunnel conflict is reported as a typed refusal, not a crash', async () => { - const result = await startLimrunHarCapture( - { - startTunnel: async () => { - throw new DestinationTunnelSessionError('already_active'); - }, - }, - { harPath: tempHarPath() }, - ); - assert.equal(result.ok, false); - if (result.ok) return; - assert.equal(result.reason, 'tunnel-in-use'); -}); - -test('conflict text without the typed session error code is not a tunnel conflict', async () => { - const result = await startLimrunHarCapture( - { - startTunnel: async () => { - throw new Error('destination tunnel failed: already_active'); - }, - }, - { harPath: tempHarPath() }, - ); - assert.equal(result.ok, false); - if (result.ok) return; - assert.equal(result.reason, 'tunnel-start-failed'); -}); - -test('a rejected selector is refused before any tunnel opens', async () => { - let opened = false; - const result = await startLimrunHarCapture( - { - startTunnel: async () => { - opened = true; - return {} as never; - }, - }, - { harPath: tempHarPath(), selectors: ['not a host!!'] }, - ); - assert.equal(result.ok, false); - if (result.ok) return; - assert.equal(result.reason, 'tunnel-start-failed'); - assert.equal(opened, false); -}); diff --git a/packages/provider-limrun/src/network-har.ts b/packages/provider-limrun/src/network-har.ts index 3ca3094fc1..cde0178378 100644 --- a/packages/provider-limrun/src/network-har.ts +++ b/packages/provider-limrun/src/network-har.ts @@ -1,45 +1,39 @@ import { DestinationTunnelHARAssembler } from '@limrun/api/destination-tunnel-har'; import { validateDestinationTunnelSelectors } from '@limrun/api/destination-tunnel'; import { DestinationTunnelSessionError } from '@limrun/api/destination-tunnel-dialer'; -import type { DestinationTunnelOpenFailureReason } from '@limrun/api/destination-tunnel'; +import type { DestinationTunnelHAREntry } from '@limrun/api/destination-tunnel-har'; import type { DestinationTunnelInspectionEvent } from '@limrun/api/destination-tunnel-inspection'; import type { DestinationTcpTunnel } from '@limrun/api/destination-tunnel-dialer'; import fs from 'node:fs'; import path from 'node:path'; /** - * The Limrun network capture: one destination tunnel with inspection, streamed into a live HAR 1.2 - * file. The file is replaced whole after completed requests, so a reader (jq included) always sees - * a valid document, during the session and after it. Memory and the cost of each write stay - * bounded however long the session runs: bodies are cut at `HAR_BODY_LIMIT_BYTES`, and the - * oldest entries leave the file once it would pass `HAR_MAX_BYTES`. + * The Limrun network capture: one destination tunnel with inspection. Completed requests stay in + * memory, with each body cut to `HAR_BODY_LIMIT_BYTES` and at most `HAR_MAX_ENTRIES` entries, and + * `writeLimrunHar` writes them as a HAR 1.2 file when `artifacts` or close asks for it. * - * One instance carries one destination tunnel, so the Metro/companion route rides this same - * tunnel: the default selectors include the `localhost:8081` route, which makes the host's Metro - * reachable from the device through the tunnel. + * One instance carries one destination tunnel, so the Metro route rides this tunnel: the default + * selectors include `localhost:8081`. * - * Known limits: certificate-pinned hosts fail closed against the tunnel's interception, and apps - * that resolve names over DNS-over-HTTPS bypass the capture entirely. Captured traffic leaves from - * the daemon host, not from the device's network. - * - * Tunnel failures never reach the HAR's readers on their own: the SDK logs dial failures only to - * the console. The capture therefore records the typed inspection failures (a request the tunnel - * could not complete, an inspection error, a stream gap) and reads the tunnel's last typed dial - * failure on demand, so `artifacts` and close can report them. + * The SDK logs tunnel failures only to the console, so the capture counts the typed ones itself + * and reads the tunnel's last typed dial failure on demand. */ /** Generic public-TLD wildcards, measured acceptable by Limrun's selector validation. */ -export const DEFAULT_LIMRUN_HAR_SELECTORS = Object.freeze([ +const DEFAULT_LIMRUN_HAR_SELECTORS = Object.freeze([ '*.com', '*.org', '*.app', '*.net', '*.io', '*.dev', - // The Metro/companion route: the device reaches this host's Metro through the one tunnel. 'localhost:8081', ] as const); +const HAR_BODY_LIMIT_BYTES = 64 * 1024; +const HAR_MAX_ENTRIES = 500; +const TUNNEL_STATUS_BUDGET_MS = 2_000; + export type LimrunHarTunnelClient = Readonly<{ startTunnel(options: { selectors: string[]; @@ -48,172 +42,98 @@ export type LimrunHarTunnelClient = Readonly<{ onInspectionError?: (error: Error) => void; }): Promise; getTunnelStatus?(): Promise< - Readonly<{ - lastDialFailure?: Readonly<{ - tunnelId: string; - selectorId: string; - reason: DestinationTunnelOpenFailureReason; - osCode?: string; - }>; - }> + Readonly<{ lastDialFailure?: Readonly<{ tunnelId: string; reason: string }> }> >; }>; /** - * What failed inside the capture: - * - `request-failed`: the tunnel accepted the device's request but could not complete it, for - * example a destination that did not resolve, refused, or timed out. The HAR holds the entry - * with status 0. - * - `inspection-error`: the tunnel could not inspect a connection, usually a certificate-pinned - * host that rejected the interception. - * - `inspection-gap`: the inspection stream skipped events, so the HAR misses requests. - * - `inspection-stream-error`: the inspection stream itself failed. - * - `har-write-failed`: the HAR file could not be written, so it lags the captured traffic. - * - `har-truncated`: the oldest entries left the HAR to keep it under its size cap; the count is - * the number of entries dropped. + * - `request-failed`: the tunnel could not complete a request; its HAR entry has status 0. + * - `inspection-error`: the tunnel could not inspect a connection, usually a pinned certificate. + * - `inspection-gap`, `inspection-stream-error`: the HAR misses requests. */ -export type LimrunTunnelFailureKind = +export type LimrunNetworkFailureKind = | 'request-failed' | 'inspection-error' | 'inspection-gap' - | 'inspection-stream-error' - | 'har-write-failed' - | 'har-truncated'; - -export type LimrunTunnelFailure = Readonly<{ - at: string; - host?: string; - port?: number; - /** The provider's own description, kept verbatim for a human reader. */ - message: string; -}>; - -export type LimrunTunnelFailureReport = Readonly<{ - total: number; - /** - * Each kind's count and its most recent failures, oldest first. Kinds are kept apart, so the - * inspection errors of pinned system hosts cannot push an app's failed requests out. - */ - byKind: Readonly< - Partial< - Record< - LimrunTunnelFailureKind, - Readonly<{ count: number; latest: readonly LimrunTunnelFailure[] }> - > - > - >; - /** The tunnel's most recent dial failure, with the provider's typed reason. */ - lastDialFailure?: Readonly<{ - reason: DestinationTunnelOpenFailureReason; - osCode?: string; - selector?: string; - }>; + | 'inspection-stream-error'; + +export type LimrunNetworkFailures = Readonly<{ + count: number; + last?: Readonly<{ kind: LimrunNetworkFailureKind; host?: string; port?: number }>; + /** The tunnel's most recent dial failure reason, such as `dns_not_found`. */ + lastDialFailure?: string; + /** How many of the oldest entries left the HAR to keep it under `HAR_MAX_ENTRIES`. */ + truncated: number; }>; -const LATEST_FAILURES_PER_KIND = 5; -const TUNNEL_STATUS_BUDGET_MS = 2_000; -/** Completed requests within this window share one rewrite of the HAR file. */ -const HAR_WRITE_COALESCE_MS = 250; -/** Each request and response body is cut to this size, by the tunnel and by the assembler. */ -const HAR_BODY_LIMIT_BYTES = 64 * 1024; -/** The serialized entries a HAR file keeps; older entries are dropped first. */ -export const HAR_MAX_BYTES = 8 * 1024 * 1024; - export type LimrunHarCapture = Readonly<{ - harPath: string; - /** - * Stops inspection and writes the final HAR document. Safe more than once; when the tunnel - * refuses to close, the HAR is still written and a later call tries the tunnel again. - */ - close(): Promise; - /** The failures recorded so far, plus the tunnel's last dial failure while it is open. */ - failures(): Promise; -}>; - -export type LimrunHarCaptureFailure = Readonly<{ - reason: 'tunnel-in-use' | 'tunnel-start-failed' | 'capture-dir-unset'; - message: string; + entries(): readonly DestinationTunnelHAREntry[]; + failures(): Promise; + close(): void; }>; export type LimrunHarCaptureResult = | Readonly<{ ok: true; capture: LimrunHarCapture }> - | Readonly<{ ok: false } & LimrunHarCaptureFailure>; + | Readonly<{ ok: false; reason: 'tunnel-in-use' | 'tunnel-start-failed'; message: string }>; -/** - * Opens the instance's destination tunnel with inspection and writes every completed request into - * `harPath` as a HAR 1.2 document. Bodies are captured; the file holds raw traffic. - */ +/** Opens the instance's destination tunnel with inspection. Bodies are captured. */ export async function startLimrunHarCapture( client: LimrunHarTunnelClient, - input: Readonly<{ harPath: string; selectors?: readonly string[] }>, + hosts: readonly string[] | undefined, ): Promise { - const selectors = [...(input.selectors ?? DEFAULT_LIMRUN_HAR_SELECTORS)]; + const entries: DestinationTunnelHAREntry[] = []; + let failures: { count: number; last?: LimrunNetworkFailures['last'] } = { count: 0 }; + let truncated = 0; + const fail = (kind: LimrunNetworkFailureKind, host?: unknown, port?: unknown): void => { + failures = { + count: failures.count + 1, + last: { + kind, + ...(typeof host === 'string' ? { host } : {}), + ...(typeof port === 'number' ? { port } : {}), + }, + }; + }; + const assembler = new DestinationTunnelHARAssembler(HAR_BODY_LIMIT_BYTES); + let closed = false; try { + const selectors = [...(hosts ?? DEFAULT_LIMRUN_HAR_SELECTORS)]; validateDestinationTunnelSelectors(selectors); - } catch (error) { - return { ok: false, reason: 'tunnel-start-failed', message: describe(error) }; - } - const failures = createFailureRecorder(); - try { - // A relative path would make the capture directory, and its chmod, the daemon's cwd. - if (!path.isAbsolute(input.harPath)) { - return { - ok: false, - reason: 'tunnel-start-failed', - message: 'The HAR path must be absolute.', - }; - } - // The HAR holds raw traffic, so only the daemon's user may read it. - const harDir = path.dirname(input.harPath); - await fs.promises.mkdir(harDir, { recursive: true, mode: 0o700 }); - // mkdir leaves an existing directory as it was, so tighten it explicitly. - await fs.promises.chmod(harDir, 0o700); - const harFile = createHarFile(input.harPath, { - onDropped: (count) => - failures.record( - 'har-truncated', - { message: `dropped the ${count} oldest entries to stay under ${HAR_MAX_BYTES} bytes` }, - count, - ), - onWriteError: (error) => failures.record('har-write-failed', { message: describe(error) }), - }); - // The first publication must succeed: a capture whose file cannot be written does not start. - await harFile.flush(true); - const assembler = new DestinationTunnelHARAssembler(HAR_BODY_LIMIT_BYTES); - let closed = false; const tunnel = await client.startTunnel({ selectors, inspection: { enabled: true, captureBodies: true, maxBodyBytes: HAR_BODY_LIMIT_BYTES }, onInspectionEvent: (event) => { if (closed) return; - failures.observe(event); - const completed = assembler.add(event); - if (completed && event.type === 'complete') harFile.add(completed); - }, - onInspectionError: (error) => { - failures.record('inspection-stream-error', { message: describe(error) }); + const entry = assembler.add(event); + if (entry) entries.push(entry); + if (entries.length > HAR_MAX_ENTRIES) { + entries.shift(); + truncated += 1; + } + if (event.type === 'complete' && event.data._limrun.error) { + const url = URL.parse(event.data.request.url); + fail('request-failed', url?.hostname, defaultPort(url)); + } else if (event.type === 'inspection_error') { + fail('inspection-error', event.data.host, event.data.port); + } else if (event.type === 'gap') { + fail('inspection-gap'); + } }, + onInspectionError: () => fail('inspection-stream-error'), }); return { ok: true, - capture: Object.freeze({ - harPath: input.harPath, - close: async () => { - if (closed) return; - try { - tunnel.close(); - closed = true; - } finally { - await harFile.flush(); - } + capture: { + entries: () => [...entries], + failures: async () => { + const lastDialFailure = closed ? undefined : await readLastDialFailure(client, tunnel); + return { ...failures, ...(lastDialFailure ? { lastDialFailure } : {}), truncated }; }, - failures: async () => - failures.report( - closed - ? undefined - : await readLastDialFailure(client, tunnel.tunnelId, tunnel.selectors), - ), - }), + close: () => { + closed = true; + tunnel.close(); + }, + }, }; } catch (error) { return { @@ -222,179 +142,43 @@ export async function startLimrunHarCapture( error instanceof DestinationTunnelSessionError && error.code === 'already_active' ? 'tunnel-in-use' : 'tunnel-start-failed', - message: describe(error), + message: error instanceof Error ? error.message : String(error), }; } } -function createFailureRecorder() { - const byKind: Partial< - Record - > = {}; - let total = 0; - const record = ( - kind: LimrunTunnelFailureKind, - failure: Omit, - count = 1, - ): void => { - total += count; - const entry = (byKind[kind] ??= { count: 0, latest: [] }); - entry.count += count; - entry.latest.push({ ...failure, at: new Date().toISOString() }); - if (entry.latest.length > LATEST_FAILURES_PER_KIND) entry.latest.shift(); - }; - return { - record, - observe(event: DestinationTunnelInspectionEvent): void { - if (event.type === 'complete' && event.data._limrun.error) { - record('request-failed', { - ...readUrlEndpoint(event.data.request.url), - message: event.data._limrun.error, - }); - } else if (event.type === 'inspection_error') { - const { host, port, message } = event.data; - record('inspection-error', { - ...(typeof host === 'string' ? { host } : {}), - ...(typeof port === 'number' ? { port } : {}), - message, - }); - } else if (event.type === 'gap') { - record('inspection-gap', { message: event.data.message }); - } - }, - report( - lastDialFailure: LimrunTunnelFailureReport['lastDialFailure'], - ): LimrunTunnelFailureReport { - return { - total, - byKind: Object.fromEntries( - Object.entries(byKind).map(([kind, entry]) => [ - kind, - { count: entry.count, latest: [...entry.latest] }, - ]), - ), - ...(lastDialFailure ? { lastDialFailure } : {}), - }; - }, +/** Writes the entries as a HAR 1.2 file that only the daemon's user can read. */ +export async function writeLimrunHar( + harPath: string, + entries: readonly DestinationTunnelHAREntry[], +): Promise { + await fs.promises.mkdir(path.dirname(harPath), { recursive: true, mode: 0o700 }); + const har = { + log: { version: '1.2', creator: { name: 'agent-device', version: '1' }, entries }, }; + await fs.promises.writeFile(harPath, `${JSON.stringify(har)}\n`, { mode: 0o600 }); + // `mode` applies only when the file is created. + await fs.promises.chmod(harPath, 0o600); } -/** Best effort: the status read is bounded well below a listing or close request. */ +/** The status read takes no signal, so a slow read is abandoned after the budget. */ async function readLastDialFailure( client: LimrunHarTunnelClient, - tunnelId: string, - selectors: DestinationTcpTunnel['selectors'], -): Promise { - const readStatus = client.getTunnelStatus; - if (!readStatus) return undefined; - const status = await new Promise> | undefined>( - (resolve) => { - const timer = setTimeout(() => resolve(undefined), TUNNEL_STATUS_BUDGET_MS); - readStatus - .call(client) - .then(resolve, () => resolve(undefined)) - .finally(() => clearTimeout(timer)); - }, - ); - const failure = status?.lastDialFailure; - if (!failure || failure.tunnelId !== tunnelId) return undefined; - const selector = selectors?.find((report) => report.id === failure.selectorId)?.value; - return { - reason: failure.reason, - ...(failure.osCode ? { osCode: failure.osCode } : {}), - ...(selector ? { selector } : {}), - }; -} - -function readUrlEndpoint(url: string): Readonly<{ host?: string; port?: number }> { - try { - const parsed = new URL(url); - const port = parsed.port - ? Number(parsed.port) - : parsed.protocol === 'https:' - ? 443 - : parsed.protocol === 'http:' - ? 80 - : undefined; - return { host: parsed.hostname, ...(port === undefined ? {} : { port }) }; - } catch { - return {}; - } -} - -const HAR_HEADER = - '{"log":{"version":"1.2","creator":{"name":"agent-device limrun-tunnel","version":"1"},"entries":['; -const HAR_FOOTER = ']}}\n'; -const HAR_WRAPPER_BYTES = Buffer.byteLength(HAR_HEADER) + Buffer.byteLength(HAR_FOOTER); - -/** - * The HAR file of one capture. Each entry is serialized once into a ring capped at - * `HAR_MAX_BYTES`; a write joins the ring, so its cost is bounded too. Writes coalesce, and one - * runs at a time, off the event loop. - */ -function createHarFile( - harPath: string, - hooks: Readonly<{ onDropped: (count: number) => void; onWriteError: (error: unknown) => void }>, -) { - const entries: { json: string; bytes: number }[] = []; - // The file's size in UTF-8 bytes: the wrapper, every entry, and the commas between them. - let bytes = HAR_WRAPPER_BYTES; + tunnel: DestinationTcpTunnel, +): Promise { let timer: NodeJS.Timeout | undefined; - let inFlight: Promise | undefined; - let tempSequence = 0; - /** Publishes the file; `required` rethrows a failure instead of recording it. */ - const write = async (required: boolean): Promise => { - // A fresh, exclusively created temp file, renamed into place: a reader never sees a partial - // document, and the published file always carries the owner-only mode. - tempSequence += 1; - const tempPath = `${harPath}.${process.pid}-${tempSequence}.tmp`; - try { - const document = `${HAR_HEADER}${entries.map((entry) => entry.json).join(',')}${HAR_FOOTER}`; - await fs.promises.writeFile(tempPath, document, { - mode: 0o600, - flag: 'wx', - }); - await fs.promises.rename(tempPath, harPath); - } catch (error) { - await fs.promises.rm(tempPath, { force: true }).catch(() => undefined); - if (required) throw error; - hooks.onWriteError(error); - } - }; - const flush = async (required = false): Promise => { - clearTimeout(timer); - timer = undefined; - while (inFlight) await inFlight; - inFlight = write(required).finally(() => { - inFlight = undefined; - }); - await inFlight; - }; - return { - flush, - add(entry: unknown): void { - const json = JSON.stringify(entry); - const entryBytes = Buffer.byteLength(json); - entries.push({ json, bytes: entryBytes }); - bytes += entryBytes + (entries.length > 1 ? 1 : 0); - let dropped = 0; - // An entry that cannot fit even alone leaves too. - while (bytes > HAR_MAX_BYTES && entries.length > 0) { - const oldest = entries.shift(); - bytes -= (oldest?.bytes ?? 0) + (entries.length > 0 ? 1 : 0); - dropped += 1; - } - if (dropped > 0) hooks.onDropped(dropped); - timer ??= setTimeout(() => void flush(), HAR_WRITE_COALESCE_MS); - }, - }; -} - -/** Deletes a capture's HAR file once nothing reports it any more. */ -export async function discardLimrunHar(harPath: string): Promise { - await fs.promises.rm(harPath, { force: true }); + const status = await Promise.race([ + client.getTunnelStatus?.().catch(() => undefined), + new Promise((resolve) => { + timer = setTimeout(() => resolve(undefined), TUNNEL_STATUS_BUDGET_MS); + }), + ]).finally(() => clearTimeout(timer)); + const failure = status?.lastDialFailure; + return failure?.tunnelId === tunnel.tunnelId ? failure.reason : undefined; } -function describe(error: unknown): string { - return error instanceof Error ? error.message : String(error); +function defaultPort(url: URL | null): number | undefined { + if (!url) return undefined; + if (url.port) return Number(url.port); + return url.protocol === 'https:' ? 443 : url.protocol === 'http:' ? 80 : undefined; } diff --git a/packages/provider-limrun/src/runtime.test.ts b/packages/provider-limrun/src/runtime.test.ts index 700d57ff04..108d4946f8 100644 --- a/packages/provider-limrun/src/runtime.test.ts +++ b/packages/provider-limrun/src/runtime.test.ts @@ -1,5 +1,6 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; +import path from 'node:path'; import { test, vi } from 'vitest'; import type { AppsFilter, DeviceLease } from '@agent-device/contracts/device'; import type { Interactor } from '@agent-device/contracts/interactor-types'; @@ -29,10 +30,8 @@ const state = vi.hoisted(() => ({ | undefined, disconnect: vi.fn(), tunnelClose: vi.fn(), - androidDelete: vi.fn(async () => undefined), - inspectionEvents: [] as ((event: unknown) => void)[], - destinationTunnelClose: vi.fn(), - tunnelStatus: {} as Record, + captureTunnelClose: vi.fn(), + onInspectionEvent: undefined as ((event: unknown) => void) | undefined, })); vi.mock('@limrun/api', () => ({ @@ -48,7 +47,7 @@ vi.mock('@limrun/api', () => ({ }, })), list: vi.fn(), - delete: state.androidDelete, + delete: vi.fn(async () => undefined), }; readonly assets = { getOrUpload: vi.fn(), list: vi.fn() }; }, @@ -68,10 +67,12 @@ vi.mock('@limrun/api/instance-client', () => ({ close: state.tunnelClose, })), startTunnel: vi.fn(async (options: { onInspectionEvent: (event: unknown) => void }) => { - state.inspectionEvents.push(options.onInspectionEvent); - return { tunnelId: 't1', selectors: [], close: state.destinationTunnelClose }; + state.onInspectionEvent = options.onInspectionEvent; + return { tunnelId: 't1', selectors: [], close: state.captureTunnelClose }; }), - getTunnelStatus: vi.fn(async () => state.tunnelStatus), + getTunnelStatus: vi.fn(async () => ({ + lastDialFailure: { tunnelId: 't1', reason: 'dns_not_found' }, + })), })), })); @@ -185,115 +186,85 @@ test('the platform module surfaces an aborted request inside the app-state reade } }); -function requestScope(signal: AbortSignal = new AbortController().signal): PlatformRequestScope { - return { - signal, - diagnostics: { emit: () => {} }, - progress: { report: () => {} }, - }; -} - -test('a network capture reports its HAR and failures through artifacts and every release attempt', async () => { +test('a network capture writes a private HAR with its failures on artifacts and at release', async () => { + const harDir = mkdtempForTestSync('limrun-har-'); const runtime = createLimrunRuntime( - { apiKey: 'lim_test_key', networkHarDir: mkdtempForTestSync('limrun-runtime-har-') }, + { apiKey: 'lim_test_key', networkHarDir: harDir }, testDependencies(), ); const lease = androidLease('lease-capture'); + const harPath = path.join(harDir, `${lease.leaseId}.har`); + // A HAR left by an earlier capture becomes private when it is rewritten. + fs.writeFileSync(harPath, '', { mode: 0o644 }); try { + // A repeat allocation of the live lease starts the capture it newly asks for. + await runtime.leaseLifecycle.allocate?.(lease); await runtime.leaseLifecycle.allocate?.(lease, { flags: { providerNetworkLogs: true } }); - state.inspectionEvents.at(-1)?.(failedRequest('https://api.example.com/login')); + for (let index = 0; index < 499; index += 1) { + state.onInspectionEvent?.(completedRequest(`https://api.example.com/${index}`)); + } + state.onInspectionEvent?.( + completedRequest('https://missing.example.com/', 'client_dial_failed'), + ); + // Truncation is a buffer statistic, so it keeps the failure that came before it. + state.onInspectionEvent?.(completedRequest('https://api.example.com/last')); const listed = await runtime.cloudArtifacts?.listCloudArtifacts?.({ leaseId: lease.leaseId }); - const harPath = listed?.cloudArtifacts[0]?.url; - assert.match(String(harPath), /android-instance-1-lease-capture\.har$/); - assert.match(String(listed?.message), /request-failed 1, latest api\.example\.com:443/); + assert.equal(listed?.cloudArtifacts[0]?.url, harPath); + const har = JSON.parse(fs.readFileSync(harPath, 'utf8')); + assert.equal(har.log.entries.length, 500); + assert.equal(har.log.entries.at(-2).response.status, 0); + assert.equal(fs.statSync(harPath).mode & 0o777, 0o600); + assert.deepEqual(listed?.cloudArtifacts[0]?.metadata, { + failures: { + count: 1, + last: { kind: 'request-failed', host: 'missing.example.com', port: 443 }, + lastDialFailure: 'dns_not_found', + truncated: 1, + }, + }); - const release = runtime.leaseLifecycle.release; - assert.ok(release); - state.androidDelete.mockRejectedValueOnce(new Error('temporary delete failure')); - await assert.rejects(() => release(lease), /temporary delete failure/); - const retried = (await release(lease)) as { + const released = (await runtime.leaseLifecycle.release?.(lease)) as { cloudArtifacts?: { cloudArtifacts: { url?: string }[]; message?: string }; }; - assert.equal(retried.cloudArtifacts?.cloudArtifacts[0]?.url, harPath); - assert.match(String(retried.cloudArtifacts?.message), /request-failed 1/); - assert.equal(state.destinationTunnelClose.mock.calls.length, 1); - } finally { - await runtime.shutdown?.(); - } -}); - -test('a repeat allocation starts the capture it newly asks for, and a dial-only failure is reported', async () => { - const runtime = createLimrunRuntime( - { apiKey: 'lim_test_key', networkHarDir: mkdtempForTestSync('limrun-runtime-har-') }, - testDependencies(), - ); - const lease = androidLease('lease-repeat'); - state.tunnelStatus = { - lastDialFailure: { tunnelId: 't1', selectorId: 's1', reason: 'connection_refused' }, - }; - try { - const first = await runtime.leaseLifecycle.allocate?.(lease); - assert.equal(first?.networkHar, undefined); - const repeat = await runtime.leaseLifecycle.allocate?.(lease, { - flags: { providerNetworkLogs: true }, + assert.equal(released.cloudArtifacts?.cloudArtifacts[0]?.url, harPath); + assert.equal(state.captureTunnelClose.mock.calls.length, 1); + assert.match( + String(released.cloudArtifacts?.message), + /last request-failed missing\.example\.com:443/, + ); + const afterClose = await runtime.cloudArtifacts?.listCloudArtifacts?.({ + leaseId: lease.leaseId, }); - assert.equal((repeat?.networkHar as { status?: string } | undefined)?.status, 'capturing'); - - const listed = await runtime.cloudArtifacts?.listCloudArtifacts?.({ leaseId: lease.leaseId }); - assert.match(String(listed?.message), /last dial failure connection_refused/); + assert.equal(afterClose?.cloudArtifacts[0]?.url, harPath); } finally { - state.tunnelStatus = {}; - await runtime.shutdown?.(); + await runtime.shutdown(); } }); -test('a repeat allocation retries a capture that could not start', async () => { +test('released captures past the record limit forget the oldest released lease first', async () => { const runtime = createLimrunRuntime( - { apiKey: 'lim_test_key', networkHarDir: mkdtempForTestSync('limrun-runtime-har-') }, + { apiKey: 'lim_test_key', networkHarDir: mkdtempForTestSync('limrun-har-') }, testDependencies(), ); - const lease = androidLease('lease-retry'); + const live = androidLease('lease-live-unavailable'); try { - const first = await runtime.leaseLifecycle.allocate?.(lease, { - flags: { providerNetworkLogs: true, providerNetworkHosts: 'not a host!!' }, - }); - assert.equal((first?.networkHar as { status?: string } | undefined)?.status, 'unavailable'); - const retried = await runtime.leaseLifecycle.allocate?.(lease, { - flags: { providerNetworkLogs: true, providerNetworkHosts: 'api.example.com' }, + await runtime.leaseLifecycle.allocate?.(live, { + flags: { providerNetworkLogs: true, providerNetworkHosts: 'not a host' }, }); - assert.equal((retried?.networkHar as { status?: string } | undefined)?.status, 'capturing'); - } finally { - await runtime.shutdown?.(); - } -}); - -test('a stopped capture past the retention limit loses its record and its HAR file', async () => { - const runtime = createLimrunRuntime( - { apiKey: 'lim_test_key', networkHarDir: mkdtempForTestSync('limrun-runtime-har-') }, - testDependencies(), - ); - const release = runtime.leaseLifecycle.release; - assert.ok(release); - const harPaths: string[] = []; - try { - // 33 stopped captures; the 34th start evicts the oldest. - for (let index = 0; index < 34; index += 1) { - const lease = androidLease(`lease-retention-${index}`); - const allocation = await runtime.leaseLifecycle.allocate?.(lease, { - flags: { providerNetworkLogs: true }, - }); - harPaths.push(String((allocation?.networkHar as { harPath?: string } | undefined)?.harPath)); - if (index < 33) await release(lease); + for (let index = 0; index < 33; index += 1) { + const lease = androidLease(`lease-released-${index}`); + await runtime.leaseLifecycle.allocate?.(lease, { flags: { providerNetworkLogs: true } }); + await runtime.leaseLifecycle.release?.(lease); } - assert.equal(fs.existsSync(harPaths[0] ?? ''), false); - assert.equal(fs.existsSync(harPaths[1] ?? ''), true); - assert.equal( - await runtime.cloudArtifacts?.listCloudArtifacts?.({ leaseId: 'lease-retention-0' }), - undefined, - ); + const list = async (leaseId: string) => + (await runtime.cloudArtifacts?.listCloudArtifacts?.({ leaseId }))?.status; + assert.equal(await list('lease-released-0'), undefined); + assert.equal(await list('lease-released-1'), undefined); + assert.equal(await list('lease-released-32'), 'ready'); + assert.equal(await list(live.leaseId), 'unavailable'); } finally { - await runtime.shutdown?.(); + await runtime.shutdown(); } }); @@ -301,50 +272,43 @@ test('a network capture that cannot start is an unavailable artifact with its ty const runtime = createLimrunRuntime({ apiKey: 'lim_test_key' }, testDependencies()); const lease = androidLease('lease-no-dir'); try { - const allocation = await runtime.leaseLifecycle.allocate?.(lease, { - flags: { providerNetworkLogs: true }, - }); - assert.deepEqual(allocation?.networkHar, { - status: 'unavailable', - reason: 'capture-dir-unset', - message: 'The runtime has no directory for network capture files.', - }); + await runtime.leaseLifecycle.allocate?.(lease, { flags: { providerNetworkLogs: true } }); const listed = await runtime.cloudArtifacts?.listCloudArtifacts?.({ leaseId: lease.leaseId }); assert.equal(listed?.status, 'unavailable'); assert.deepEqual(listed?.cloudArtifacts[0]?.metadata, { reason: 'capture-dir-unset' }); - assert.match(String(listed?.message), /did not start \(capture-dir-unset\)/); } finally { - await runtime.shutdown?.(); + await runtime.shutdown(); } }); -function failedRequest(url: string): unknown { +function completedRequest(url: string, error?: string): unknown { return { type: 'complete', sequence: 1, - requestId: 'req-1', + requestId: url, data: { startedDateTime: new Date(0).toISOString(), time: 0, request: { method: 'GET', url, httpVersion: 'HTTP/1.1', headers: [], cookies: [] }, - response: { status: 0, statusText: '', httpVersion: '', headers: [], cookies: [] }, + response: { + status: error ? 0 : 200, + statusText: '', + httpVersion: '', + headers: [], + cookies: [], + }, cache: {}, timings: { send: 0, wait: 0, receive: 0 }, - _limrun: { tunnelId: 't1', selectorId: 's1', error: 'client_dial_failed' }, + _limrun: { tunnelId: 't1', selectorId: 's1', ...(error ? { error } : {}) }, }, }; } -function androidLease(leaseId: string): DeviceLease { +function requestScope(signal: AbortSignal = new AbortController().signal): PlatformRequestScope { return { - leaseId, - tenantId: 'team-a', - runId: 'run-a', - backend: 'android-instance', - leaseProvider: 'limrun', - createdAt: 1, - heartbeatAt: 1, - expiresAt: 60_001, + signal, + diagnostics: { emit: () => {} }, + progress: { report: () => {} }, }; } @@ -358,6 +322,19 @@ async function allocateAndroidDevice( return device as DeviceInfo; } +function androidLease(leaseId: string): DeviceLease { + return { + leaseId, + tenantId: 'team-a', + runId: 'run-a', + backend: 'android-instance', + leaseProvider: 'limrun', + createdAt: 1, + heartbeatAt: 1, + expiresAt: 60_001, + }; +} + function testDependencies(): LimrunRuntimeDependencies { return { clientVersion: 'test-version', diff --git a/packages/provider-limrun/src/runtime.ts b/packages/provider-limrun/src/runtime.ts index ad9189b840..7a0f704f72 100644 --- a/packages/provider-limrun/src/runtime.ts +++ b/packages/provider-limrun/src/runtime.ts @@ -53,14 +53,9 @@ import type { LimrunAppAsset } from './app-catalog.ts'; import type { LimrunInstanceAccess } from './instance-access.ts'; import type { CloudArtifactProvider, - CloudArtifactsQuery, CloudArtifactsResult, } from '@agent-device/contracts/observability'; -import type { - LimrunHarCapture, - LimrunHarCaptureFailure, - LimrunTunnelFailureReport, -} from './network-har.ts'; +import type { LimrunHarCapture, LimrunNetworkFailures } from './network-har.ts'; import path from 'node:path'; type LimrunRuntimeSession = LimrunIosSession | LimrunAndroidSession; @@ -75,10 +70,7 @@ export type LimrunRuntimeOptions = { keepAlive?: boolean; runtimeInstance?: string; instances?: LimrunInstanceAccess; - /** - * Where `--provider-network-logs` writes each session's live HAR file. The composition root - * resolves it under the daemon state dir; without it the opt-in reports a typed refusal. - */ + /** Where `--provider-network-logs` writes each lease's HAR file. Without it the capture is unavailable. */ networkHarDir?: string; }; @@ -124,8 +116,7 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { private readonly limrun: Limrun | undefined; private readonly sessions = new Map(); private readonly keepAliveTimers = new Map(); - /** Each lease's `--provider-network-logs` capture: live, stopped at release, or never started. */ - private readonly networkCaptures = new Map(); + private readonly networkCaptures = new Map(); private readonly appAliases = new Map< string, Readonly<{ assetName: string; installedAppId: string }> @@ -274,38 +265,83 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { // ahead of attach as well as create, since an attached instance reads none of them either. rejectRefusedLimrunProfileFields(context); const existing = this.sessions.get(lease.leaseId); - if (existing) { - // A repeat allocation can opt into the capture the first one did not ask for, or retry one - // that could not start. - const networkHar = - context?.flags?.providerNetworkLogs === true && - (this.networkCaptures.get(lease.leaseId)?.phase ?? 'unavailable') === 'unavailable' - ? await this.startNetworkCapture(lease, existing, context) - : undefined; - return { - limrunInstanceId: existing.instanceId, - device: existing.device, - ...(networkHar ? { networkHar } : {}), - }; - } - const session = + existing ?? (await this.attachSession(platform, lease)) ?? (await this.createSession(platform, lease, context)); - this.sessions.set(lease.leaseId, session); - if (this.options.keepAlive) this.startKeepAlive(lease.leaseId, session); - const networkHar = - context?.flags?.providerNetworkLogs === true - ? await this.startNetworkCapture(lease, session, context) - : undefined; - return { - limrunInstanceId: session.instanceId, - providerSessionId: session.instanceId, - device: session.device, - ...(networkHar ? { networkHar } : {}), - }; + if (!existing) { + this.sessions.set(lease.leaseId, session); + if (this.options.keepAlive) this.startKeepAlive(lease.leaseId, session); + } + // A repeat allocation can ask for the capture, or retry one that could not start. + if ( + context?.flags?.providerNetworkLogs === true && + this.networkCaptures.get(lease.leaseId)?.phase !== 'capturing' + ) { + await this.startNetworkCapture(lease.leaseId, session, context.flags.providerNetworkHosts); + } + return { limrunInstanceId: session.instanceId, device: session.device }; } + private async startNetworkCapture( + leaseId: string, + session: LimrunRuntimeSession, + hostList: unknown, + ): Promise { + const harDir = this.options.networkHarDir; + if (!harDir) { + this.networkCaptures.set(leaseId, { phase: 'unavailable', reason: 'capture-dir-unset' }); + return; + } + const hosts = + typeof hostList === 'string' + ? hostList + .split(',') + .map((host) => host.trim()) + .filter(Boolean) + : []; + const { startLimrunHarCapture } = await import('./network-har.ts'); + const result = await startLimrunHarCapture( + session.client, + hosts.length > 0 ? hosts : undefined, + ); + this.networkCaptures.set( + leaseId, + result.ok + ? { + phase: 'capturing', + harPath: path.join(harDir, `${leaseId}.har`), + capture: result.capture, + } + : { phase: 'unavailable', reason: result.reason, message: result.message }, + ); + } + + /** Writes a live capture's HAR now; a released capture reports the file it wrote at release. */ + private async writeNetworkCapture(leaseId: string): Promise { + const state = this.networkCaptures.get(leaseId); + if (state?.phase !== 'capturing') return state; + const failures = await state.capture.failures(); + try { + const { writeLimrunHar } = await import('./network-har.ts'); + await writeLimrunHar(state.harPath, state.capture.entries()); + return { phase: 'written', harPath: state.harPath, failures }; + } catch (error) { + return { + phase: 'unavailable', + reason: 'har-write-failed', + message: error instanceof Error ? error.message : String(error), + }; + } + } + + readonly cloudArtifacts: CloudArtifactProvider = { + listCloudArtifacts: async (query) => { + const capture = query.leaseId ? await this.writeNetworkCapture(query.leaseId) : undefined; + return capture && networkArtifacts(capture); + }, + }; + private async attachSession( platform: LimrunPlatform, lease: DeviceLease, @@ -390,103 +426,27 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { private async release(lease: DeviceLease): Promise | undefined> { const session = this.sessions.get(lease.leaseId); if (!session) return await this.releaseRecoveredSession(lease); - // A retry after a failed termination finds the capture already stopped and reports it again. - const networkCapture = await this.stopNetworkCapture(lease.leaseId); + const live = this.networkCaptures.get(lease.leaseId); + const capture = await this.writeNetworkCapture(lease.leaseId); + if (capture) { + // Re-insertion keeps the map in settle order, so the oldest released record goes first. + this.networkCaptures.delete(lease.leaseId); + this.networkCaptures.set(lease.leaseId, capture); + } + for (const leaseId of this.networkCaptures.keys()) { + if (this.networkCaptures.size <= SETTLED_NETWORK_CAPTURE_LIMIT) break; + if (!this.sessions.has(leaseId)) this.networkCaptures.delete(leaseId); + } + if (live?.phase === 'capturing') live.capture.close(); await this.terminateSession(session); this.sessions.delete(lease.leaseId); this.appAliases.delete(lease.leaseId); return { limrunInstanceId: session.instanceId, - providerSessionId: session.instanceId, - ...(networkCapture ? { cloudArtifacts: networkCaptureArtifacts(networkCapture) } : {}), + ...(capture ? { cloudArtifacts: networkArtifacts(capture) } : {}), }; } - /** - * `--provider-network-logs`: opens the instance's one destination tunnel with inspection and - * keeps a live HAR file under the state dir. The Metro/companion route rides this tunnel. - */ - private async startNetworkCapture( - lease: DeviceLease, - session: LimrunRuntimeSession, - context?: LeaseLifecycleContext, - ): Promise> { - const instanceId = session.instanceId; - const harDir = this.options.networkHarDir; - const result = harDir - ? await import('./network-har.ts').then(({ startLimrunHarCapture }) => - startLimrunHarCapture(session.client, { - // One file per lease: an attached instance serves many sessions. - harPath: path.join(harDir, `${instanceId}-${fileSafe(lease.leaseId)}.har`), - selectors: readProviderNetworkHosts(context?.flags?.providerNetworkHosts), - }), - ) - : ({ - ok: false, - reason: 'capture-dir-unset', - message: 'The runtime has no directory for network capture files.', - } as const); - await this.forgetStoppedNetworkCaptures(); - if (!result.ok) { - const { reason, message } = result; - this.networkCaptures.set(lease.leaseId, { - phase: 'unavailable', - instanceId, - reason, - message, - }); - return { status: 'unavailable', reason, message }; - } - this.networkCaptures.set(lease.leaseId, { - phase: 'capturing', - instanceId, - capture: result.capture, - }); - return { status: 'capturing', harPath: result.capture.harPath }; - } - - private async stopNetworkCapture(leaseId: string): Promise { - const state = this.networkCaptures.get(leaseId); - if (state?.phase !== 'capturing') return state; - // Read the tunnel's last dial failure while the tunnel is still open. - const failures = await state.capture.failures(); - await state.capture.close(); - const stopped = { - phase: 'stopped', - instanceId: state.instanceId, - harPath: state.capture.harPath, - failures, - } as const; - this.networkCaptures.set(leaseId, stopped); - return stopped; - } - - /** Keeps released captures listable for a while without growing for the daemon's lifetime. */ - private async forgetStoppedNetworkCaptures(): Promise { - const settled = [...this.networkCaptures].filter(([, state]) => state.phase !== 'capturing'); - const { discardLimrunHar } = await import('./network-har.ts'); - for (const [leaseId, state] of settled.slice(0, -SETTLED_NETWORK_CAPTURE_LIMIT)) { - this.networkCaptures.delete(leaseId); - // The file holds raw traffic, so it lives exactly as long as the record that reports it. - if (state.phase === 'stopped') await discardLimrunHar(state.harPath).catch(() => undefined); - } - } - - readonly cloudArtifacts: CloudArtifactProvider = { - listCloudArtifacts: async ( - query: CloudArtifactsQuery, - ): Promise => { - const state = query.leaseId ? this.networkCaptures.get(query.leaseId) : undefined; - if (state?.phase !== 'capturing') return state ? networkCaptureArtifacts(state) : undefined; - return networkCaptureArtifacts({ - phase: 'stopped', - instanceId: state.instanceId, - harPath: state.capture.harPath, - failures: await state.capture.failures(), - }); - }, - }; - private async releaseRecoveredSession( lease: DeviceLease, ): Promise | undefined> { @@ -526,12 +486,10 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { const leaseId = session.lease.leaseId; clearInterval(this.keepAliveTimers.get(leaseId)); this.keepAliveTimers.delete(leaseId); - // A capture rides the instance's one tunnel; close it before the client disconnects. - const networkCapture = this.networkCaptures.get(leaseId); - if (networkCapture?.phase === 'capturing') { + const capture = this.networkCaptures.get(leaseId); + if (capture?.phase === 'capturing') { this.networkCaptures.delete(leaseId); - // The client disconnect below ends the tunnel even when its own close fails. - await networkCapture.capture.close().catch(() => undefined); + capture.capture.close(); } session.client.disconnect(); if (session.platform === 'android') await cleanupLimrunAndroidAdbTunnel(session); @@ -684,49 +642,29 @@ function unsupported(command: string, message: string): never { throw new AppError('UNSUPPORTED_OPERATION', message, { command }); } -function fileSafe(value: string): string { - return value.replaceAll(/[^\w.-]/g, '_'); -} - -/** The `--provider-network-hosts` comma list, or undefined to keep the default selectors. */ -function readProviderNetworkHosts(value: unknown): readonly string[] | undefined { - if (typeof value !== 'string') return undefined; - const hosts = value - .split(',') - .map((host) => host.trim()) - .filter((host) => host.length > 0); - return hosts.length > 0 ? hosts : undefined; -} - +/** Released captures stay listable; the oldest records are forgotten past this count. */ const SETTLED_NETWORK_CAPTURE_LIMIT = 32; type SettledNetworkCapture = + | Readonly<{ phase: 'written'; harPath: string; failures: LimrunNetworkFailures }> | Readonly<{ - phase: 'stopped'; - instanceId: string; - harPath: string; - failures: LimrunTunnelFailureReport; - }> - | Readonly<{ phase: 'unavailable'; instanceId: string } & LimrunHarCaptureFailure>; - -type NetworkCaptureState = + phase: 'unavailable'; + reason: 'capture-dir-unset' | 'tunnel-in-use' | 'tunnel-start-failed' | 'har-write-failed'; + message?: string; + }>; + +type NetworkCapture = | SettledNetworkCapture - | Readonly<{ phase: 'capturing'; instanceId: string; capture: LimrunHarCapture }>; + | Readonly<{ phase: 'capturing'; harPath: string; capture: LimrunHarCapture }>; -const NETWORK_ARTIFACT_NAME = 'Network traffic (HAR, live file on the daemon host)'; +const NETWORK_ARTIFACT_NAME = 'Network traffic (HAR on the daemon host)'; -/** - * One HAR file, stated as a provider artifact whose `url` is its path on this host. The tunnel - * failure report rides the artifact's metadata, and its summary is the result's message. A capture - * that never started is an unavailable artifact carrying the typed reason. - */ -function networkCaptureArtifacts(capture: SettledNetworkCapture): CloudArtifactsResult { +function networkArtifacts(capture: SettledNetworkCapture): CloudArtifactsResult { if (capture.phase === 'unavailable') { return { provider: LIMRUN_PROVIDER, status: 'unavailable', - providerSessionId: capture.instanceId, - message: `Network capture did not start (${capture.reason}): ${capture.message}`, + message: `Network capture unavailable (${capture.reason})${capture.message ? `: ${capture.message}` : ''}`, cloudArtifacts: [ { provider: LIMRUN_PROVIDER, @@ -738,39 +676,30 @@ function networkCaptureArtifacts(capture: SettledNetworkCapture): CloudArtifacts ], }; } - const { harPath, instanceId, failures } = capture; + const { count, last, lastDialFailure, truncated } = capture.failures; + const summary = [ + `Network capture failures: ${count}`, + ...(last + ? [`last ${last.kind}${last.host ? ` ${last.host}${last.port ? `:${last.port}` : ''}` : ''}`] + : []), + ...(lastDialFailure ? [`last dial failure ${lastDialFailure}`] : []), + ...(truncated > 0 ? [`${truncated} oldest requests left the HAR`] : []), + ].join('; '); return { provider: LIMRUN_PROVIDER, status: 'ready', - providerSessionId: instanceId, - ...(failures.total > 0 || failures.lastDialFailure - ? { message: summarizeTunnelFailures(failures) } - : {}), + ...(count > 0 || lastDialFailure || truncated > 0 ? { message: summary } : {}), cloudArtifacts: [ { provider: LIMRUN_PROVIDER, kind: 'network', name: NETWORK_ARTIFACT_NAME, - url: harPath, + url: capture.harPath, extension: 'har', contentType: 'application/json', availability: 'ready', - metadata: { tunnelFailures: failures }, + metadata: { failures: capture.failures }, }, ], }; } - -function summarizeTunnelFailures(failures: LimrunTunnelFailureReport): string { - const kinds = Object.entries(failures.byKind).map(([kind, entry]) => { - const failure = entry.latest.at(-1); - const endpoint = failure?.host - ? ` ${failure.host}${failure.port ? `:${failure.port}` : ''}` - : ''; - return `${kind} ${entry.count}, latest${endpoint} (${failure?.message})`; - }); - const dial = failures.lastDialFailure - ? [`last dial failure ${failures.lastDialFailure.reason}`] - : []; - return `Network capture failures: ${failures.total}; ${[...kinds, ...dial].join('; ')}`; -} diff --git a/src/__tests__/limrun-runtime.test.ts b/src/__tests__/limrun-runtime.test.ts index 58ddae603e..dec506e77a 100644 --- a/src/__tests__/limrun-runtime.test.ts +++ b/src/__tests__/limrun-runtime.test.ts @@ -755,12 +755,7 @@ test('Limrun keeps session tracked when release fails so release can be retried' limrunMockState.androidDelete.mockRejectedValueOnce(new Error('temporary delete failure')); await assert.rejects(() => releaseLease(lease), /temporary delete failure/); - assert.deepEqual(await releaseLease(lease), { - limrunInstanceId: 'android-instance-1', - // The instance id doubles as the provider session id, so a released session's - // artifacts stay listable by that id. - providerSessionId: 'android-instance-1', - }); + assert.deepEqual(await releaseLease(lease), { limrunInstanceId: 'android-instance-1' }); } finally { await runtime.shutdown(); } diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 3bdf6abf2b..4966c47b28 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -626,7 +626,7 @@ Limrun direct-device flow: Limrun creates remote iOS simulators and Android emulators only. Do not pass local device selectors such as --udid, --serial, or --device. To drive an existing instance without the API key, set LIM_IOS_INSTANCE_URL and LIM_IOS_INSTANCE_TOKEN, or LIM_ANDROID_INSTANCE_URL, LIM_ANDROID_INSTANCE_TOKEN, and LIM_ANDROID_INSTANCE_ADB_URL, from the instance status before connect. agent-device then never creates or deletes that instance; install, and apps before the first open, still need LIMRUN_API_KEY. Set LIMRUN_KEEP_ALIVE=1 to ping the instance every 30 seconds while a session is open, so an idle session does not hit the Limrun inactivity timeout. It is off by default. - To capture network traffic, connect with --provider-network-logs --provider-network-hosts . artifacts and close print the HAR path and any tunnel failures; the HAR holds raw headers and bodies, and captured traffic exits through the daemon host. + To capture network traffic, connect with --provider-network-logs --provider-network-hosts . artifacts and close write the HAR and print its path and any capture failures; the HAR holds raw headers and bodies, and captured traffic exits through the daemon host. agent-device apps agent-device open Example.apk agent-device snapshot -i diff --git a/website/docs/docs/limrun.md b/website/docs/docs/limrun.md index c26eb1068f..ac1638cf5a 100644 --- a/website/docs/docs/limrun.md +++ b/website/docs/docs/limrun.md @@ -81,15 +81,14 @@ To drive Limrun only through MCP, see [Use a provider only through MCP](/docs/de ## Capture session network traffic -`--provider-network-logs` records the device's HTTP traffic into a HAR 1.2 file on the machine that runs agent-device. The file stays valid while the session runs, so you can read it with `jq` at any point. +Use `--provider-network-logs` when you debug an app's network requests on a remote Limrun device. The device's traffic is captured while the session runs. `agent-device artifacts` and `close` write it as a HAR 1.2 file and print its path. Before you turn it on, know what the capture changes: -- Captured traffic leaves through the machine that runs agent-device, not the device's own network. Servers see that machine's public IP, each new connection takes longer, and the device loses the captured hosts if agent-device stops. On CI, the traffic leaves from the CI runner. -- The HAR holds raw requests and responses, including headers, cookies, tokens, and bodies. Treat it as a secret: keep it out of logs, bug reports, and build artifacts that others can read. -- Certificate-pinned hosts refuse the connection, and an app that resolves names over DNS-over-HTTPS bypasses the capture. -- HTTPS hosts that don't support HTTP/2 fail to connect while the capture runs. -- Each request and response body is cut to 64 KiB. Once the file would pass 8 MiB, the oldest entries are dropped, and the failure summary reports them as `har-truncated`. +- Captured traffic leaves through the machine that runs agent-device, not the device's own network. Servers see that machine's public IP. On CI, the traffic leaves from the CI runner. +- The HAR holds raw requests and responses, including headers, cookies, tokens, and bodies. Treat it as a secret. Keep it out of logs, bug reports, and build artifacts that others can read. +- Some hosts can't be captured: certificate-pinned hosts refuse the connection, apps that resolve names over DNS-over-HTTPS bypass the capture, and HTTPS hosts that don't support HTTP/2 fail to connect. +- Each body is cut to 64 KiB, and the HAR keeps the latest 500 requests. Pass your app's API hosts with `--provider-network-hosts`, then open the app after you connect: @@ -97,34 +96,25 @@ Pass your app's API hosts with `--provider-network-hosts`, then open the app aft agent-device connect limrun --platform ios --provider-network-logs \ --provider-network-hosts "api.example.com,*.cdn.example.com,localhost:8081" agent-device open com.example.app -agent-device artifacts # prints the HAR path +agent-device artifacts # writes the HAR and prints its path jq -r '.log.entries[] | "\(.response.status) \(.request.method) \(.request.url)"' -agent-device close # prints the HAR path again +agent-device close # writes the HAR again and prints its path agent-device disconnect ``` -`--provider-network-hosts` takes exact hosts, wildcards such as `*.example.com`, and `localhost:` routes. Keep `localhost:8081`, or your Metro port, in the list when the app loads its bundle from a local Metro server. Without `--provider-network-hosts`, the capture covers every `.com`, `.org`, `.app`, `.net`, `.io`, and `.dev` host plus `localhost:8081`. Operating system traffic then fills most of the file, and hosts under other domains, such as `.co`, `.ai`, or country domains, are not captured. +`--provider-network-hosts` takes exact hosts, wildcards such as `*.example.com`, and `localhost:` routes. Keep `localhost:8081`, or your Metro port, in the list when the app loads its bundle from a local Metro server. Without `--provider-network-hosts`, the capture covers every `.com`, `.org`, `.app`, `.net`, `.io`, and `.dev` host plus `localhost:8081`. System traffic then fills most of the file. -The file is `/network-har/-.har`, readable only by your user. `agent-device artifacts` lists it during the session and after `close`. agent-device keeps the files of the 32 most recent captures that have stopped and deletes older ones; files from a daemon that has stopped stay until you delete them. If the capture can't start, for example because a `--provider-network-hosts` entry is not a valid host, `artifacts` reports the network artifact as `unavailable` with the reason. +The file is `/network-har/.har`, and only your user can read it. It stays until you delete it. If the capture can't start, for example because a `--provider-network-hosts` entry is not a valid host, `artifacts` reports the network artifact as `unavailable` with the reason. -### When a request fails or hangs - -A request that can't reach its host still appears in the HAR with status `0`. `artifacts` and `close` also print a failure summary after the HAR path: +A request that can't reach its host appears in the HAR with status `0`. When the capture has failures, `artifacts` and `close` print a summary after the HAR path: ```text -Network capture failures: 9; inspection-error 8, latest bag.itunes.apple.com:443 (terminate app TLS: EOF); request-failed 1, latest api.example.com:443 (tunnel client could not open the destination: client_dial_failed); last dial failure tls_handshake_failed +Network capture failures: 2; last request-failed api.example.com:443; last dial failure dns_not_found ``` -- `request-failed`: the request reached the capture, but its host didn't resolve, refused, timed out, or failed the TLS handshake. Check that the machine running agent-device can reach the host. -- `inspection-error`: the capture couldn't read a connection. This is usually a certificate-pinned host. System hosts, such as Apple's, report these in every session. -- `inspection-gap` and `inspection-stream-error`: the HAR misses requests. Reconnect if you need a complete file. -- `har-truncated`: the oldest entries were dropped to keep the file under 8 MiB. Narrow `--provider-network-hosts` to keep more of your app's traffic. -- `har-write-failed`: the file could not be written, so it lags the traffic. Check the free disk space on the machine that runs agent-device. -- `last dial failure`: the reason Limrun reports for the most recent failed connection, such as `dns_not_found`, `connection_refused`, `client_timeout`, or `tls_handshake_failed`. - -Occasionally, requests skip the capture: they are missing from the HAR and from the failure summary. This affects the first request after the device is allocated, or now and then a whole session. If a request you expect is missing, repeat it. If the HAR stays empty while the app makes requests, run `close` and `disconnect`, then connect again. +The count includes these kinds: `request-failed` (the host didn't resolve, refused, timed out, or failed TLS), `inspection-error` (usually a certificate-pinned host), and `inspection-gap` and `inspection-stream-error` (the HAR misses requests). `last dial failure` is Limrun's reason for the most recent failed connection. The HAR keeps the latest 500 requests, with each body cut to 64 KiB, so a capture can hold tens of MB in the daemon. When older requests left the HAR, the summary says how many, and the count doesn't include them. `artifacts --json` returns the same values in `data.cloudArtifacts[0].metadata.failures`. -`artifacts --json` returns the same report, with counts and the latest failures of each kind, in `data.cloudArtifacts[0].metadata.tunnelFailures`. +Now and then, a request skips the capture: it is missing from the HAR and from the failure count. If a request you expect is missing, repeat it. If the HAR stays empty while the app makes requests, run `close` and `disconnect`, then connect again. ## Embed the Node.js runtime @@ -178,4 +168,4 @@ After allocating a lease, call `runtime.getDeviceSession(device)` to get the all ## Get artifacts and troubleshoot -For Limrun, `agent-device artifacts` lists only the `--provider-network-logs` HAR file. If a page hangs while the capture runs, read the failure summary that `artifacts` prints; see [When a request fails or hangs](#when-a-request-fails-or-hangs). If `connect` fails, check `LIMRUN_API_KEY` and the optional `LIMRUN_REGION`. For an existing instance, check its URL and token variables, and that the instance is still running. +For Limrun, `agent-device artifacts` lists only the `--provider-network-logs` HAR file. If a page hangs while the capture runs, read the failure summary that `artifacts` prints; see [Capture session network traffic](#capture-session-network-traffic). If `connect` fails, check `LIMRUN_API_KEY` and the optional `LIMRUN_REGION`. For an existing instance, check its URL and token variables, and that the instance is still running.