Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
58a95b2
fix(remote)!: never send credentials over plain http off loopback
thymikee Nov 27, 2026
f566b46
fix(remote): close the remaining cleartext credential paths
thymikee Nov 27, 2026
cdbb0ae
fix(remote): satisfy the layering, lint, and coverage gates
thymikee Nov 27, 2026
94582ba
chore(wire-compat): acknowledge the direct-connection transport changes
thymikee Nov 27, 2026
358e2b4
test(remote): pin the direct agent on the request diagnostics fetch
thymikee Nov 27, 2026
18a45e1
fix(proxy): relay upstream redirects instead of refusing them
thymikee Nov 27, 2026
05f08d9
fix(proxy): one redirect rule across routes, with a safe relayed Loca…
thymikee Nov 27, 2026
3c6adad
fix(host-kit): break the direct-http import cycle and share the heade…
thymikee Nov 27, 2026
6d13926
fix(remote): close the remaining credential transport gaps
thymikee Nov 27, 2026
7f7168a
fix(remote): cover the Revyl client and the Metro bridge socket
thymikee Nov 27, 2026
96d8f4f
test(react-native): handle a peer reset on the companion test bridge
thymikee Nov 27, 2026
3db25a8
fix(remote): close the gaps a focused review found
thymikee Nov 27, 2026
3b9b896
fix(remote): release aborted uploads and narrow the tunnel exception
thymikee Nov 27, 2026
221f662
fix(remote): send every credential through one checked primitive
thymikee Nov 27, 2026
50fb538
test(react-native): build the companion test redirect from constants
thymikee Nov 27, 2026
85cc91c
test(proxy): cover cancellation of a plain-http upstream exchange
thymikee Nov 27, 2026
572b141
refactor(remote)!: apply the credential transport rule over plain fetch
thymikee Nov 27, 2026
071e33c
fix(react-native): relay an absolute path on the local base origin
thymikee Nov 27, 2026
8a7acf1
fix(remote): use fetch redirect modes and check relayed sockets
thymikee Nov 28, 2026
e6b07ff
fix(remote): follow no redirect on credentialed bridge and profile re…
thymikee Nov 28, 2026
e7b2e16
fix(limrun): pass the download URL to fetch as a string
thymikee Nov 28, 2026
98a5c09
test: expect a redirected cloud profile request to fail
thymikee Nov 28, 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
84 changes: 83 additions & 1 deletion packages/apple-runner/src/__tests__/runner-transport.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,11 @@ vi.mock('../runner-usbmux.ts', async (importOriginal) => {
});

import { clearDeviceTunnelIpCache } from '../runner-command-route.ts';
import { fetchWithTimeout, sendRunnerCommandOnce } from '../runner-transport.ts';
import {
fetchWithTimeout,
postRunnerCommandOverRoute,
sendRunnerCommandOnce,
} from '../runner-transport.ts';
import { mkdtempForTestSync } from './tmp-dir.ts';

// The real `resolveIosPhysicalDeviceControl` resolves the CoreDevice tunnel IP
Expand Down Expand Up @@ -211,6 +215,84 @@ test('sendRunnerCommandOnce reaches the macOS host runner on loopback, never ove
assert.equal(mockRunCmd.mock.calls.length, 0);
});

test('a forwarded runner route never sends its tokens over plain http off loopback', async () => {
const fetchMock = vi.fn();
vi.stubGlobal('fetch', fetchMock);
const endpoint = {
...RUNNER_ENDPOINT_FIXTURE,
http: { url: 'http://instance.invalid/command', headers: { Authorization: 'Bearer limrun' } },
};

await assert.rejects(
() => sendRunnerCommandOnce(iosSimulator, endpoint, { command: 'uptime' }),
(error: unknown) => {
assert.ok(error instanceof AppError);
assert.equal(error.details?.reason, 'insecure_credential_transport');
assert.equal(error.details?.dispatched, 'no');
return true;
},
);
assert.equal(fetchMock.mock.calls.length, 0);
});

test('the runner sends to a CoreDevice tunnel address with fetch, as a bracketed fd00:: host', async () => {
mockUsbmuxPostCommand.mockRejectedValue(usbmuxDeviceUnattachedError());
stubSuccessfulFetch();
mockRunCmd.mockImplementation(makeTunnelIpLookup('fda3:3a9e:368d::1'));

await sendRunnerCommandOnce(iosDevice, RUNNER_ENDPOINT_FIXTURE, { command: 'uptime' });

const [url, init] = vi.mocked(fetch).mock.calls[0]!;
assert.equal(url, 'http://[fda3:3a9e:368d::1]:8100/command');
assert.equal(init?.redirect, 'error');
});

// The same address is allowed on the tunnel route above, so the exclusion
// follows how the route was resolved, not what the address looks like.
test('a route CoreDevice did not report is refused even at a tunnel-shaped address', async () => {
const fetchMock = vi.fn();
vi.stubGlobal('fetch', fetchMock);
const route = {
kind: 'network',
url: 'http://[fd00::123]:8100/command',
cachedTunnelIp: false,
} as const;

await assert.rejects(
() =>
postRunnerCommandOverRoute(iosDevice, route, {
endpoint: RUNNER_ENDPOINT_FIXTURE,
command: { command: 'uptime' },
timeoutMs: 5_000,
}),
(error: unknown) => {
assert.equal((error as AppError).details?.reason, 'insecure_credential_transport');
assert.equal((error as AppError).details?.dispatched, 'no');
return true;
},
);
assert.equal(fetchMock.mock.calls.length, 0);
});

test.each(['fe80::1', '2001:db8::1', 'fc00::1', '10.0.0.7', 'iphone.coredevice.local'])(
'a reported tunnel address of %s is no tunnel route, so it never receives the runner token',
async (reported) => {
mockUsbmuxPostCommand.mockRejectedValue(usbmuxDeviceUnattachedError());
stubSuccessfulFetch();
mockRunCmd.mockImplementation(makeTunnelIpLookup(reported));

await assert.rejects(
() => sendRunnerCommandOnce(iosDevice, RUNNER_ENDPOINT_FIXTURE, { command: 'uptime' }),
(error: unknown) => {
assert.equal((error as AppError).details?.reason, 'insecure_credential_transport');
assert.equal((error as AppError).details?.dispatched, 'no');
return true;
},
);
assert.equal(vi.mocked(fetch).mock.calls.length, 0);
},
);

test('sendRunnerCommandOnce writes nothing for a device with no route, and says so', async () => {
mockUsbmuxPostCommand.mockRejectedValue(usbmuxDeviceUnattachedError());
const fetchMock = vi.fn();
Expand Down
7 changes: 7 additions & 0 deletions packages/apple-runner/src/runner-command-route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ export type RunnerCommandRoute =
kind: 'network';
url: string | null;
cachedTunnelIp: boolean;
/**
* Set only on the route built from the tunnel address CoreDevice reports for this device.
* Its tunnel encrypts the traffic, so it may carry the runner token over plain http to a
* tunnel address that is not loopback.
*/
coreDeviceTunnel?: true;
}
| {
kind: 'usbmux';
Expand Down Expand Up @@ -115,6 +121,7 @@ function buildTunnelRoute(
kind: 'network',
url: tunnelIp ? `http://[${tunnelIp}]:${port}/command` : null,
cachedTunnelIp,
coreDeviceTunnel: true,
};
}

Expand Down
12 changes: 12 additions & 0 deletions packages/apple-runner/src/runner-transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,18 @@ export async function postRunnerCommandOverRoute(
'no',
);
}
// The request carries the runner token, and a forwarded one the provider's own headers. A
// simulator or macOS runner listens on 127.0.0.1, so only another route loads the rule.
if (URL.parse(route.url)?.hostname !== '127.0.0.1') {
const { assertSecureCredentialTransport } =
await import('@agent-device/contracts/credential-transport');
assertSecureCredentialTransport(
route.url,
endpoint.http ? 'Runner forwarding URL' : 'Runner device address',
{ coreDeviceTunnel: route.coreDeviceTunnel },
);
throwIfCanceledBeforeSend(signal);
}
const response = await fetchWithTimeout(
route.url,
{
Expand Down
8 changes: 8 additions & 0 deletions packages/contracts/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,10 @@
"types": "./src/daemon-command-surface.ts",
"default": "./src/daemon-command-surface.ts"
},
"./credential-transport": {
"types": "./src/credential-transport.ts",
"default": "./src/credential-transport.ts"
},
"./daemon-http": {
"types": "./src/daemon-http.ts",
"default": "./src/daemon-http.ts"
Expand Down Expand Up @@ -308,6 +312,10 @@
"types": "./src/logs-runtime-plan.ts",
"default": "./src/logs-runtime-plan.ts"
},
"./loopback-host": {
"types": "./src/loopback-host.ts",
"default": "./src/loopback-host.ts"
},
"./managed-web-backend": {
"types": "./src/managed-web-backend.ts",
"default": "./src/managed-web-backend.ts"
Expand Down
97 changes: 97 additions & 0 deletions packages/contracts/src/credential-transport.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { expect, test } from 'vitest';
import { AppError } from '@agent-device/kernel/errors';
import {
assertSecureCredentialSocket,
assertSecureCredentialTransport,
} from './credential-transport.ts';
import { isLoopbackHostname } from './loopback-host.ts';

test('loopback hostnames are recognized in each spelling a base URL carries', () => {
expect(isLoopbackHostname('LocalHost ')).toBe(true);
expect(isLoopbackHostname('127.0.0.1')).toBe(true);
expect(isLoopbackHostname('[::1]')).toBe(true);
expect(isLoopbackHostname('::ffff:127.0.0.1')).toBe(true);
expect(isLoopbackHostname('0.0.0.0')).toBe(false);
expect(isLoopbackHostname('127.1.2.3')).toBe(true);
expect(isLoopbackHostname('localhost.example.test')).toBe(false);
expect(isLoopbackHostname('')).toBe(false);
});

test.each([
'https://fleet.example.test/agent-device',
'https://10.0.0.7:4310',
'http://127.0.0.1:4310/agent-device',
'http://[::1]:4310',
'http://localhost:4310',
])('a credential may travel to %s', (url) => {
expect(assertSecureCredentialTransport(url, 'Remote daemon base URL').href).toBe(
new URL(url).href,
);
});

test.each([
'http://fleet.example.test/agent-device',
'http://10.0.0.7:4310',
'http://0.0.0.0:4310',
'http://localhost.:4310',
'ws://127.0.0.1:4310',
'http:',
])('a credential never travels to %s', (url) => {
let refusal: unknown;
try {
assertSecureCredentialTransport(url, 'Remote daemon base URL');
} catch (error) {
refusal = error;
}
expect(refusal).toBeInstanceOf(AppError);
expect((refusal as AppError).code).toBe('INVALID_ARGS');
expect((refusal as AppError).details?.reason).toBe('insecure_credential_transport');
});

test.each([
'wss://bridge.example.test/bridge?ticket=t',
'ws://127.0.0.1:4310/bridge?ticket=t',
'WS://[::1]:4310/bridge',
'ws://localhost:4310/bridge',
])('a credential socket may open to %s', (url) => {
expect(assertSecureCredentialSocket(url, 'Bridge socket URL').href).toBe(new URL(url).href);
});

test.each([
'ws://bridge.example.test/bridge?ticket=t',
'ws://10.0.0.7:4310/bridge',
'http://localhost/bridge',
'http://127.0.0.1:4310/bridge',
'https://bridge.example.test/bridge',
'ftp://127.0.0.1/bridge',
'ws:',
])('a credential socket never opens to %s', (url) => {
expect(() => assertSecureCredentialSocket(url, 'Bridge socket URL')).toThrow(
expect.objectContaining({
details: expect.objectContaining({ reason: 'insecure_credential_transport' }),
}),
);
});

test.each(['http://[fd00::1]:8100/command', 'http://[fdda:2b::42]:8100'])(
'the CoreDevice tunnel exception admits %s, and only when asked for',
(url) => {
expect(() => assertSecureCredentialTransport(url, 'Runner URL')).toThrow();
expect(
assertSecureCredentialTransport(url, 'Runner URL', { coreDeviceTunnel: true }).href,
).toBe(new URL(url).href);
},
);

test.each([
'http://[fe80::1]:8100',
'http://[fc00::1]:8100',
'http://[2001:db8::1]:8100',
'http://10.0.0.7:8100',
'http://iphone.coredevice.local:8100',
'ws://[fd00::1]:8100',
])('the CoreDevice tunnel exception never admits %s', (url) => {
expect(() =>
assertSecureCredentialTransport(url, 'Runner URL', { coreDeviceTunnel: true }),
).toThrow();
});
90 changes: 90 additions & 0 deletions packages/contracts/src/credential-transport.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import net from 'node:net';
import { AppError, type ReasonTable } from '@agent-device/kernel/errors';
import { isLoopbackHostname } from './loopback-host.ts';

// The one rule for every request that carries a credential (a daemon or proxy token, a host bridge
// or provider bearer, a cloud auth secret): it travels over https, or over plain http only to this
// machine.

/** Why a client refuses to send a credential before any request leaves. */
const CREDENTIAL_TRANSPORT_REASONS = {
// A credential would travel over plain http or ws to a host that is not loopback, to a socket URL
// that is not ws or wss, or to a URL that does not parse. The refusal names the setting, never
// the destination.
insecureTransport: { reason: 'insecure_credential_transport' },
} as const satisfies ReasonTable<'remote connection'>;

/** The one plain-http destination off loopback a credential may name, and only when asked for. */
export type CredentialTransportExceptions = {
/** The request goes to a device's CoreDevice tunnel address, which that tunnel encrypts. */
coreDeviceTunnel?: boolean;
};

/** Whether a credential sent to `url` stays off the network in cleartext: https, or http on loopback. */
export function isSecureCredentialDestination(url: URL): boolean {
if (url.protocol === 'https:') return true;
return url.protocol === 'http:' && isLoopbackHostname(url.hostname);
}

/** Plain http to a unique local IPv6 address in `fd00::/8`, where CoreDevice puts its tunnel. */
function isCoreDeviceTunnelDestination(url: URL): boolean {
const address = url.hostname.replace(/^\[(.*)\]$/, '$1');
const range = new net.BlockList();
range.addSubnet('fd00::', 8, 'ipv6');
return url.protocol === 'http:' && net.isIPv6(address) && range.check(address, 'ipv6');
}

/**
* Refuses a credential-bearing destination unless it is https or plain http to loopback. A URL
* that does not parse is refused too. `subject` names the setting in the message; the destination
* itself is never named, so a refusal is safe on paths that must not disclose their endpoint.
*/
export function assertSecureCredentialTransport(
url: string | URL,
subject: string,
exceptions: CredentialTransportExceptions = {},
): URL {
const destination = typeof url === 'string' ? URL.parse(url) : url;
if (destination) {
if (isSecureCredentialDestination(destination)) return destination;
if (exceptions.coreDeviceTunnel && isCoreDeviceTunnelDestination(destination)) {
return destination;
}
}
throw credentialTransportRefusal(
destination
? `${subject} must use https to send credentials; plain http is allowed only on loopback.`
: `${subject} is not a valid URL, so no credential is sent to it.`,
);
}

/**
* The same rule for a WebSocket that carries a credential: `wss` to any host, or `ws` to loopback.
* Any other scheme is refused, including the http and https a `WebSocket` would accept.
*/
export function assertSecureCredentialSocket(url: string, subject: string): URL {
const destination = URL.parse(url);
if (destination?.protocol === 'wss:') return destination;
if (destination?.protocol === 'ws:' && isLoopbackHostname(destination.hostname)) {
return destination;
}
throw credentialTransportRefusal(
`${subject} must use wss to send credentials; ws is allowed only on loopback.`,
);
}

/** The typed refusal. It is only ever thrown before the credential leaves. */
function credentialTransportRefusal(message: string): AppError {
return new AppError('INVALID_ARGS', message, {
reason: CREDENTIAL_TRANSPORT_REASONS.insecureTransport.reason,
dispatched: 'no',
hint: 'Use an https or wss URL, or reach the host through a loopback tunnel or port forward, for example ssh -L 4310:127.0.0.1:4310 <host> and then http://127.0.0.1:4310.',
});
}

export function isCredentialTransportRefusal(error: unknown): error is AppError {
return (
error instanceof AppError &&
error.details?.reason === CREDENTIAL_TRANSPORT_REASONS.insecureTransport.reason
);
}
18 changes: 18 additions & 0 deletions packages/contracts/src/loopback-host.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import net from 'node:net';

const LOOPBACK_BLOCK_LIST = new net.BlockList();
LOOPBACK_BLOCK_LIST.addSubnet('127.0.0.0', 8, 'ipv4');
LOOPBACK_BLOCK_LIST.addAddress('::1', 'ipv6');
LOOPBACK_BLOCK_LIST.addSubnet('::ffff:127.0.0.0', 104, 'ipv6');

/** Whether an address names this machine: `localhost` or a loopback literal. */
export function isLoopbackHostname(hostname: string): boolean {
const normalized = hostname
.trim()
.toLowerCase()
.replace(/^\[(.*)\]$/, '$1');
if (normalized === 'localhost') return true;
if (net.isIPv4(normalized)) return LOOPBACK_BLOCK_LIST.check(normalized, 'ipv4');
if (net.isIPv6(normalized)) return LOOPBACK_BLOCK_LIST.check(normalized, 'ipv6');
return false;
}
Loading
Loading