From 4af00afc4d5421213cae0bfd5f9dd3439effe928 Mon Sep 17 00:00:00 2001 From: finalerock44 Date: Mon, 16 Nov 2026 18:29:58 +0000 Subject: [PATCH 1/2] feat(device): open a link, set the location, and a wait on tap Three additions to `dcd device`, for the device session API's new actions. `dcd device open-link [id] ` opens a link on the device as tapping it would: a deep link into an app, or a web link in the app that claims it or the browser. `--sensitive` keeps a link that carries a token out of the timeline and out of what the command prints. `dcd device set-location [id] --latitude --longitude ` sets the device's GPS position in decimal degrees. South and west are negative. `dcd device tap --text|--rid ... --timeout ` says how long to wait for the element before the tap fails (0 to 60; 0 looks once). Without it the device waits 17 seconds, as before. A lone positional with a colon is the link, not a session id, as a lone key is for `press-key`. Usage errors answer inside the --json envelope and call nothing. --- src/commands/device.ts | 112 +++++++++++++++++- src/gateways/device-gateway.ts | 2 +- src/types/domain/device-session.types.ts | 15 ++- test/unit/device-command.test.ts | 141 +++++++++++++++++++++++ 4 files changed, 265 insertions(+), 5 deletions(-) diff --git a/src/commands/device.ts b/src/commands/device.ts index db11dfb..eb7c2c4 100644 --- a/src/commands/device.ts +++ b/src/commands/device.ts @@ -738,6 +738,38 @@ function percentArg(value: unknown, flag: string): number { return n; } +/** The longest a tap may wait for its target, as the API allows. */ +const MAX_TAP_TIMEOUT_SECONDS = 60; + +/** Seconds from a flag value, from 0 to `max`, or a usage error. Undefined when the flag was not given. */ +function secondsArg(value: unknown, flag: string, max: number): number | undefined { + if (value === undefined) return undefined; + const n = typeof value === 'number' ? value : Number(value); + if (typeof value === 'boolean' || value === '' || !Number.isFinite(n) || n < 0 || n > max) { + throw new CliError(`--${flag} must be a number of seconds from 0 to ${max}.`, 1); + } + return n; +} + +/** Decimal degrees from a flag value, within `limit` either way, or a usage error. */ +function degreesArg(value: unknown, flag: string, limit: number): number { + const n = typeof value === 'number' ? value : Number(value); + if ( + value === undefined || + typeof value === 'boolean' || + (typeof value === 'string' && value.trim() === '') || + !Number.isFinite(n) || + n < -limit || + n > limit + ) { + throw new CliError(`--${flag} must be a number from -${limit} to ${limit} (decimal degrees).`, 1); + } + return n; +} + +/** A link with a scheme and nothing a shell or a URL would split on. A session id has no colon. */ +const LINK = /^[A-Za-z][A-Za-z0-9+.-]*:\S+$/; + /** "x,y" (percentages) from a flag value, or a usage error. */ function pointArg(value: unknown, flag: string): DevicePoint { const parts = typeof value === 'string' ? value.split(',') : []; @@ -782,6 +814,10 @@ const tapSub = defineCommand({ rid: { type: 'string', description: 'The element\'s resource id (rid in `dcd device inspect`)' }, x: { type: 'string', description: 'With --y: a point, as percentages of the screen (0-100)' }, y: { type: 'string', description: 'See --x' }, + timeout: { + type: 'string', + description: `With --text or --rid: seconds to wait for it to appear before failing (0-${MAX_TAP_TIMEOUT_SECONDS}, default 17; 0 looks once)`, + }, maestro: maestroArg, }, async run({ args }) { @@ -795,11 +831,16 @@ const tapSub = defineCommand({ if (targets !== 1) { throw new CliError('tap takes exactly one target: --text, --rid, or --x and --y.', 1); } + const timeoutSeconds = secondsArg(args.timeout, 'timeout', MAX_TAP_TIMEOUT_SECONDS); + if (timeoutSeconds !== undefined && args.text === undefined && args.rid === undefined) { + throw new CliError('tap --timeout goes with --text or --rid: a point has nothing to wait for.', 1); + } + const wait = timeoutSeconds === undefined ? {} : { timeoutSeconds }; const body: DeviceActionRequest = args.text !== undefined - ? { type: 'tap', text: String(args.text) } + ? { type: 'tap', text: String(args.text), ...wait } : args.rid !== undefined - ? { type: 'tap', id: String(args.rid) } + ? { type: 'tap', id: String(args.rid), ...wait } : { type: 'tap', x: percentArg(args.x, 'x'), y: percentArg(args.y, 'y') }; const what = args.text !== undefined @@ -914,6 +955,71 @@ const pressKeySub = defineCommand({ }, }); +const openLinkSub = defineCommand({ + meta: { name: 'open-link', description: 'Open a link on the device: a deep link into an app, or a web link' }, + args: { + ...commonArgs, + id: idArg, + // Not `required`, as with `type --text`: a missing link fails inside the envelope. + url: { + type: 'positional', + required: false, + description: 'The link with its scheme, e.g. myapp://path or https://example.com', + }, + sensitive: { + type: 'boolean', + default: false, + description: 'The link is a secret (it carries a token): stored encrypted, never shown', + }, + }, + async run({ args }) { + const json = Boolean(args.json); + await runDeviceCommand(json, async () => { + let id = args.id as string | undefined; + let url = args.url as string | undefined; + // `dcd device open-link myapp://path`: the one positional is the link, not a session. + if (id && !url && id.includes(':')) [id, url] = [undefined, id]; + if (!url || !LINK.test(url)) { + throw new CliError( + 'open-link takes a link with its scheme and no spaces, e.g. myapp://path or https://example.com.', + 1, + ); + } + const shown = args.sensitive ? 'a link' : url; + return performAction( + args, + id, + { type: 'open_link', url, ...(args.sensitive ? { sensitive: true } : {}) }, + { done: `Opened ${shown}`, failed: `Opening ${shown} failed` }, + ); + }); + }, +}); + +const setLocationSub = defineCommand({ + meta: { name: 'set-location', description: "Set the device's GPS position, in decimal degrees" }, + args: { + ...commonArgs, + id: idArg, + latitude: { type: 'string', description: 'Decimal degrees, north positive (-90 to 90)' }, + longitude: { type: 'string', description: 'Decimal degrees, east positive (-180 to 180)' }, + }, + async run({ args }) { + const json = Boolean(args.json); + await runDeviceCommand(json, async () => { + // South and west are negative. citty keeps a value that is a number, minus sign and all. + const latitude = degreesArg(args.latitude, 'latitude', 90); + const longitude = degreesArg(args.longitude, 'longitude', 180); + return performAction( + args, + args.id as string | undefined, + { type: 'set_location', latitude, longitude }, + { done: `Location set to ${latitude}, ${longitude}`, failed: 'Setting the location failed' }, + ); + }); + }, +}); + const modelsSub = defineCommand({ meta: { name: 'models', description: 'The devices a session can ask for' }, args: { @@ -1553,6 +1659,8 @@ export const deviceCommand = defineCommand({ type: typeSub, swipe: swipeSub, 'press-key': pressKeySub, + 'open-link': openLinkSub, + 'set-location': setLocationSub, models: modelsSub, inspect: inspectSub, screenshot: screenshotSub, diff --git a/src/gateways/device-gateway.ts b/src/gateways/device-gateway.ts index bd99951..4c044c2 100644 --- a/src/gateways/device-gateway.ts +++ b/src/gateways/device-gateway.ts @@ -278,7 +278,7 @@ export const DeviceGateway = { return request(baseUrl, auth, 'POST', `${sessionPath(id)}/request-human`, { reason }); }, - /** One typed action: tap, type, swipe or press_key. Synchronous: answers with the outcome. */ + /** One typed action: tap, type, swipe, press_key, open_link or set_location. Synchronous: answers with the outcome. */ action( baseUrl: string, auth: AuthContext, diff --git a/src/types/domain/device-session.types.ts b/src/types/domain/device-session.types.ts index 774b978..8f65875 100644 --- a/src/types/domain/device-session.types.ts +++ b/src/types/domain/device-session.types.ts @@ -130,7 +130,16 @@ export interface DevicePoint { * no longer sends it. */ export type DeviceActionRequest = - | { id?: string; mode?: 'maestro'; text?: string; type: 'tap'; x?: number; y?: number } + | { + id?: string; + mode?: 'maestro'; + text?: string; + /** With `text` or `id`: seconds to wait for it to appear (0 to 60; 0 looks once). */ + timeoutSeconds?: number; + type: 'tap'; + x?: number; + y?: number; + } | { key: string; mode?: 'maestro'; type: 'press_key' } | { mode?: 'maestro'; sensitive?: boolean; text: string; type: 'type' } | { @@ -139,7 +148,9 @@ export type DeviceActionRequest = mode?: 'maestro'; to?: DevicePoint; type: 'swipe'; - }; + } + | { sensitive?: boolean; type: 'open_link'; url: string } + | { latitude: number; longitude: number; type: 'set_location' }; /** The keys press_key takes, as the API names them. */ export const DEVICE_KEYS = [ diff --git a/test/unit/device-command.test.ts b/test/unit/device-command.test.ts index cf2529c..6287add 100644 --- a/test/unit/device-command.test.ts +++ b/test/unit/device-command.test.ts @@ -151,6 +151,36 @@ async function runText(name: string, args: Record): Promise` through citty's own parser with --json, capturing + * the envelope and the exit code: for what the parser does to a value before + * a subcommand sees it. + */ +async function runArgv(rawArgs: string[]): Promise<{ exit: number; out: Record }> { + let out = ''; + const write = process.stdout.write.bind(process.stdout); + const exit = process.exit; + process.stdout.write = ((chunk: string) => { + out += chunk; + return true; + }) as typeof process.stdout.write; + process.exit = ((code?: number) => { + throw new ExitError(code ?? 0); + }) as typeof process.exit; + let code = 0; + try { + await runCommand(deviceCommand, { rawArgs: [...rawArgs, '--json', '--api-url', API, '--api-key', 'k'] }); + } catch (error) { + if (!(error instanceof ExitError)) throw error; + code = error.code; + } finally { + process.stdout.write = write; + process.exit = exit; + } + + return { exit: code, out: JSON.parse(out) as Record }; +} + describe('dcd device', () => { const realFetch = globalThis.fetch; const ORIGINAL_ENV = { ...process.env }; @@ -384,6 +414,117 @@ describe('dcd device', () => { expect(exit).to.equal(DEVICE_EXIT.usage); }); + it('tap --timeout rides on a tap by text or id, in seconds', async () => { + const calls = stubFetch(ok); + await runJson('tap', { id: 'a-b-c', rid: 'login_button', timeout: '2.5' }); + await runJson('tap', { id: 'a-b-c', text: 'Log in', timeout: '0' }); + expect(calls.map((c) => c.body)).to.deep.equal([ + { type: 'tap', id: 'login_button', timeoutSeconds: 2.5 }, + // 0 is a wait of its own: look once. + { type: 'tap', text: 'Log in', timeoutSeconds: 0 }, + ]); + }); + + it('tap --timeout is refused with a point, out of range or not a number, without calling the API', async () => { + const calls = stubFetch(ok); + for (const args of [ + { id: 'a-b-c', x: '50', y: '50', timeout: '2' }, + { id: 'a-b-c', text: 'x', timeout: '61' }, + { id: 'a-b-c', text: 'x', timeout: '-1' }, + { id: 'a-b-c', text: 'x', timeout: 'soon' }, + { id: 'a-b-c', text: 'x', timeout: '' }, + ]) { + const { exit, out } = await runJson('tap', args); + expect(exit, JSON.stringify(args)).to.equal(DEVICE_EXIT.usage); + expect(out.ok).to.equal(false); + } + expect(calls).to.have.length(0); + }); + + it('open-link takes the link as its only positional when the session is implied', async () => { + const calls = stubFetch((call) => + call.url.endsWith('/device/sessions') ? { body: { sessions: [session('a-b-c')] } } : ok(), + ); + await runJson('open-link', { id: 'myapp://sign-in?user=a' }); + await runJson('open-link', { id: 'a-b-c', url: 'https://example.com/page?a=1&b=2' }); + await runJson('open-link', { id: 'a-b-c', url: 'myapp://sign-in?token=abc', sensitive: true }); + const posts = calls.filter((c) => c.method === 'POST'); + expect(posts.map((c) => [c.url, c.body])).to.deep.equal([ + [`${API}/device/sessions/a-b-c/actions`, { type: 'open_link', url: 'myapp://sign-in?user=a' }], + [`${API}/device/sessions/a-b-c/actions`, { type: 'open_link', url: 'https://example.com/page?a=1&b=2' }], + [ + `${API}/device/sessions/a-b-c/actions`, + { type: 'open_link', url: 'myapp://sign-in?token=abc', sensitive: true }, + ], + ]); + }); + + it('open-link refuses no link, no scheme and a space, without calling the API', async () => { + const calls = stubFetch(ok); + for (const args of [ + { id: 'a-b-c' }, + { id: 'a-b-c', url: 'example.com/page' }, + { id: 'a-b-c', url: 'myapp://a b' }, + { id: 'a-b-c', url: ':nothing' }, + ]) { + const { exit, out } = await runJson('open-link', args); + expect(exit, JSON.stringify(args)).to.equal(DEVICE_EXIT.usage); + expect(out.ok).to.equal(false); + } + expect(calls).to.have.length(0); + }); + + it('open-link --sensitive does not print the link', async () => { + stubFetch(ok); + const shown = await runText('open-link', { id: 'a-b-c', url: 'myapp://sign-in?user=a' }); + expect(shown).to.contain('myapp://sign-in?user=a'); + const hidden = await runText('open-link', { + id: 'a-b-c', + url: 'myapp://sign-in?token=hunter2', + sensitive: true, + }); + expect(hidden).to.contain('Opened a link'); + expect(hidden).to.not.contain('hunter2'); + }); + + it('set-location sends decimal degrees, south and west as negative numbers', async () => { + const calls = stubFetch((call) => + call.url.endsWith('/device/sessions') ? { body: { sessions: [session('a-b-c')] } } : ok(), + ); + await runJson('set-location', { id: 'a-b-c', latitude: '51.5074', longitude: '-0.1278' }); + // Through citty's own parser too: a value that starts with `-` must arrive as the number it is. + const south = await runArgv(['set-location', 'a-b-c', '--latitude', '-33.86882', '--longitude', '151.2093']); + expect(south.exit).to.equal(0); + const west = await runArgv(['set-location', '--latitude=40.7128', '--longitude', '-74.006']); + expect(west.exit).to.equal(0); + const nearZero = await runArgv(['set-location', '--latitude', '-0.5', '--longitude', '-0.1278']); + expect(nearZero.exit).to.equal(0); + const posts = calls.filter((c) => c.method === 'POST'); + expect(posts.map((c) => [c.url, c.body])).to.deep.equal([ + [`${API}/device/sessions/a-b-c/actions`, { type: 'set_location', latitude: 51.5074, longitude: -0.1278 }], + [`${API}/device/sessions/a-b-c/actions`, { type: 'set_location', latitude: -33.86882, longitude: 151.2093 }], + [`${API}/device/sessions/a-b-c/actions`, { type: 'set_location', latitude: 40.7128, longitude: -74.006 }], + [`${API}/device/sessions/a-b-c/actions`, { type: 'set_location', latitude: -0.5, longitude: -0.1278 }], + ]); + }); + + it('set-location refuses a missing, out-of-range or non-numeric coordinate, without calling the API', async () => { + const calls = stubFetch(ok); + for (const args of [ + { id: 'a-b-c' }, + { id: 'a-b-c', latitude: '51.5' }, + { id: 'a-b-c', latitude: '90.1', longitude: '0' }, + { id: 'a-b-c', latitude: '0', longitude: '-180.5' }, + { id: 'a-b-c', latitude: 'north', longitude: '0' }, + { id: 'a-b-c', latitude: '', longitude: '0' }, + ]) { + const { exit, out } = await runJson('set-location', args); + expect(exit, JSON.stringify(args)).to.equal(DEVICE_EXIT.usage); + expect(out.ok).to.equal(false); + } + expect(calls).to.have.length(0); + }); + it('exits 2 with the result when the device could not do the action', async () => { stubFetch(() => ({ body: { result: { success: false, error: 'Element not found: "Nope"' }, session: session('a-b-c') }, From e96f15a7c9283dd3cca603b76e9a8fe44e26e071 Mon Sep 17 00:00:00 2001 From: finalerock44 Date: Tue, 17 Nov 2026 11:52:18 +0000 Subject: [PATCH 2/2] fix(telemetry): keep an open-link link and typed text out of telemetry Telemetry records the argv of every command, with the values of a few flags redacted by name. `dcd device open-link` takes its link as a positional, which no flag name marks, so a link sent with `--sensitive` was kept out of the terminal and the session's timeline and still sent to telemetry in full, token included. `scrubArgv` now redacts everything after `device open-link` that is not a flag, and the value of any flag there but the API URL: with or without `--sensitive`, since a sign-in link is a credential whether or not the caller marked it. The session id goes with it, and a link too malformed to send is not kept either. The subcommand is found by name anywhere after `device`, so a flag's value in between cannot hide it. `dcd device type --text` had the same hole: `--text` was never in the list, so a typed password or code went to telemetry even with `--sensitive`. It is redacted for `device type`; `device tap --text`, an element's label, is kept. --- src/services/telemetry.service.ts | 41 ++++++++- test/unit/telemetry-scrub-argv.test.ts | 121 +++++++++++++++++++++++++ 2 files changed, 158 insertions(+), 4 deletions(-) create mode 100644 test/unit/telemetry-scrub-argv.test.ts diff --git a/src/services/telemetry.service.ts b/src/services/telemetry.service.ts index 8bb51ea..2726533 100644 --- a/src/services/telemetry.service.ts +++ b/src/services/telemetry.service.ts @@ -345,22 +345,55 @@ const SENSITIVE_FLAG_NAMES = new Set([ '--env', ]); -function scrubArgv(args: string[]): string[] { +const REDACTED = ''; + +/** + * The argv a command was run with, as telemetry may keep it: without the + * values of the flags above, and without what two `dcd device` subcommands + * are given that no flag name marks as a secret. + * + * - `device open-link` takes its link as a positional. A sign-in link is a + * credential, and `--sensitive` promises it is never shown, so everything + * after `open-link` that is not a flag is taken for the link, and the value + * of any flag but the API URL goes too. That costs the session id, and + * keeps a link too malformed to send from being kept either. + * - `device type` takes `--text`, which is a password or a code as often as + * not. `device tap` has a `--text` as well, an element's label, and keeps it. + * + * The subcommand is found by its name anywhere after `device`, not as the + * first positional: a flag's value in between must not hide it. + */ +export function scrubArgv(args: string[]): string[] { + const device = args.indexOf('device'); + const subcommand = (name: string) => (device === -1 ? -1 : args.indexOf(name, device + 1)); + const openLink = subcommand('open-link'); + const type = subcommand('type'); + const keeps = (flag: string) => API_URL_FLAGS.includes(flag); + const scrubbed: string[] = []; for (let i = 0; i < args.length; i++) { const arg = args[i]; + const isFlag = arg.startsWith('-'); const eqIndex = arg.indexOf('='); const flagName = eqIndex === -1 ? arg : arg.slice(0, eqIndex); - if (arg.startsWith('-') && SENSITIVE_FLAG_NAMES.has(flagName)) { + const afterOpenLink = openLink !== -1 && i > openLink; + const secretFlag = + SENSITIVE_FLAG_NAMES.has(flagName) || + (type !== -1 && i > type && flagName === '--text') || + // `--anything=value` after open-link: no flag of the command needs its value kept. + (afterOpenLink && eqIndex !== -1 && !keeps(flagName)); + if (isFlag && secretFlag) { if (eqIndex === -1) { scrubbed.push(arg); if (i + 1 < args.length) { - scrubbed.push(''); + scrubbed.push(REDACTED); i++; } } else { - scrubbed.push(`${flagName}=`); + scrubbed.push(`${flagName}=${REDACTED}`); } + } else if (afterOpenLink && !isFlag) { + scrubbed.push(keeps(args[i - 1]) ? arg : REDACTED); } else { scrubbed.push(arg); } diff --git a/test/unit/telemetry-scrub-argv.test.ts b/test/unit/telemetry-scrub-argv.test.ts new file mode 100644 index 0000000..972987b --- /dev/null +++ b/test/unit/telemetry-scrub-argv.test.ts @@ -0,0 +1,121 @@ +import { expect } from 'chai'; + +import { scrubArgv } from '../../src/services/telemetry.service.js'; + +/** + * Telemetry keeps the argv of every command. What a caller gives a command + * as a secret must not be in it: the link of `device open-link`, which is a + * positional and so has no flag name to go by, and the text of `device type`. + */ +describe('telemetry: scrubArgv', () => { + const R = ''; + + it('redacts the link of device open-link, with or without --sensitive, wherever it sits', () => { + expect(scrubArgv(['device', 'open-link', 'myapp://sign-in?token=SECRET', '--sensitive'])).to.deep.equal([ + 'device', + 'open-link', + R, + '--sensitive', + ]); + expect(scrubArgv(['device', 'open-link', '--sensitive', '--json', 'myapp://sign-in?token=SECRET'])).to.deep.equal([ + 'device', + 'open-link', + '--sensitive', + '--json', + R, + ]); + // No flag: the link is the caller's all the same, and may carry a token they did not think to mark. + expect(scrubArgv(['device', 'open-link', 'https://example.com/reset?token=SECRET'])).to.deep.equal([ + 'device', + 'open-link', + R, + ]); + }); + + it('redacts a link too malformed to send, and the session id with it', () => { + expect(scrubArgv(['device', 'open-link', 'brave-teal-otter', 'example.com/reset?token=SECRET'])).to.deep.equal([ + 'device', + 'open-link', + R, + R, + ]); + }); + + it('finds open-link behind a flag and its value, and keeps only the API URL of what follows', () => { + const scrubbed = scrubArgv([ + '--api-url', + 'https://dev-api.devicecloud.dev', + 'device', + '--api-key', + 'dcd_SECRETKEY', + 'open-link', + 'myapp://x?token=SECRET', + '--api-url', + 'https://dev-api.devicecloud.dev', + '--url=myapp://y?token=SECRET', + '--other', + 'myapp://z?token=SECRET', + ]); + expect(scrubbed).to.deep.equal([ + '--api-url', + 'https://dev-api.devicecloud.dev', + 'device', + '--api-key', + R, + 'open-link', + R, + '--api-url', + 'https://dev-api.devicecloud.dev', + `--url=${R}`, + '--other', + R, + ]); + expect(JSON.stringify(scrubbed)).to.not.contain('SECRET'); + }); + + it('redacts the text of device type, in both spellings, and keeps the label of a tap', () => { + expect(scrubArgv(['device', 'type', '--text', 'hunter2', '--sensitive'])).to.deep.equal([ + 'device', + 'type', + '--text', + R, + '--sensitive', + ]); + expect(scrubArgv(['device', 'type', 'brave-teal-otter', '--text=hunter2'])).to.deep.equal([ + 'device', + 'type', + 'brave-teal-otter', + `--text=${R}`, + ]); + expect(scrubArgv(['device', 'tap', '--text', 'Log in', '--timeout', '2'])).to.deep.equal([ + 'device', + 'tap', + '--text', + 'Log in', + '--timeout', + '2', + ]); + }); + + it('still redacts the flags it always did, and leaves other commands alone', () => { + expect(scrubArgv(['cloud', '--api-key', 'dcd_SECRETKEY', '-e', 'PASSWORD=hunter2', '--env=TOKEN=abc', 'flows/'])).to.deep.equal([ + 'cloud', + '--api-key', + R, + '-e', + R, + `--env=${R}`, + 'flows/', + ]); + expect(scrubArgv(['device', 'set-location', '--latitude', '51.5074', '--longitude', '-0.1278'])).to.deep.equal([ + 'device', + 'set-location', + '--latitude', + '51.5074', + '--longitude', + '-0.1278', + ]); + // A link is only a link after `device open-link`. + expect(scrubArgv(['upload', 'open-link', 'app.apk'])).to.deep.equal(['upload', 'open-link', 'app.apk']); + }); +});