Skip to content

Commit 4e13a8d

Browse files
feat(remote): add a host-allocated macos-app lease backend
A macos-app lease confines a proxy client to one macOS app, named by bundle id and optionally pinned to a pid. Only the host allocates it, over the loopback /admin/leases route with the daemon token. Request admission refuses other apps, non-app surfaces, full-screen capture and commands outside an allow list, and requires the native app backend. A session under the lease holds its app rather than the host Mac. A daemon policy leases.require refuses requests that name no lease, and /health advertises leaseBackends. Refs callstack#3229.
1 parent b8826b5 commit 4e13a8d

31 files changed

Lines changed: 1541 additions & 37 deletions

‎docs/adr/0007-remote-device-leases.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,30 @@ reconnect and re-establish them; no persisted hold store is used. Local takeover
164164
future host-global human-control fence must coexist with the local session's device claim, not
165165
acquire it exclusively.
166166

167+
## macOS app leases
168+
169+
A lease on the macOS host would rent the whole desktop, so the macOS platform rents one app instead.
170+
A `macos-app` lease's device key is a bundle id, optionally pinned to one process
171+
(`<bundleId>` or `<bundleId>@<pid>`). The scope would be self-chosen if a tenant could name it, so
172+
only a host administrator allocates one, over the loopback `/admin/leases` route that uses the daemon
173+
token like host holds; tenant `lease_allocate` refuses the backend. The host picks the lease id, a
174+
repeated PUT renews it, and a PUT naming another scope for an existing id is refused rather than
175+
rewritten. Heartbeat, expiry, release, and the loss on daemon restart are those of any lease.
176+
177+
Request admission confines every request admitted under the lease, so `batch` steps and `replay`
178+
actions are confined when they re-enter it: an allow list of commands (later commands are refused),
179+
`open` and `close` of the leased bundle only, the `app` surface only, window-only screenshots, no
180+
input that names a host path or launches beside the app, and a session that is the leased app. `open` requires the native app backend (ADR 0031), because XCTest
181+
posts screen events that can land outside the app's window. A pid-pinned lease is checked against the
182+
running process before each admitted request. A session opened under the lease holds its app, not
183+
the Mac: it takes no host device claim, and other app-leased sessions on the same Mac do not conflict
184+
with it, so one daemon serves several leased apps beside the host's own sessions.
185+
186+
These rules bind a request that names the lease or runs in its session. A daemon policy
187+
`leases.require` (ADR 0029) refuses requests that name no lease. The proxy token is one credential
188+
for every client, so a host serving several clients through one proxy authenticates each client and
189+
sets its tenant, session isolation, and lease on every request it forwards.
190+
167191
## Host managed-device durability amendment
168192

169193
ADR 0021 adds a narrow durability exception for Host leases backed by a managed-device allocator.

‎docs/adr/0029-daemon-policy.md‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ Accepted (2026-09-29).
2323
command asks for it. The one exception is Apple readiness rolling back a Simulator boot that
2424
the same request started and then canceled: the Simulator was not running before.
2525
4. A denial is `UNAUTHORIZED` with `details.reason: 'DAEMON_POLICY_DENIED'`, the `rule`
26-
(`command`, `device`, or `capability`), the policy digest, `retriable: false`, and a hint. It
26+
(`command`, `device`, `capability`, or `lease`), the policy digest, `retriable: false`, and a hint. It
2727
never names the policy's host path.
2828
5. The daemon publishes the policy digest in `daemon.json`. A client that names a policy refuses to
2929
reuse a daemon that enforces a different one, or none. A client that names no policy reuses
@@ -36,7 +36,8 @@ Accepted (2026-09-29).
3636
"version": 1,
3737
"devices": { "allow": [{ "udid": "8F1C…" }, { "serial": "emulator-5554" }] },
3838
"commands": { "deny": ["boot", "shutdown"] },
39-
"capabilities": { "deny": ["device-shutdown"] }
39+
"capabilities": { "deny": ["device-shutdown"] },
40+
"leases": { "require": "macos-app" }
4041
}
4142
```
4243

@@ -56,6 +57,10 @@ Accepted (2026-09-29).
5657
upgrade are denied by default.
5758
- `capabilities.deny` — operations denied whichever command reaches them. `device-shutdown` is the
5859
only capability today.
60+
- `leases.require` — a lease backend. Every request that lease admission gates must be admitted
61+
under a lease of that backend; a request naming no lease is refused instead of being admitted
62+
unleased. A denial carries `rule: 'lease'`. A host that confines clients to `macos-app` leases
63+
(ADR 0007) sets it so a client cannot drop its lease to reach the desktop.
5964

6065
Unknown keys are errors, so a misspelled rule cannot silently become no rule.
6166

‎packages/command-registry/src/flag-definitions-connection.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -131,8 +131,15 @@ export const CONNECTION_FLAG_DEFINITIONS: readonly FlagDefinition[] = [
131131
key: 'leaseBackend',
132132
names: ['--lease-backend'],
133133
type: 'enum',
134-
enumValues: ['ios-simulator', 'ios-instance', 'android-instance', 'harmonyos-instance'],
135-
usageLabel: '--lease-backend ios-simulator|ios-instance|android-instance|harmonyos-instance',
134+
enumValues: [
135+
'ios-simulator',
136+
'ios-instance',
137+
'android-instance',
138+
'harmonyos-instance',
139+
'macos-app',
140+
],
141+
usageLabel:
142+
'--lease-backend ios-simulator|ios-instance|android-instance|harmonyos-instance|macos-app',
136143
usageDescription: 'Lease backend for remote tenant connection admission',
137144
projectConfig: false,
138145
recorded: false,

‎packages/contracts/src/daemon-http.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,13 +57,20 @@ export type DaemonHealthPayload = {
5757
rpcProtocolVersion: number;
5858
instanceId?: string;
5959
hostArch?: string;
60+
/** The lease backends this daemon admits; a host checks it before relying on one. */
61+
leaseBackends?: readonly string[];
6062
upstream?: unknown;
6163
};
6264

6365
export function buildDaemonHealthPayload(
6466
service: DaemonHealthPayload['service'],
6567
version: string,
66-
options: { upstream?: unknown; instanceId?: string; hostArch?: string } = {},
68+
options: {
69+
upstream?: unknown;
70+
instanceId?: string;
71+
hostArch?: string;
72+
leaseBackends?: readonly string[];
73+
} = {},
6774
): DaemonHealthPayload {
6875
return {
6976
ok: true,
@@ -72,6 +79,7 @@ export function buildDaemonHealthPayload(
7279
rpcProtocolVersion: DAEMON_RPC_PROTOCOL_VERSION,
7380
...(options.instanceId !== undefined ? { instanceId: options.instanceId } : {}),
7481
...(options.hostArch !== undefined ? { hostArch: options.hostArch } : {}),
82+
...(options.leaseBackends !== undefined ? { leaseBackends: options.leaseBackends } : {}),
7583
...(options.upstream !== undefined ? { upstream: options.upstream } : {}),
7684
};
7785
}

‎packages/kernel/src/contracts.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,11 +51,12 @@ export type LocalInstallSource = Extract<DaemonInstallSource, { kind: 'url' | 'p
5151

5252
const DAEMON_LOCK_POLICIES = ['reject', 'strip'] as const;
5353
export type DaemonLockPolicy = (typeof DAEMON_LOCK_POLICIES)[number];
54-
const LEASE_BACKENDS = [
54+
export const LEASE_BACKENDS = [
5555
'ios-simulator',
5656
'ios-instance',
5757
'android-instance',
5858
'harmonyos-instance',
59+
'macos-app',
5960
] as const;
6061
export type LeaseBackend = (typeof LEASE_BACKENDS)[number];
6162

@@ -96,11 +97,14 @@ export function leaseBackendForPlatform(
9697
* plain object would answer `constructor` and friends with an inherited function, which is a platform
9798
* nobody rents.
9899
*/
99-
const PLATFORM_BY_LEASE_BACKEND = new Map<string, PublicPlatform>(
100-
Object.entries(LEASE_BACKEND_BY_PLATFORM).flatMap(([platform, backend]) =>
100+
const PLATFORM_BY_LEASE_BACKEND = new Map<string, PublicPlatform>([
101+
...Object.entries(LEASE_BACKEND_BY_PLATFORM).flatMap(([platform, backend]) =>
101102
backend === undefined ? [] : [[backend, platform as PublicPlatform] as const],
102103
),
103-
);
104+
// A `macos-app` lease rents one app on the macOS host, never the host itself, so no platform
105+
// selector resolves to it: only a host administrator allocates one, and its client names it.
106+
['macos-app', 'macos'],
107+
]);
104108

105109
export function platformForLeaseBackend(backend: string): PublicPlatform | undefined {
106110
return PLATFORM_BY_LEASE_BACKEND.get(backend);

‎src/__tests__/daemon-policy-file.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import crypto from 'node:crypto';
12
import fs from 'node:fs';
23
import path from 'node:path';
34
import { expect, test } from 'vitest';
@@ -35,6 +36,11 @@ test.each([
3536
[{ version: 1, devices: { allow: [] } }, /must not be empty/],
3637
[{ version: 1, devices: { allow: [{ udid: 'a', serial: 'b' }] } }, /exactly one "udid"/],
3738
[{ version: 1, capabilities: { deny: ['device-erase'] } }, /unknown capability "device-erase"/],
39+
[
40+
{ version: 1, leases: { require: 'macos-desktop' } },
41+
/"leases.require" must name a lease backend/,
42+
],
43+
[{ version: 1, leases: { allow: ['macos-app'] } }, /unknown key "leases.allow"/],
3844
])('rejects an invalid policy %j', (raw, message) => {
3945
expect(() => parseDaemonPolicy(raw, SOURCE)).toThrow(message);
4046
});
@@ -62,6 +68,7 @@ test('the digest names the rules, not their order or source path', () => {
6268
{ ...base, commands: { deny: ['boot', 'shutdown'] } },
6369
{ ...base, devices: { allow: [{ udid: 'b' }] } },
6470
{ ...base, capabilities: { deny: ['device-shutdown'] } },
71+
{ ...base, leases: { require: 'macos-app' } },
6572
];
6673

6774
expect(reordered.digest).toBe(first.digest);
@@ -70,6 +77,17 @@ test('the digest names the rules, not their order or source path', () => {
7077
}
7178
});
7279

80+
test('a policy without lease rules keeps the digest it had before lease rules existed', () => {
81+
const canonical = JSON.stringify({ devices: null, commands: null, capabilities: [] });
82+
const expected = crypto.createHash('sha256').update(canonical).digest('hex');
83+
expect(parseDaemonPolicy({ version: 1 }, SOURCE).digest).toBe(expected);
84+
expect(parseDaemonPolicy({ version: 1, leases: { require: 'macos-app' } }, SOURCE)).toMatchObject(
85+
{
86+
requiredLeaseBackend: 'macos-app',
87+
},
88+
);
89+
});
90+
7391
test('internal device commands are nameable by the public command they serve or by their own name', () => {
7492
expect(() =>
7593
parseDaemonPolicy(
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
import { expect, test } from 'vitest';
2+
import fs from 'node:fs';
3+
import { AppError } from '@agent-device/kernel/errors';
4+
import { connectionWorkspace, createTestClient } from './remote-connection.fixtures.ts';
5+
import { materializeRemoteConnectionForCommand } from '../cli/commands/connection-runtime.ts';
6+
import { readRemoteConnectionState } from '../remote/remote-connection-state.ts';
7+
import { LeaseRegistry } from '../daemon/lease-registry.ts';
8+
9+
const LEASE_ID = 'a1b2c3d4e5f60718293a4b5c6d7e8f90';
10+
11+
function writeHostIssuedConfig(remoteConfigPath: string): void {
12+
fs.writeFileSync(
13+
remoteConfigPath,
14+
JSON.stringify({
15+
daemonBaseUrl: 'https://host.example/agent/',
16+
daemonAuthToken: 'client-token',
17+
tenant: 'stim',
18+
runId: 'session-1',
19+
leaseId: LEASE_ID,
20+
leaseBackend: 'macos-app',
21+
leaseProvider: 'proxy',
22+
clientId: 'client-1',
23+
deviceKey: 'com.example.app@4242',
24+
platform: 'macos',
25+
}),
26+
);
27+
}
28+
29+
function flagsFor(stateDir: string, remoteConfig: string) {
30+
return {
31+
json: true,
32+
help: false,
33+
version: false,
34+
stateDir,
35+
remoteConfig,
36+
session: 'hosted',
37+
};
38+
}
39+
40+
test('a macos-app remote config opens on the lease the host allocated, unchanged', async () => {
41+
const { stateDir, remoteConfigPath } = connectionWorkspace('macos-app-open-');
42+
writeHostIssuedConfig(remoteConfigPath);
43+
const registry = new LeaseRegistry();
44+
registry.putHostLease(LEASE_ID, {
45+
tenantId: 'stim',
46+
runId: 'session-1',
47+
clientId: 'client-1',
48+
leaseBackend: 'macos-app',
49+
leaseProvider: 'proxy',
50+
deviceKey: 'com.example.app@4242',
51+
});
52+
const client = createTestClient({
53+
listDevices: async () => {
54+
throw new Error('a macos-app connection resolves no device into a new key');
55+
},
56+
allocate: async () => {
57+
throw new Error('a macos-app connection never allocates');
58+
},
59+
heartbeat: async (request) => registry.heartbeatLease({ ...request, tenantId: request.tenant }),
60+
});
61+
const flags = flagsFor(stateDir, remoteConfigPath);
62+
const materialized = await materializeRemoteConnectionForCommand({
63+
command: 'open',
64+
positionals: ['com.example.app'],
65+
flags,
66+
client,
67+
});
68+
expect(materialized.flags).toMatchObject({
69+
leaseId: LEASE_ID,
70+
leaseBackend: 'macos-app',
71+
platform: 'macos',
72+
});
73+
expect(materialized.connection).toMatchObject({ deviceKey: 'com.example.app@4242' });
74+
expect(readRemoteConnectionState({ stateDir, session: 'hosted' })).toMatchObject({
75+
leaseId: LEASE_ID,
76+
deviceKey: 'com.example.app@4242',
77+
});
78+
});
79+
80+
test('an inactive host lease is reported, never replaced by a tenant allocation', async () => {
81+
const { stateDir, remoteConfigPath } = connectionWorkspace('macos-app-inactive-');
82+
writeHostIssuedConfig(remoteConfigPath);
83+
let allocations = 0;
84+
const client = createTestClient({
85+
allocate: async () => {
86+
allocations += 1;
87+
throw new Error('unreachable');
88+
},
89+
heartbeat: async () => {
90+
throw new AppError('UNAUTHORIZED', 'Lease is not active', { reason: 'LEASE_NOT_FOUND' });
91+
},
92+
});
93+
await expect(
94+
materializeRemoteConnectionForCommand({
95+
command: 'snapshot',
96+
flags: flagsFor(stateDir, remoteConfigPath),
97+
client,
98+
}),
99+
).rejects.toMatchObject({ code: 'UNAUTHORIZED', details: { reason: 'LEASE_NOT_FOUND' } });
100+
expect(allocations).toBe(0);
101+
});

‎src/cli/commands/connection-runtime.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -434,6 +434,7 @@ type ConnectionLeasePolicy = {
434434
};
435435

436436
function connectionLeasePolicyForState(state: RemoteConnectionState): ConnectionLeasePolicy {
437+
if (state.leaseBackend === 'macos-app') return MACOS_APP_CONNECTION_LEASE_POLICY;
437438
const capabilities = connectionProviderCapabilities(state.leaseProvider);
438439
if (capabilities.leaseKind === 'proxy') {
439440
return PROXY_CONNECTION_LEASE_POLICY;
@@ -466,6 +467,24 @@ const PROXY_CONNECTION_LEASE_POLICY: ConnectionLeasePolicy = {
466467
resolveLeaseState: resolveProxyLeaseState,
467468
};
468469

470+
/**
471+
* A `macos-app` lease names one app, and the host allocated it: the client uses the lease its
472+
* remote config names as it is, and never resolves a device into a new key or allocates a lease.
473+
*/
474+
const MACOS_APP_CONNECTION_LEASE_POLICY: ConnectionLeasePolicy = {
475+
shouldAllocate: (command) => command !== 'devices' && !leaseDeferredCommands.has(command),
476+
ttlMs: () => undefined,
477+
resolveLeaseState: async ({ state }) => {
478+
if (!state.leaseId || !state.deviceKey) {
479+
throw new AppError(
480+
'INVALID_ARGS',
481+
'A macos-app connection needs the leaseId and deviceKey the host allocated in its remote config.',
482+
);
483+
}
484+
return { state: { ...state, platform: 'macos' } };
485+
},
486+
};
487+
469488
const CLOUD_WEBDRIVER_CONNECTION_LEASE_POLICY: ConnectionLeasePolicy = {
470489
shouldAllocate: (command) => !leaseDeferredCommands.has(command),
471490
ttlMs: () => CLOUD_WEBDRIVER_REMOTE_LEASE_TTL_MS,
@@ -870,6 +889,13 @@ async function allocateOrReuseLease(
870889
});
871890
if (existing) return { lease: existing, acquired: false };
872891
}
892+
if (leaseBackend === 'macos-app') {
893+
throw new AppError('UNAUTHORIZED', 'The host-allocated macos-app lease is no longer active.', {
894+
reason: 'LEASE_NOT_FOUND',
895+
leaseId: state.leaseId,
896+
hint: 'Ask the host for a new macos-app lease and update the remote config.',
897+
});
898+
}
873899
const lease = await client.leases.allocate({
874900
tenant: state.tenant,
875901
runId: state.runId,

‎src/commands/schema/cli-help.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -609,7 +609,7 @@ Human takeover of a leased remote device:
609609
agent-device takeover --session remote-session
610610
agent-device takeover status
611611
agent-device takeover release <hold-id>
612-
An HTTP-mode daemon also accepts authenticated GET/PUT/DELETE requests at /admin/human-control/holds on its loopback listener. Host administrators supply the exact lease backend/provider/device key and use the local daemon token, not a tenant credential. This host-admin route is intentionally not forwarded by agent-device proxy. Holds do not survive daemon restart; re-establish them after reconnecting.
612+
An HTTP-mode daemon also accepts authenticated GET/PUT/DELETE requests at /admin/human-control/holds on its loopback listener. Host administrators supply the exact lease backend/provider/device key and use the local daemon token, not a tenant credential. This host-admin route is intentionally not forwarded by agent-device proxy. Holds do not survive daemon restart; re-establish them after reconnecting. The same listener and token serve GET/PUT/DELETE /admin/leases, where a host allocates a macos-app lease confining a client to one app (<bundleId> or <bundleId>@<pid>); tenants cannot allocate one.
613613
614614
Cloud profile flow:
615615
agent-device connect

0 commit comments

Comments
 (0)