Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
24f9b1e
fix(providers): bound credential endpoints and responses
thymikee Nov 30, 2026
e9c71d0
fix(providers): require origin fences for authenticated downloads
thymikee Nov 30, 2026
f3378ac
fix(providers): bound Limrun control responses
thymikee Nov 30, 2026
53eaadb
fix(providers): satisfy response boundary gates
thymikee Nov 30, 2026
e1cfdf3
fix(providers): share response failure vocabulary
thymikee Nov 30, 2026
2c503f0
fix(providers): cancel stalled Limrun response reads
thymikee Nov 30, 2026
930a769
docs: regenerate provider response reasons
thymikee Nov 30, 2026
edbfdc0
chore(gates): refresh contracts export snapshot
thymikee Nov 30, 2026
7bd574a
test(providers): narrow stalled response observation
thymikee Nov 30, 2026
1e8387f
fix(providers): preserve observed Limrun rejection status
thymikee Nov 30, 2026
03aa325
test(providers): await client-observed rejection body
thymikee Nov 30, 2026
bd04eb3
test(providers): observe retry conflict body seam
thymikee Nov 30, 2026
8b7110c
fix(providers): keep response reason in existing closure
thymikee Nov 30, 2026
ba2d7f4
fix: preserve anonymous Limrun release redirects and BOM decoding
thymikee Nov 30, 2026
a2fa5bb
fix(providers): close credential and response boundaries
thymikee Nov 30, 2026
80f1279
fix(contracts): keep response reasons in remote facade
thymikee Nov 30, 2026
6d63706
docs(contracts): summarize provider response reason
thymikee Nov 30, 2026
3ed35d7
fix(providers): narrow response bounds to buffered bodies
thymikee Dec 1, 2026
2955f2b
fix(revyl): report oversized responses with shared reason
thymikee Dec 1, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/contracts/src/facades/remote.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { ReasonTable } from '@agent-device/kernel/errors';

export type { CompanionTunnelScope, MetroBridgeScope } from '../companion-tunnel-scope.ts';
export type {
MetroBridgeResult,
Expand All @@ -22,6 +24,13 @@ export {
PROVIDER_PROFILE_FIELD_FLAG_ALIASES,
PROVIDER_PROFILE_FIELD_FLAGS,
} from '../remote-config-fields.ts';

/** Why a provider response was rejected before its body was accepted. */
export const PROVIDER_RESPONSE_REASONS = {
// A provider answered with more bytes than the response budget allows.
tooLarge: { reason: 'provider_response_too_large' },
} as const satisfies ReasonTable<'provider response'>;

export type {
CloudProviderProfileFields,
DaemonRpcMode,
Expand Down
21 changes: 21 additions & 0 deletions packages/provider-revyl/src/revyl-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,27 @@ test('uses the public Revyl backend when no URL is configured', () => {
assert.equal(client.backendUrl, REVYL_DEFAULT_BACKEND_URL);
});

test('rejects an oversized provider answer before accepting its body', async () => {
const client = clientResponding(
() =>
new Response(
new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array(32 * 1024 * 1024 + 1));
},
}),
{ status: 200, headers: { 'content-type': 'application/json' } },
),
);
await assert.rejects(
client.verifyCredentials(),
(error: unknown) =>
error instanceof AppError &&
error.details?.reason === 'provider_response_too_large' &&
error.details?.limitBytes === 32 * 1024 * 1024,
);
});

test('keeps plain HTTP only on loopback', () => {
assert.equal(resolveRevylBackendUrl('http://127.0.0.1:8787'), 'http://127.0.0.1:8787');
assert.equal(resolveRevylBackendUrl('http://localhost:8787'), 'http://localhost:8787');
Expand Down
29 changes: 28 additions & 1 deletion packages/provider-revyl/src/revyl-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
} from '@agent-device/kernel/errors';
import { isRecord } from '@agent-device/kernel/record';
import { isLoopbackHostname } from '@agent-device/contracts/loopback-host';
import { PROVIDER_RESPONSE_REASONS } from '@agent-device/contracts/remote';
import fs from 'node:fs';
import { Readable } from 'node:stream';
import { setTimeout as sleep } from 'node:timers/promises';
Expand All @@ -30,6 +31,8 @@ export const REVYL_DEFAULT_BACKEND_URL = 'https://backend.revyl.ai';
const REVYL_ATTRIBUTION = 'agent-device';

const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
const MAX_REVYL_RESPONSE_BYTES = 32 * 1024 * 1024;

/** How long `start_device` may take to answer: Revyl assigns a worker and boots the device in it. */
export const REVYL_START_DEVICE_TIMEOUT_MS = 120_000;
const RETRY_DELAYS_MS = [500, 1_500] as const;
Expand Down Expand Up @@ -379,9 +382,10 @@ async function sendOnce(
return Object.freeze({
status: response.status,
contentType: response.headers.get('content-type') ?? undefined,
body: new Uint8Array(await response.arrayBuffer()),
body: await readRevylResponseBody(response),
});
} catch (error) {
if (error instanceof AppError) return error;
if (request.signal?.aborted) return requestCanceled(request, error);
if (timeout.aborted) return requestTimedOut(request, error);
return new AppError(
Expand All @@ -393,6 +397,29 @@ async function sendOnce(
}
}

async function readRevylResponseBody(response: Response): Promise<Uint8Array> {
if (!response.body) return new Uint8Array();
const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
let bytes = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) return new Uint8Array(Buffer.concat(chunks, bytes));
bytes += value.byteLength;
if (bytes > MAX_REVYL_RESPONSE_BYTES) {
throw new AppError('COMMAND_FAILED', 'Revyl response exceeds the size limit.', {
Comment thread
thymikee marked this conversation as resolved.
Resolved
reason: PROVIDER_RESPONSE_REASONS.tooLarge.reason,
limitBytes: MAX_REVYL_RESPONSE_BYTES,
});
}
chunks.push(value);
}
} finally {
void reader.cancel().catch(() => {});
}
}

/**
* Only a request that never reached Revyl, or a status Revyl marks transient, is replayed. A
* cancellation is the caller's own answer, and a timeout has already spent the request's budget, so
Expand Down
22 changes: 22 additions & 0 deletions packages/provider-webdriver/src/webdriver-transport.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,28 @@ afterEach(() => {
globalThis.fetch = realFetch;
});

test('WebDriver stops reading a response after its byte limit', async () => {
const transport = new WebDriverTransport({
clientVersion: '0.0.0-test',
endpoint: 'https://cloud-webdriver.test/wd/hub/',
});
globalThis.fetch = async () =>
new Response(
new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array(32 * 1024 * 1024 + 1));
},
}),
);
await assert.rejects(
transport.requestValue('GET', '/session/x/source'),
(error: unknown) =>
error instanceof AppError &&
error.details?.reason === 'provider_response_too_large' &&
error.details?.dispatched === 'unknown',
);
});

// The transport's own deadline must surface as a machine-readable reason, not
// as fetch's `AbortError`/`TimeoutError` DOMException name: the session manager
// keys its "the provider may still be creating a billed session" branch on
Expand Down
21 changes: 19 additions & 2 deletions packages/provider-webdriver/src/webdriver-transport.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { setTimeout as sleep } from 'node:timers/promises';
import { AppError, type DispatchDisclosure, type ReasonTable } from '@agent-device/kernel/errors';
import { agentDeviceRequestHeaders } from './request-headers.ts';
import { basicAuthHeader, trimLeadingSlash, withTrailingSlash } from './webdriver-utils.ts';
import {
basicAuthHeader,
readProviderTextBody,
trimLeadingSlash,
withTrailingSlash,
} from './webdriver-utils.ts';

/** Why a WebDriver request failed at the transport. */
const WEBDRIVER_TRANSPORT_REASONS = {
Expand Down Expand Up @@ -261,8 +266,20 @@ export class WebDriverTransport {
throw classifyWebDriverFetchFailure(error, failure, 'request');
}
try {
return { ok: response.ok, status: response.status, text: await response.text() };
return {
ok: response.ok,
status: response.status,
text: await readProviderTextBody(response),
};
} catch (error) {
if (error instanceof AppError) {
throw new AppError(
error.code,
error.message,
{ ...error.details, ...dispatchDisclosure('unknown') },
error,
);
}
throw classifyWebDriverFetchFailure(error, failure, 'response');
}
}
Expand Down
5 changes: 5 additions & 0 deletions packages/provider-webdriver/src/webdriver-utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ test('the hub upload helper posts with credentials and returns the vendor refere
assert.equal(await postHubAppUpload(form, hub), 'hub://APP1');
});

test('the hub upload helper parses a response with a UTF-8 byte-order mark', async () => {
globalThis.fetch = async () => new Response('\ufeff{"ref":"hub://APP1"}');
assert.equal(await postHubAppUpload(new FormData(), hub), 'hub://APP1');
});

test('the hub upload helper fails typed with the status on an error page or a missing reference', async () => {
for (const response of [
new Response('<html>502 Bad Gateway</html>', { status: 502 }),
Expand Down
31 changes: 30 additions & 1 deletion packages/provider-webdriver/src/webdriver-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type {
} from '@agent-device/contracts/device';
import {
PROVIDER_DEVICE_ORIENTATIONS,
PROVIDER_RESPONSE_REASONS,
type ProviderDeviceOrientation,
} from '@agent-device/contracts/remote';
import { AppError, errorMessage, type ReasonTable } from '@agent-device/kernel/errors';
Expand Down Expand Up @@ -74,6 +75,32 @@ export function withTrailingSlash(url: URL): URL {

type HubCredentials = { username: string; accessKey: string };

const MAX_PROVIDER_RESPONSE_BYTES = 32 * 1024 * 1024;

/** Bound provider answers even when a peer omits or lies about Content-Length. */
export async function readProviderTextBody(response: Response): Promise<string> {
if (!response.body) return '';
const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
let bytes = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) return new TextDecoder().decode(Buffer.concat(chunks, bytes));
bytes += value.byteLength;
if (bytes > MAX_PROVIDER_RESPONSE_BYTES) {
throw new AppError('COMMAND_FAILED', 'Provider response exceeds the size limit.', {
reason: PROVIDER_RESPONSE_REASONS.tooLarge.reason,
limitBytes: MAX_PROVIDER_RESPONSE_BYTES,
});
}
chunks.push(value);
}
} finally {
void reader.cancel().catch(() => {});
}
}

/**
* A multipart form carrying the local app file under the hub's field name. Upload APIs take one
* regular file, so anything else (an extracted `.app` directory, a missing path) is refused here,
Expand Down Expand Up @@ -142,6 +169,7 @@ export async function postHubAppUpload(
json = await readProviderJsonBody(response);
} catch (error) {
if (signal?.aborted) throw error;
if (error instanceof AppError) throw error;
const timedOut = timeoutSignal.aborted;
throw new AppError(
'COMMAND_FAILED',
Expand Down Expand Up @@ -325,6 +353,7 @@ export async function fetchProviderSessionDetails(
});
json = await readProviderJsonBody(response);
} catch (error) {
if (error instanceof AppError) throw error;
throw new AppError(
'COMMAND_FAILED',
`${options.service} session details lookup failed.`,
Expand All @@ -347,7 +376,7 @@ export async function fetchProviderSessionDetails(

/** A provider response body parsed as JSON, or `undefined` when it is empty or not JSON (a gateway error page). */
async function readProviderJsonBody(response: Response): Promise<unknown> {
const text = await response.text();
const text = await readProviderTextBody(response);
Comment thread
thymikee marked this conversation as resolved.
Resolved
if (text.length === 0) return undefined;
try {
return JSON.parse(text) as unknown;
Expand Down
33 changes: 33 additions & 0 deletions src/core/interactors/limrun-http-response.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { expect, test } from 'vitest';
import { readLimrunControlJson } from './limrun-http-response.ts';

test('stops an oversized Limrun control response before accepting its body', async () => {
const response = new Response('{}', {
Comment thread
thymikee marked this conversation as resolved.
Resolved
headers: { 'content-length': String(32 * 1024 * 1024 + 1) },
});

await expect(readLimrunControlJson(response)).rejects.toMatchObject({
code: 'COMMAND_FAILED',
details: { reason: 'provider_response_too_large', limitBytes: 32 * 1024 * 1024 },
});
});

test('stops a streaming Limrun control response without a declared length', async () => {
const response = new Response(
new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array(32 * 1024 * 1024 + 1));
},
}),
);

await expect(readLimrunControlJson(response)).rejects.toMatchObject({
code: 'COMMAND_FAILED',
details: { reason: 'provider_response_too_large', limitBytes: 32 * 1024 * 1024 },
});
});

test('parses a bounded Limrun control response with a UTF-8 byte-order mark', async () => {
const response = new Response('\ufeff{"synced":true}');
await expect(readLimrunControlJson(response)).resolves.toEqual({ synced: true });
});
48 changes: 48 additions & 0 deletions src/core/interactors/limrun-http-response.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { AppError } from '@agent-device/kernel/errors';
import { PROVIDER_RESPONSE_REASONS } from '@agent-device/contracts/remote';

const MAX_LIMRUN_CONTROL_RESPONSE_BYTES = 32 * 1024 * 1024;

export async function readLimrunControlText(
response: Response,
signal?: AbortSignal,
): Promise<string> {
signal?.throwIfAborted();
const declaredBytes = Number(response.headers.get('content-length'));
if (Number.isFinite(declaredBytes) && declaredBytes > MAX_LIMRUN_CONTROL_RESPONSE_BYTES) {
await response.body?.cancel().catch(() => {});
throw responseTooLarge();
Comment thread
thymikee marked this conversation as resolved.
Resolved
}
if (!response.body) return '';
const reader = response.body.getReader();
const cancel = () => void reader.cancel(signal?.reason).catch(() => {});
signal?.addEventListener('abort', cancel, { once: true });
const chunks: Uint8Array[] = [];
let bytes = 0;
try {
while (true) {
const { done, value } = await reader.read();
signal?.throwIfAborted();
if (done) return new TextDecoder().decode(Buffer.concat(chunks, bytes));
bytes += value.byteLength;
if (bytes > MAX_LIMRUN_CONTROL_RESPONSE_BYTES) {
throw responseTooLarge();
}
chunks.push(value);
}
} finally {
signal?.removeEventListener('abort', cancel);
void reader.cancel().catch(() => {});
}
}

function responseTooLarge(): AppError {
return new AppError('COMMAND_FAILED', 'Limrun response exceeds the size limit.', {
reason: PROVIDER_RESPONSE_REASONS.tooLarge.reason,
limitBytes: MAX_LIMRUN_CONTROL_RESPONSE_BYTES,
});
}

export async function readLimrunControlJson<T>(response: Response): Promise<T> {
return JSON.parse(await readLimrunControlText(response)) as T;
}
7 changes: 5 additions & 2 deletions src/core/interactors/limrun-ios-files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
import type { LimrunRuntimeDependencies } from '@agent-device/provider-limrun';
import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors';
import { downloadLimrunFile } from '../limrun-download-file.ts';
import { readLimrunControlJson } from './limrun-http-response.ts';

type Session = Parameters<LimrunRuntimeDependencies['ios']['createRunner']>[0];
type Files = AppleToolProvider['simulatorFiles'];
Expand Down Expand Up @@ -95,7 +96,9 @@ export function createLimrunSimulatorFiles(
const list = () =>
operation(container, async (signal) => {
const response = await request('GET', urlFor('files/list', '', container), signal);
const result = (await response.json()) as { entries: Array<{ name: string }> };
const result = await readLimrunControlJson<{ entries: Array<{ name: string }> }>(
response,
);
return result.entries.map((entry) => entry.name);
});
try {
Expand Down Expand Up @@ -141,7 +144,7 @@ export function createLimrunSimulatorFiles(
signal,
await fs.readFile(localPath, { signal }),
);
return (await response.json()) as { path: string };
return await readLimrunControlJson<{ path: string }>(response);
}).catch(async (error: unknown) => {
await remove().catch(() => {});
throw error;
Expand Down
3 changes: 2 additions & 1 deletion src/core/interactors/limrun-ios-runner-products.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { limrunRunnerError } from './limrun-ios-runner-errors.ts';
import { readLimrunControlJson } from './limrun-http-response.ts';
import { awaitWithSignal } from '@agent-device/kernel/await-with-signal';
import {
runnerListenerEnv,
Expand Down Expand Up @@ -305,7 +306,7 @@ export async function uploadLimrunRunnerProducts(
},
);
}
return (await response.json()) as { ok?: boolean; needFull?: string[] };
return await readLimrunControlJson<{ ok?: boolean; needFull?: string[] }>(response);
} finally {
stream.destroy();
await compression;
Expand Down
Loading
Loading