Skip to content

Commit 9a0fc7c

Browse files
committed
refactor(daemon): enforce require-owner in-memory claim guard in request device access
1 parent be2bf39 commit 9a0fc7c

8 files changed

Lines changed: 49 additions & 54 deletions

File tree

‎.changeset/device-selector-session-claim-guard.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@
22
'agent-device': patch
33
---
44

5-
Fix commands with an explicit device selector creating a session or executing capture and input against a device another active session already holds. Commands marked `require-owner` now enforce the device claim before capture, input, or session creation, refusing the request with `DEVICE_IN_USE`.
5+
Refuse `require-owner` commands run under a session this daemon does not hold with `DEVICE_IN_USE` when another session of this daemon holds the device (without reading the host-global claim store). Enforce the in-memory holder guard in the request scope's device access before inspecting device facts or binding, covering snapshot, wait, find, clipboard, keyboard, trigger-app-event, port-reverse, and record. Preserve `NO_ACTIVE_SESSION` for sessionless requests without a device selector.

‎packages/command-registry/src/types.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,9 @@ export type CommandTimeoutPolicy = {
8888
* - `observe` — device inventory/ownership projection; may report a
8989
* claim, never mutates one.
9090
* - `require-owner` — session-bound work; trusts the invariant `open`
91-
* established and does NO claim-store I/O.
91+
* established and does NO claim-store I/O. Refuses a
92+
* foreign in-memory session holder when its own session
93+
* is unheld.
9294
* - `transient-exclusive` — sessionless device mutation; acquires a
9395
* command-scoped claim before device operations reach
9496
* the handler, refuses a foreign claim, and releases

‎packages/daemon/src/core/snapshot-session.ts‎

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,15 +22,6 @@ export async function resolveSessionDevice(
2222
}
2323
const device =
2424
session?.device ?? (await resolveRequestTargetDevice(req, { env: sessionStore.host.env }));
25-
if (!session) {
26-
const inUse = sessionStore.findByDevice(device.id);
27-
if (inUse && inUse.address !== sessionName) {
28-
const { buildDeviceInUseBySessionError } = await import('./session-recovery-hints.ts');
29-
const refusal = buildDeviceInUseBySessionError(inUse, device);
30-
const { AppError } = await import('@agent-device/kernel/errors');
31-
throw new AppError(refusal.error.code, refusal.error.message, refusal.error.details);
32-
}
33-
}
3425
return { ref, session, device };
3526
}
3627

‎packages/daemon/src/execution/interaction/internal/interaction-touch-press-admission.ts‎

Lines changed: 1 addition & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -74,22 +74,7 @@ async function readTargetedTouchAdmission(
7474
): Promise<{ response: DaemonResponse } | { admitted: AdmittedTargetedTouch }> {
7575
const { req, sessionStore, sessionName } = params;
7676
const session = sessionStore.get(sessionName);
77-
if (!session) {
78-
const { hasDeviceSelectionInput } =
79-
await import('../../../core/device/device-selector-intent.ts');
80-
if (hasDeviceSelectionInput(req.flags)) {
81-
const { resolveRequestTargetDevice } =
82-
await import('../../../core/request-device-resolution.ts');
83-
const device = await resolveRequestTargetDevice(req, { env: sessionStore.host.env });
84-
const inUse = sessionStore.findByDevice(device.id);
85-
if (inUse && inUse.address !== sessionName) {
86-
const { buildDeviceInUseBySessionError } =
87-
await import('../../../core/session-recovery-hints.ts');
88-
return { response: buildDeviceInUseBySessionError(inUse, device) };
89-
}
90-
}
91-
return { response: noActiveSessionError() };
92-
}
77+
if (!session) return { response: noActiveSessionError() };
9378

9479
const commandLabel = command === 'click' ? 'click' : command;
9580
const policyResponse = targetedTouchPolicyResponse(session, command, commandLabel, req.flags);

‎packages/daemon/src/execution/selector-runtime-backend.ts‎

Lines changed: 1 addition & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -126,24 +126,10 @@ async function resolveSelectorRuntimeDevice(
126126
session,
127127
});
128128
}
129-
if (!session && requireSession) {
130-
const { hasDeviceSelectionInput } =
131-
await import('../core/device/device-selector-intent.ts');
132-
if (!hasDeviceSelectionInput(params.req.flags)) {
133-
return { ok: false, response: noActiveSessionError() };
134-
}
135-
}
129+
if (!session && requireSession) return { ok: false, response: noActiveSessionError() };
136130
const device =
137131
session?.device ??
138132
(await resolveRequestTargetDevice(params.req, { env: params.sessionStore.host.env }));
139-
if (!session) {
140-
const inUse = params.sessionStore.findByDevice(device.id);
141-
if (inUse && inUse.address !== params.sessionName) {
142-
const { buildDeviceInUseBySessionError } = await import('../core/session-recovery-hints.ts');
143-
return { ok: false, response: buildDeviceInUseBySessionError(inUse, device) };
144-
}
145-
}
146-
if (!session && requireSession) return { ok: false, response: noActiveSessionError() };
147133
return { ok: true, ref, session, device };
148134
}
149135

‎packages/daemon/src/server/__tests__/request-router-bounded-claim-recovery.test.ts‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -737,7 +737,7 @@ test('a later request does not inherit a prior request device pin', async () =>
737737
});
738738
});
739739

740-
test('snapshot and press with device selector are refused when another session holds device (#4228)', async () => {
740+
test('require-owner commands with device selector are refused when another session holds device (#4228)', async () => {
741741
const device = { ...makeIosDevice('SIM-HELD-BY-FIRST'), appleOs: 'ios' as const };
742742
process.env.AGENT_DEVICE_CLAIMS_DIR = root('issue-4228-claims-');
743743
const { handler, runtime, sessionStore } = route(device);
@@ -779,18 +779,18 @@ test('snapshot and press with device selector are refused when another session h
779779
error: { code: 'DEVICE_IN_USE', message: 'Device is already in use by session "first".' },
780780
});
781781

782-
// 3. Session B press with selector must also be refused with DEVICE_IN_USE
783-
const pressB = await handler({
782+
// 3. Session B clipboard write with selector (mutating handler family) must also be refused with DEVICE_IN_USE
783+
const clipboardB = await handler({
784784
token: 'test-token',
785785
session: 'second',
786-
command: 'press',
787-
positionals: ['400', '860'],
786+
command: 'clipboard',
787+
positionals: ['write', 'pasted text'],
788788
flags: { platform: 'ios', udid: 'SIM-HELD-BY-FIRST' },
789-
meta: { requestId: 'second-press', sessionExplicit: true },
789+
meta: { requestId: 'second-clipboard', sessionExplicit: true },
790790
});
791791
expect(sessionStore.get('second')).toBeUndefined();
792792
expect(runtime.bind).not.toHaveBeenCalled();
793-
expect(pressB).toMatchObject({
793+
expect(clipboardB).toMatchObject({
794794
ok: false,
795795
error: { code: 'DEVICE_IN_USE', message: 'Device is already in use by session "first".' },
796796
});

‎packages/daemon/src/server/request-execution-scope.ts‎

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,14 @@ import {
2626
} from '../core/context.ts';
2727
import { assertSessionSelectorMatches } from '../core/session-selector.ts';
2828
import {
29+
isImplicitSessionScopeConflict,
2930
resolveCallerScopeRoot,
3031
resolveEffectiveSessionName,
3132
} from '../sessions/session-routing.ts';
33+
import {
34+
buildDeviceInUseBySessionError,
35+
buildForeignWorkspaceSessionConflict,
36+
} from '../core/session-recovery-hints.ts';
3237
import { deriveWebSessionIdentity } from '../core/session-tenant-scope.ts';
3338
import {
3439
assertRequestLeaseAdmissionPreflight,
@@ -51,6 +56,7 @@ import {
5156
} from './request-binding.ts';
5257
import {
5358
beginOpenDeviceWait,
59+
findSessionHoldingDevice,
5460
readOpenWaitBudgetMs,
5561
} from '../sessions/open-device-contention-wait.ts';
5662
import {
@@ -336,6 +342,7 @@ export async function createRequestExecutionScope(params: {
336342
platformRequestScope: params.platformRequestScope,
337343
daemonPolicy: params.daemonPolicy,
338344
claimRecoveryGateway: params.claimRecoveryGateway,
345+
sessionStore,
339346
});
340347

341348
let bindingCleanup: Promise<void> | undefined;
@@ -567,13 +574,15 @@ function createRequestDeviceAccess(params: {
567574
platformRequestScope: PlatformRequestScope;
568575
daemonPolicy: DaemonPolicy | undefined;
569576
claimRecoveryGateway: ClaimRecoveryGatewayFactory;
577+
sessionStore: SessionStore;
570578
}): {
571579
claimAdmission: DeviceClaimAdmission;
572580
runtimeBindings: RequestRuntimeBindings;
573581
} {
574582
const { deviceRuntimeGateway, platformRequestScope, daemonPolicy } = params;
583+
const claimPolicy = resolveCommandDeviceClaimPolicy(params.command);
575584
const claimAdmission = createDeviceClaimAdmission({
576-
policy: resolveCommandDeviceClaimPolicy(params.command),
585+
policy: claimPolicy,
577586
command: params.command,
578587
session: params.sessionName,
579588
workspace: params.workspace,
@@ -598,9 +607,31 @@ function createRequestDeviceAccess(params: {
598607
scope: platformRequestScope,
599608
dispatchLedger: params.dispatchLedger,
600609
admitDeviceClaim: claimAdmission.admit,
601-
admitDevice: daemonPolicy
602-
? (device) => assertDaemonPolicyAdmitsDevice(daemonPolicy, device)
603-
: undefined,
610+
admitDevice:
611+
daemonPolicy || claimPolicy === 'require-owner'
612+
? (device) => {
613+
if (daemonPolicy) {
614+
assertDaemonPolicyAdmitsDevice(daemonPolicy, device);
615+
}
616+
if (claimPolicy === 'require-owner' && !params.sessionStore.get(params.sessionName)) {
617+
const inUse = findSessionHoldingDevice(
618+
params.sessionStore,
619+
device.id,
620+
params.sessionName,
621+
);
622+
if (inUse) {
623+
const refusal = isImplicitSessionScopeConflict(params.req, inUse.session)
624+
? buildForeignWorkspaceSessionConflict(inUse, device)
625+
: buildDeviceInUseBySessionError(inUse, device);
626+
throw new AppError(
627+
refusal.error.code,
628+
refusal.error.message,
629+
refusal.error.details,
630+
);
631+
}
632+
}
633+
}
634+
: undefined,
604635
}),
605636
};
606637
}

‎packages/daemon/src/sessions/open-device-contention-wait.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ export function beginOpenDeviceWait(params: {
119119

120120
/** The other session holding `deviceId`, or `undefined` when nothing stands between this open and
121121
* the device — including when this open's own session is what holds it. */
122-
function findSessionHoldingDevice(
122+
export function findSessionHoldingDevice(
123123
sessionStore: SessionStore,
124124
deviceId: string,
125125
sessionName: string,

0 commit comments

Comments
 (0)