diff --git a/.fallowrc.json b/.fallowrc.json index c1d92c5396..56dcdb5e17 100644 --- a/.fallowrc.json +++ b/.fallowrc.json @@ -156,6 +156,11 @@ "file": "packages/provider-*/src/index.ts", "exports": ["default"] }, + { + // Test runners that drive Revyl's own API beside the plugin (e2e's video recording) find a lease's session by this id; the repository has no consumer of it. + "file": "packages/provider-revyl/src/index.ts", + "exports": ["revylSessionIdForLease"] + }, { // The version 1 entry a provider package's `agentDevicePlugin.entry` names; hosts without the version 2 contract import the built file and read `default`. "file": "packages/provider-*/src/plugin.ts", diff --git a/packages/provider-revyl/src/deployment.test.ts b/packages/provider-revyl/src/deployment.test.ts index 98fcc55ca6..09bfd95f46 100644 --- a/packages/provider-revyl/src/deployment.test.ts +++ b/packages/provider-revyl/src/deployment.test.ts @@ -10,7 +10,7 @@ import { type RevylFixtureBackend, } from './revyl-backend.fixtures.ts'; import { deployRevylApp } from './deployment.ts'; -import { revylSessionIdForLease } from './session-identity.ts'; +import { revylSessionIdForLease } from './device.ts'; const openBackends: RevylFixtureBackend[] = []; diff --git a/packages/provider-revyl/src/device.test.ts b/packages/provider-revyl/src/device.test.ts index 86a066812c..dc08d8c9f9 100644 --- a/packages/provider-revyl/src/device.test.ts +++ b/packages/provider-revyl/src/device.test.ts @@ -7,6 +7,7 @@ import { isSupportedRevylRuntimeDevice, parseRevylDeviceId, platformForRevylLeaseBackend, + revylSessionIdForLease, } from './device.ts'; test('only the two instance backends name a Revyl platform', () => { @@ -101,3 +102,27 @@ test('only a device this module could have built is one it may act on', () => { assert.equal(isSupportedRevylRuntimeDevice(device as DeviceInfo), false, name); } }); + +/** Revyl's own UUID pattern for the `session_id` field. */ +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; + +test('one lease always derives the same session id', () => { + const first = revylSessionIdForLease('lease-1'); + assert.match(first, UUID, 'the field is declared as a UUID'); + assert.equal(revylSessionIdForLease('lease-1'), first); + // Recovery in another process works because the id depends on nothing but the lease. + assert.equal(revylSessionIdForLease('lease-1'), first); +}); + +test('two leases never derive one session id', () => { + const ids = new Set( + ['lease-1', 'lease-2', 'lease-9', 'revyl:ios:lease-1', ''].map((leaseId) => + revylSessionIdForLease(leaseId), + ), + ); + assert.equal(ids.size, 5); + assert.deepEqual( + [...ids].filter((id) => !UUID.test(id)), + [], + ); +}); diff --git a/packages/provider-revyl/src/device.ts b/packages/provider-revyl/src/device.ts index 2ea10fb67c..1fbf851793 100644 --- a/packages/provider-revyl/src/device.ts +++ b/packages/provider-revyl/src/device.ts @@ -1,3 +1,4 @@ +import { createHash } from 'node:crypto'; import type { DeviceLease } from '@agent-device/contracts/device'; import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -69,3 +70,33 @@ export function isSupportedRevylRuntimeDevice(device: DeviceInfo): boolean { device.kind === 'emulator' && device.iosPhysicalDeviceBackend === undefined; } + +/** Names this derivation, so a re-issue can change it without colliding with ids already issued. */ +const REVYL_SESSION_ID_NAMESPACE = 'agent-device:revyl:session:v1'; + +/** + * The session id one lease's device is started and stopped under. + * + * Revyl's `start_device` takes a caller-generated `session_id` and uses it as the session's canonical + * identity, which is what Revyl's own clients do for a hosted session. Deriving it from the lease id + * therefore gives the runtime a durable identity for one lease: an expired-lease recovery in a process + * that never started the device can name the session it has to stop. + * + * It is a UUID because that is the field's declared format, and it is a hash rather than the lease id + * itself because two daemons that rent for the same account must derive the same id for the same lease + * and never collide across providers. Revyl's UUID regex accepts lowercase hex with the version and + * variant bits set. + */ +export function revylSessionIdForLease(leaseId: string): string { + const digest = createHash('sha256') + .update(`${REVYL_SESSION_ID_NAMESPACE}:${leaseId}`) + .digest('hex'); + const hex = `${digest.slice(0, 32)}`; + return [ + hex.slice(0, 8), + hex.slice(8, 12), + `4${hex.slice(13, 16)}`, + `${((Number.parseInt(hex.slice(16, 17), 16) & 0x3) | 0x8).toString(16)}${hex.slice(17, 20)}`, + hex.slice(20, 32), + ].join('-'); +} diff --git a/packages/provider-revyl/src/index.ts b/packages/provider-revyl/src/index.ts index 6e14615904..19fb207cec 100644 --- a/packages/provider-revyl/src/index.ts +++ b/packages/provider-revyl/src/index.ts @@ -67,3 +67,4 @@ function revyl(options: RevylPluginOptions = {}): AgentDevicePlugin { } export { revyl as default }; +export { revylSessionIdForLease } from './device.ts'; diff --git a/packages/provider-revyl/src/interactor-settings.test.ts b/packages/provider-revyl/src/interactor-settings.test.ts index 35f8908003..ab03215964 100644 --- a/packages/provider-revyl/src/interactor-settings.test.ts +++ b/packages/provider-revyl/src/interactor-settings.test.ts @@ -86,8 +86,19 @@ test('appearance sets the named mode, and toggle flips the mode the worker repor ); }); -test('location sets the coordinates and refuses switching location services', async () => { +test('iOS refuses location on and off, which are the app grant there, and still sets coordinates', async () => { + const { fixture, interactor } = await liveInteractor('ios'); + await assert.rejects(interactor.setSetting('location', 'on'), refusedForMode); + await assert.rejects(interactor.setSetting('location', 'off'), refusedForMode); + await interactor.setSetting('location', 'set', undefined, { latitude: 43.65, longitude: -79.38 }); + + assert.deepEqual(fixture.bodyFor('set_location'), { latitude: 43.65, longitude: -79.38 }); + assert.equal(fixture.paths().filter((request) => request.endsWith('/set_location')).length, 1); +}); + +test('Android sets the coordinates, answers on as already on, and refuses switching it off', async () => { const { fixture, interactor } = await liveInteractor('android'); + assert.equal(await interactor.setSetting('location', 'on'), undefined); await interactor.setSetting('location', 'set', undefined, { latitude: 43.65, longitude: -79.38 }); await assert.rejects(interactor.setSetting('location', 'off'), refusedForMode); diff --git a/packages/provider-revyl/src/interactor.ts b/packages/provider-revyl/src/interactor.ts index 988c62c92f..c4cf42c890 100644 --- a/packages/provider-revyl/src/interactor.ts +++ b/packages/provider-revyl/src/interactor.ts @@ -464,15 +464,24 @@ class RevylInteractor implements Interactor { } /** - * `/set_location` moves the device's own coordinates. The worker has no action that switches - * location services, so `on` and `off` are refused rather than reported as applied. + * `/set_location` moves the device's own coordinates. On Android, `on` switches location services + * on, and Revyl starts every Android device with them on, so it is answered without a request. On + * iOS, `on|off` is the session app's location grant, which this does not set, so it is refused + * like Android's `off`. */ private async setLocation( state: string, options: SettingOptions | undefined, - ): Promise<{ latitude: number; longitude: number }> { + ): Promise<{ latitude: number; longitude: number } | void> { const latitude = options?.latitude; const longitude = options?.longitude; + if ( + state === 'on' && + this.session.platform === 'android' && + latitude === undefined && + longitude === undefined + ) + return; if (latitude === undefined || longitude === undefined) { throw unsupported( 'settings', diff --git a/packages/provider-revyl/src/platform-runtime.test.ts b/packages/provider-revyl/src/platform-runtime.test.ts index f48bc8365d..a9579389b2 100644 --- a/packages/provider-revyl/src/platform-runtime.test.ts +++ b/packages/provider-revyl/src/platform-runtime.test.ts @@ -98,6 +98,20 @@ test('a live session binds the interactor-backed operations and refuses the rest assert.equal(binding.operations.appLogInspect, undefined); }); +test('a live session binds settings and reaches the interactor with the setting and its state', async () => { + const calls: unknown[][] = []; + const interactor = { + setSetting: async (...args: unknown[]) => { + calls.push(args); + return { appearance: 'dark' }; + }, + } as unknown as Interactor; + const binding = await bind(owner({ hasLiveSession: true, interactor })); + assert.ok(binding.operations.setSetting); + await binding.operations.setSetting({ setting: 'appearance', state: 'dark' } as never); + assert.deepEqual(calls[0]?.slice(0, 2), ['appearance', 'dark']); +}); + test('a session that has ended reports the refused facts and binds no device action', async () => { const facts = await owner({ hasLiveSession: false }).inspectFacts(IOS_DEVICE); assert.equal(facts?.operations.captureSnapshot.available, false); diff --git a/packages/provider-revyl/src/revyl-session.ts b/packages/provider-revyl/src/revyl-session.ts index 2cd0590e12..c46a64d1b3 100644 --- a/packages/provider-revyl/src/revyl-session.ts +++ b/packages/provider-revyl/src/revyl-session.ts @@ -2,13 +2,13 @@ import { AppError } from '@agent-device/kernel/errors'; import { setTimeout as sleep } from 'node:timers/promises'; import type { DeviceLease } from '@agent-device/contracts/device'; import type { DeviceInfo } from '@agent-device/kernel/device'; -import { buildRevylDevice, type RevylPlatform } from './device.ts'; +import { buildRevylDevice, revylSessionIdForLease, type RevylPlatform } from './device.ts'; import { REVYL_START_DEVICE_TIMEOUT_MS, + isRevylSessionGone, revylFailureRefusedTheRequest, type RevylClient, } from './revyl-client.ts'; -import { revylSessionIdForLease } from './session-identity.ts'; import type { RevylStartDeviceRequest, RevylStartDeviceResponse, @@ -487,7 +487,8 @@ async function sleepBefore(deadline: RevylDeadline, signal?: AbortSignal): Promi * Refreshes a held session's idle clock on a timer, with a read that changes nothing on the device: * the worker counts a state read as device use and `health` as not. A failed refresh is not reported, * since the next one or any command refreshes the clock again; only a holder gone for the whole idle - * timeout loses the device. The timer never keeps the process alive. + * timeout loses the device. A session Revyl reports gone stops the timer, since no later read can + * refresh it. The timer never keeps the process alive. */ export function keepRevylSessionAlive(client: RevylClient, runId: string): () => void { let refreshing = false; @@ -496,7 +497,9 @@ export function keepRevylSessionAlive(client: RevylClient, runId: string): () => refreshing = true; void client .workerAction(runId, 'appearance') - .catch(() => undefined) + .catch((error: unknown) => { + if (isRevylSessionGone(error)) clearInterval(timer); + }) .finally(() => { refreshing = false; }); diff --git a/packages/provider-revyl/src/runtime-keep-alive.test.ts b/packages/provider-revyl/src/runtime-keep-alive.test.ts index ad57d6d574..18e0c34e62 100644 --- a/packages/provider-revyl/src/runtime-keep-alive.test.ts +++ b/packages/provider-revyl/src/runtime-keep-alive.test.ts @@ -44,6 +44,24 @@ test('a held session reads appearance on each keep-alive beat, and its release s assert.equal(fixture.paths().filter((path) => path === KEEP_ALIVE).length, 2); }); +test('a keep-alive read that finds the session gone stops the beat', async () => { + vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }); + const fixture = await startRevylFixtureBackend({ + respond: { [KEEP_ALIVE]: { status: 404, body: { detail: 'Session not found' } } }, + }); + openBackends.push(fixture); + const runtime = fixture.createRuntime(); + const lease = revylLease('android'); + await runtime.leaseLifecycle?.allocate?.(lease); + + vi.advanceTimersByTime(REVYL_KEEP_ALIVE_INTERVAL_MS); + await keepAlivesReach(fixture, 1); + await vi.waitFor(() => assert.equal(vi.getTimerCount(), 0)); + vi.advanceTimersByTime(REVYL_KEEP_ALIVE_INTERVAL_MS * 3); + assert.equal(fixture.paths().filter((path) => path === KEEP_ALIVE).length, 1); + await runtime.leaseLifecycle?.release?.(lease); +}); + test('a failed keep-alive read leaves the session held and the next beat reads again', async () => { vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }); const fixture = await startRevylFixtureBackend({ diff --git a/packages/provider-revyl/src/runtime-transient-reads.test.ts b/packages/provider-revyl/src/runtime-transient-reads.test.ts index 94eb2ab0a5..7e61d5c0d1 100644 --- a/packages/provider-revyl/src/runtime-transient-reads.test.ts +++ b/packages/provider-revyl/src/runtime-transient-reads.test.ts @@ -1,5 +1,6 @@ import assert from 'node:assert/strict'; import { afterEach, test } from 'vitest'; +import { AppError } from '@agent-device/kernel/errors'; import { revylLease, startRevylFixtureBackend, @@ -59,6 +60,10 @@ test('a lease start still fails on a worker-connection answer that is not a serv initialApp: 'https://apps.test/app.apk', flags: { device: 'Pixel 7' }, }), + (error: unknown) => + error instanceof AppError && + error.code === 'UNAUTHORIZED' && + error.details?.providerStatus === 403, ); assert.deepEqual( fixture.paths().filter((path) => path === CONNECTION), diff --git a/packages/provider-revyl/src/runtime.test.ts b/packages/provider-revyl/src/runtime.test.ts index cb0d90b334..bbde4e2de7 100644 --- a/packages/provider-revyl/src/runtime.test.ts +++ b/packages/provider-revyl/src/runtime.test.ts @@ -6,7 +6,7 @@ import { startRevylFixtureBackend, type RevylFixtureBackend, } from './revyl-backend.fixtures.ts'; -import { revylSessionIdForLease } from './session-identity.ts'; +import { revylSessionIdForLease } from './device.ts'; const openBackends: RevylFixtureBackend[] = []; diff --git a/packages/provider-revyl/src/runtime.ts b/packages/provider-revyl/src/runtime.ts index 0ad478fd6c..b154d1efdc 100644 --- a/packages/provider-revyl/src/runtime.ts +++ b/packages/provider-revyl/src/runtime.ts @@ -19,6 +19,7 @@ import { parseRevylDeviceId, platformForRevylLeaseBackend, REVYL_PROVIDER, + revylSessionIdForLease, type RevylPlatform, } from './device.ts'; import { createRevylClient, isRevylSessionGone, type RevylClient } from './revyl-client.ts'; @@ -42,7 +43,6 @@ import { import { createRevylInteractor } from './interactor.ts'; import { providerRuntimeOwner } from '@agent-device/contracts/platform-runtime'; import { resolveRevylRuntimeInstance } from './runtime-instance.ts'; -import { revylSessionIdForLease } from './session-identity.ts'; import type { RevylStartRequest } from './session-allocation.ts'; import type { RevylDeploymentSession } from './deployment.ts'; diff --git a/packages/provider-revyl/src/session-identity.test.ts b/packages/provider-revyl/src/session-identity.test.ts deleted file mode 100644 index a9cde7ca04..0000000000 --- a/packages/provider-revyl/src/session-identity.test.ts +++ /dev/null @@ -1,27 +0,0 @@ -import assert from 'node:assert/strict'; -import { test } from 'vitest'; -import { revylSessionIdForLease } from './session-identity.ts'; - -/** Revyl's own UUID pattern for the `session_id` field. */ -const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; - -test('one lease always derives the same session id', () => { - const first = revylSessionIdForLease('lease-1'); - assert.match(first, UUID, 'the field is declared as a UUID'); - assert.equal(revylSessionIdForLease('lease-1'), first); - // Recovery in another process works because the id depends on nothing but the lease. - assert.equal(revylSessionIdForLease('lease-1'), first); -}); - -test('two leases never derive one session id', () => { - const ids = new Set( - ['lease-1', 'lease-2', 'lease-9', 'revyl:ios:lease-1', ''].map((leaseId) => - revylSessionIdForLease(leaseId), - ), - ); - assert.equal(ids.size, 5); - assert.deepEqual( - [...ids].filter((id) => !UUID.test(id)), - [], - ); -}); diff --git a/packages/provider-revyl/src/session-identity.ts b/packages/provider-revyl/src/session-identity.ts deleted file mode 100644 index e02b25bed5..0000000000 --- a/packages/provider-revyl/src/session-identity.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { createHash } from 'node:crypto'; - -/** Names this derivation, so a re-issue can change it without colliding with ids already issued. */ -const REVYL_SESSION_ID_NAMESPACE = 'agent-device:revyl:session:v1'; - -/** - * The session id one lease's device is started and stopped under. - * - * Revyl's `start_device` takes a caller-generated `session_id` and uses it as the session's canonical - * identity, which is what Revyl's own clients do for a hosted session. Deriving it from the lease id - * therefore gives the runtime a durable identity for one lease: an expired-lease recovery in a process - * that never started the device can name the session it has to stop. - * - * It is a UUID because that is the field's declared format, and it is a hash rather than the lease id - * itself because two daemons that rent for the same account must derive the same id for the same lease - * and never collide across providers. Revyl's UUID regex accepts lowercase hex with the version and - * variant bits set. - */ -export function revylSessionIdForLease(leaseId: string): string { - const digest = createHash('sha256') - .update(`${REVYL_SESSION_ID_NAMESPACE}:${leaseId}`) - .digest('hex'); - const hex = `${digest.slice(0, 32)}`; - return [ - hex.slice(0, 8), - hex.slice(8, 12), - `4${hex.slice(13, 16)}`, - `${((Number.parseInt(hex.slice(16, 17), 16) & 0x3) | 0x8).toString(16)}${hex.slice(17, 20)}`, - hex.slice(20, 32), - ].join('-'); -} diff --git a/website/docs/docs/revyl.md b/website/docs/docs/revyl.md index 1f16059940..1a57c61f22 100644 --- a/website/docs/docs/revyl.md +++ b/website/docs/docs/revyl.md @@ -97,14 +97,17 @@ A Revyl session runs the commands that reach a device through Revyl's device act bundle identifier or package name, `open` with a deep link or URL, and `close` for the app the session opened. - `home`, and `back` on Android. iOS has no system back button; click the app's own back control. -- `orientation`. An Android emulator rotates to all four sides. An iOS simulator rotates to - `portrait` and `landscape-left` only, and refuses the other two. Neither releases the rotation lock, +- `orientation`. A worker that reports precise orientation, as Revyl's Android emulators do, rotates + to all four sides. Any other worker, such as an iOS simulator, rotates to `portrait` and + `landscape-left` only, and refuses the other two. Neither releases the rotation lock, so `orientation auto` refuses. - `settings appearance` (`light`, `dark`, or `toggle`), `settings location set `, `settings permission`, and `settings clear-app-state`. On iOS, `settings reset-keychain` also - works. `settings location on|off` refuses, because Revyl moves the device's coordinates but cannot - switch location services. `settings permission` refuses `location-always`, `contacts-limited`, and - `--mode limited`. Revyl's iOS simulators refuse `camera` and `notifications`. + works. Revyl starts every Android device with location services on, so `settings location on` + succeeds there without changing anything, and `settings location off` refuses, because Revyl + cannot switch location services off. On iOS, `settings location on|off` refuses; grant the app + location with `settings permission grant location`. `settings permission` refuses + `location-always`, `contacts-limited`, and `--mode limited`. Revyl's iOS simulators refuse `camera` and `notifications`. The plugin refuses every other command with a reason that names the substitute. It does not report a refused command as a success: