@devicecloud.dev/dcd 5.14.0 → 5.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +4 -2
  2. package/dist/commands/artifacts.d.ts +13 -0
  3. package/dist/commands/artifacts.js +43 -5
  4. package/dist/commands/cloud.d.ts +1 -1
  5. package/dist/commands/cloud.js +2 -2
  6. package/dist/commands/device.d.ts +39 -0
  7. package/dist/commands/device.js +479 -101
  8. package/dist/commands/live.js +1 -1
  9. package/dist/config/flags/device.flags.d.ts +1 -1
  10. package/dist/config/flags/device.flags.js +1 -1
  11. package/dist/constants.d.ts +1 -1
  12. package/dist/gateways/api-gateway.d.ts +25 -3
  13. package/dist/gateways/api-gateway.js +68 -6
  14. package/dist/gateways/device-gateway.d.ts +34 -10
  15. package/dist/gateways/device-gateway.js +72 -17
  16. package/dist/mcp/bridge.d.ts +30 -16
  17. package/dist/mcp/bridge.js +201 -64
  18. package/dist/mcp/local-files.d.ts +14 -0
  19. package/dist/mcp/local-files.js +75 -0
  20. package/dist/mcp/tools/download-artifacts.d.ts +4 -1
  21. package/dist/mcp/tools/download-artifacts.js +44 -17
  22. package/dist/services/report-download.service.d.ts +32 -0
  23. package/dist/services/report-download.service.js +51 -2
  24. package/dist/services/telemetry.service.d.ts +20 -1
  25. package/dist/services/telemetry.service.js +27 -6
  26. package/dist/types/domain/device-session.types.d.ts +73 -3
  27. package/dist/types/domain/device-session.types.js +2 -0
  28. package/dist/utils/api-url.d.ts +20 -0
  29. package/dist/utils/api-url.js +49 -0
  30. package/dist/utils/app-upload.d.ts +6 -0
  31. package/dist/utils/app-upload.js +19 -0
  32. package/dist/utils/config-store.d.ts +5 -1
  33. package/dist/utils/config-store.js +18 -2
  34. package/dist/utils/device-artifacts.d.ts +5 -0
  35. package/dist/utils/device-artifacts.js +22 -0
  36. package/dist/utils/device-bundle.d.ts +39 -9
  37. package/dist/utils/device-bundle.js +153 -51
  38. package/dist/utils/device-flags.d.ts +17 -0
  39. package/dist/utils/device-flags.js +145 -0
  40. package/dist/utils/device-output.d.ts +53 -7
  41. package/dist/utils/device-output.js +148 -21
  42. package/dist/utils/device-run.d.ts +8 -3
  43. package/dist/utils/device-run.js +85 -8
  44. package/dist/utils/zip-integrity.d.ts +21 -0
  45. package/dist/utils/zip-integrity.js +45 -0
  46. package/package.json +3 -2
@@ -10,7 +10,34 @@ export interface DownloadOptions {
10
10
  export interface ArtifactsDownloadOptions extends DownloadOptions {
11
11
  artifactsPath?: string;
12
12
  downloadType: 'ALL' | 'FAILED';
13
+ /**
14
+ * Only this flow's artifacts, by its file path or name: resolved to one
15
+ * result with {@link matchFlowResult}. Leave unset with `resultId`.
16
+ */
17
+ flow?: string;
18
+ /**
19
+ * Only the artifacts of the flow run this result belongs to: its first
20
+ * attempt and every retry, on that one device.
21
+ */
22
+ resultId?: number;
23
+ }
24
+ /** A result row as the flow lookup needs it. */
25
+ export interface FlowResultRow {
26
+ config?: unknown;
27
+ id: number;
28
+ retry_of?: null | number;
29
+ simulator_name?: null | string;
30
+ test_file_name: string;
13
31
  }
32
+ /**
33
+ * The one run in an upload whose flow file matches `flow`: its full path as
34
+ * submitted (`flows/login.yaml`, with or without `./`), its file name
35
+ * (`login.yaml`) or its name without the extension (`login`). Only first
36
+ * attempts are candidates; the API adds the retries. Throws when nothing
37
+ * matches, or when several runs do (a device matrix runs one flow per
38
+ * device), listing the result ids to pick from with --result-id.
39
+ */
40
+ export declare function matchFlowResult(rows: FlowResultRow[], flow: string): number;
14
41
  export interface ReportDownloadOptions extends DownloadOptions {
15
42
  allurePath?: string;
16
43
  htmlPath?: string;
@@ -31,6 +58,11 @@ export interface DownloadResult {
31
58
  path: string;
32
59
  type: 'allure' | 'artifacts' | 'html' | 'junit';
33
60
  }
61
+ /**
62
+ * Whether every requested download succeeded. `dcd artifacts` exits 1 when
63
+ * not; `dcd cloud` only warns, so a download never changes a test-run exit.
64
+ */
65
+ export declare function downloadsSucceeded(downloads: DownloadResult[]): boolean;
34
66
  /**
35
67
  * Service for downloading test artifacts and reports
36
68
  */
@@ -1,6 +1,37 @@
1
1
  import * as path from 'node:path';
2
2
  import { ApiGateway } from '../gateways/api-gateway.js';
3
3
  import { refreshAuth } from '../utils/auth.js';
4
+ import { deviceFromResultRow } from './results-polling.service.js';
5
+ /** `./flows/login.yaml` -> `flows/login.yaml`, so the forms compare equal. */
6
+ const normaliseFlowPath = (p) => p.trim().replace(/^(\.\/)+/, '');
7
+ /**
8
+ * The one run in an upload whose flow file matches `flow`: its full path as
9
+ * submitted (`flows/login.yaml`, with or without `./`), its file name
10
+ * (`login.yaml`) or its name without the extension (`login`). Only first
11
+ * attempts are candidates; the API adds the retries. Throws when nothing
12
+ * matches, or when several runs do (a device matrix runs one flow per
13
+ * device), listing the result ids to pick from with --result-id.
14
+ */
15
+ export function matchFlowResult(rows, flow) {
16
+ const wanted = normaliseFlowPath(flow);
17
+ const roots = rows.filter((r) => r.retry_of === null || r.retry_of === undefined);
18
+ const matches = roots.filter((r) => {
19
+ const file = normaliseFlowPath(r.test_file_name);
20
+ const base = file.split('/').pop() ?? file;
21
+ return file === wanted || base === wanted || base.replace(/\.ya?ml$/i, '') === wanted;
22
+ });
23
+ if (matches.length === 1)
24
+ return matches[0].id;
25
+ if (matches.length === 0) {
26
+ throw new Error(`No flow matching '${flow}' in this upload`);
27
+ }
28
+ const candidates = matches.map((r) => {
29
+ const device = deviceFromResultRow(r);
30
+ const label = [device?.name, device?.osVersion].filter(Boolean).join(' ');
31
+ return `${r.id} (${r.test_file_name}${label ? `, ${label}` : ''})`;
32
+ });
33
+ throw new Error(`'${flow}' matches ${matches.length} results in this upload; pick one with --result-id: ${candidates.join(', ')}`);
34
+ }
4
35
  /**
5
36
  * The report formats retired on 7 December 2026, and what each one
6
37
  * does from that date. `dcd cloud` users are told by the API's submit message
@@ -20,6 +51,13 @@ export function reportFormatDeprecation(report) {
20
51
  }
21
52
  }
22
53
  }
54
+ /**
55
+ * Whether every requested download succeeded. `dcd artifacts` exits 1 when
56
+ * not; `dcd cloud` only warns, so a download never changes a test-run exit.
57
+ */
58
+ export function downloadsSucceeded(downloads) {
59
+ return downloads.length > 0 && downloads.every((d) => d.ok);
60
+ }
23
61
  /**
24
62
  * Service for downloading test artifacts and reports
25
63
  */
@@ -30,14 +68,25 @@ export class ReportDownloadService {
30
68
  * @returns What the download did
31
69
  */
32
70
  async downloadArtifacts(options) {
33
- const { apiUrl, auth, uploadId, downloadType, artifactsPath = './artifacts.zip', debug = false, logger, warnLogger, } = options;
71
+ const { apiUrl, auth, uploadId, downloadType, artifactsPath = './artifacts.zip', debug = false, flow, logger, warnLogger, } = options;
34
72
  try {
35
73
  if (debug && logger) {
36
74
  logger(`[DEBUG] Downloading artifacts: ${downloadType}`);
37
75
  }
38
76
  // `dcd cloud` downloads after polling, which can outlast a `dcd login`
39
77
  // token; a failed refresh lands in the warning below like any failure.
40
- await ApiGateway.downloadArtifactsZip(apiUrl, await refreshAuth(auth), uploadId, downloadType, artifactsPath);
78
+ const freshAuth = await refreshAuth(auth);
79
+ // A flow name becomes the result id the API filters on. A name that
80
+ // matches nothing, or several runs, lands in the warning below.
81
+ let { resultId } = options;
82
+ if (flow !== undefined) {
83
+ const { results } = (await ApiGateway.getResultsForUpload(apiUrl, freshAuth, uploadId));
84
+ resultId = matchFlowResult(results ?? [], flow);
85
+ if (debug && logger) {
86
+ logger(`[DEBUG] Flow '${flow}' is result ${resultId}`);
87
+ }
88
+ }
89
+ await ApiGateway.downloadArtifactsZip(apiUrl, freshAuth, uploadId, downloadType, artifactsPath, resultId);
41
90
  if (logger) {
42
91
  logger('\n');
43
92
  logger(`Test artifacts have been downloaded to ${artifactsPath}`);
@@ -13,7 +13,9 @@ export interface EncryptionTelemetry {
13
13
  * (a 501) is the expected answer from a deployment without bundle delivery;
14
14
  * the rest are failures worth counting.
15
15
  */
16
- export type BundleFallbackReason = 'bundle_http_error' | 'bundle_request_failed' | 'bundle_stream_failed' | 'manifest_http_error' | 'manifest_incomplete' | 'manifest_invalid_json' | 'manifest_request_failed' | 'manifest_unavailable';
16
+ export type BundleFallbackReason = 'bundle_http_error' | 'bundle_request_failed' | 'bundle_stream_failed'
17
+ /** The stream ended cleanly but the ZIP has no complete central directory. */
18
+ | 'bundle_truncated' | 'manifest_http_error' | 'manifest_incomplete' | 'manifest_invalid_json' | 'manifest_request_failed' | 'manifest_unavailable';
17
19
  export interface BundleFallbackTelemetry {
18
20
  /** Bytes of the ZIP received before the stream failed. */
19
21
  bytes_received?: number;
@@ -81,6 +83,16 @@ declare class Telemetry {
81
83
  * file), so without this the reason is lost.
82
84
  */
83
85
  recordBundleFallback(detail: BundleFallbackTelemetry): void;
86
+ /**
87
+ * Record an inline ZIP download that ended before its central directory.
88
+ * The user sees the failure; this keeps a count of how often it happens.
89
+ */
90
+ recordDownloadIncomplete(detail: {
91
+ bytes: number;
92
+ /** The inline route, e.g. `download` or `html-report`. */
93
+ route: string;
94
+ upload_id?: string;
95
+ }): void;
84
96
  recordCommandSuccess(): void;
85
97
  recordCommandFailure(opts: {
86
98
  error: Error | string;
@@ -99,6 +111,13 @@ declare class Telemetry {
99
111
  flushSync(): void;
100
112
  private buildMeta;
101
113
  }
114
+ /**
115
+ * Links in `text` without their query, fragment and user info. A signed
116
+ * download link's query is its credential (`?X-Amz-Signature=…`), and `dcd
117
+ * device start --app <url>` and `install <url>` take one as a plain value.
118
+ * Where the link points stays, for telling failures apart.
119
+ */
120
+ export declare function redactUrls(text: string): string;
102
121
  /**
103
122
  * The argv a command was run with, as telemetry may keep it: without the
104
123
  * values of the flags above, and without what two `dcd device` subcommands
@@ -17,6 +17,7 @@ import { randomUUID } from 'node:crypto';
17
17
  import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
18
18
  import { tmpdir } from 'node:os';
19
19
  import { join } from 'node:path';
20
+ import { checkApiUrl } from '../utils/api-url.js';
20
21
  import { getCliVersion, getInstallMethod } from '../utils/cli.js';
21
22
  const DEFAULT_API_URL = 'https://api.devicecloud.dev';
22
23
  class Telemetry {
@@ -73,7 +74,7 @@ class Telemetry {
73
74
  this.enqueue('error', 'cli.mcp', 'mcp tool failed', {
74
75
  tool,
75
76
  duration_ms: durationMs,
76
- error_message: error instanceof Error ? error.message : String(error),
77
+ error_message: redactUrls(error instanceof Error ? error.message : String(error)),
77
78
  error_name: error instanceof Error ? error.name : 'Error',
78
79
  ...extra,
79
80
  });
@@ -112,6 +113,13 @@ class Telemetry {
112
113
  recordBundleFallback(detail) {
113
114
  this.enqueue(detail.reason === 'manifest_unavailable' ? 'info' : 'warn', 'cli.download', 'bundle download fell back', { ...detail });
114
115
  }
116
+ /**
117
+ * Record an inline ZIP download that ended before its central directory.
118
+ * The user sees the failure; this keeps a count of how often it happens.
119
+ */
120
+ recordDownloadIncomplete(detail) {
121
+ this.enqueue('warn', 'cli.download', 'download incomplete', { ...detail });
122
+ }
115
123
  recordCommandSuccess() {
116
124
  this.enqueue('info', 'cli.lifecycle', 'command completed', {
117
125
  duration_ms: Date.now() - this.startedAt,
@@ -125,9 +133,10 @@ class Telemetry {
125
133
  this.enqueue('error', 'cli.lifecycle', 'command failed', {
126
134
  duration_ms: Date.now() - this.startedAt,
127
135
  exit_code: opts.exitCode,
128
- error_message: message,
136
+ // A failed install from a signed link says the link.
137
+ error_message: redactUrls(message),
129
138
  error_name: opts.error instanceof Error ? opts.error.name : 'CliError',
130
- error_stack: opts.error instanceof Error ? opts.error.stack : undefined,
139
+ error_stack: opts.error instanceof Error && opts.error.stack ? redactUrls(opts.error.stack) : undefined,
131
140
  ...this.encryptionExtra(),
132
141
  ...this.submitExtra(),
133
142
  });
@@ -246,6 +255,15 @@ const SENSITIVE_FLAG_NAMES = new Set([
246
255
  '--env',
247
256
  ]);
248
257
  const REDACTED = '<redacted>';
258
+ /**
259
+ * Links in `text` without their query, fragment and user info. A signed
260
+ * download link's query is its credential (`?X-Amz-Signature=…`), and `dcd
261
+ * device start --app <url>` and `install <url>` take one as a plain value.
262
+ * Where the link points stays, for telling failures apart.
263
+ */
264
+ export function redactUrls(text) {
265
+ return text.replaceAll(/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/?#]*@)?([^\s?#]*)(\?[^\s#]*)?(#\S*)?/gi, (_match, scheme, user, rest, query, fragment) => `${scheme}${user ? `${REDACTED}@` : ''}${rest}${query ? `?${REDACTED}` : ''}${fragment ? `#${REDACTED}` : ''}`);
266
+ }
249
267
  /**
250
268
  * The argv a command was run with, as telemetry may keep it: without the
251
269
  * values of the flags above, and without what two `dcd device` subcommands
@@ -298,7 +316,7 @@ export function scrubArgv(args) {
298
316
  scrubbed.push(arg);
299
317
  }
300
318
  }
301
- return scrubbed;
319
+ return scrubbed.map((arg) => redactUrls(arg));
302
320
  }
303
321
  // argv layout: node|tsx, script, command, ...flags. The first non-flag after
304
322
  // the script is the subcommand. Falls back to 'help' for `--help`/`--version`
@@ -319,13 +337,16 @@ function inferCommandFromArgv() {
319
337
  const API_URL_FLAGS = ['--api-url', '--apiURL', '--apiUrl'];
320
338
  function inferApiUrlFromArgv() {
321
339
  const args = process.argv.slice(2);
340
+ // Only a URL the command itself would send credentials to: these events
341
+ // carry them too, and may be sent before the command checks its flag.
342
+ const usable = (url) => (checkApiUrl(url.trim()).ok ? url.trim() : DEFAULT_API_URL);
322
343
  for (let i = 0; i < args.length; i++) {
323
344
  const arg = args[i];
324
345
  for (const flag of API_URL_FLAGS) {
325
346
  if (arg === flag && args[i + 1])
326
- return args[i + 1];
347
+ return usable(args[i + 1]);
327
348
  if (arg.startsWith(`${flag}=`))
328
- return arg.slice(flag.length + 1);
349
+ return usable(arg.slice(flag.length + 1));
329
350
  }
330
351
  }
331
352
  return DEFAULT_API_URL;
@@ -15,10 +15,23 @@ export interface DeviceSession {
15
15
  model: null | string;
16
16
  client_label: null | string;
17
17
  created_at: string;
18
+ /** When a device was assigned (billing starts); null while queued. Absent from older APIs. */
19
+ started_at?: null | string;
20
+ /** When it ended; null while open. Absent from older APIs. */
21
+ released_at?: null | string;
22
+ /** When its maximum duration ends it; null while queued and once ended. Absent from older APIs. */
23
+ expires_at?: null | string;
18
24
  queue: {
19
25
  eta_s: null | number;
20
26
  position: null | number;
21
- reason: 'fleet_busy' | 'waiting_for_device';
27
+ /**
28
+ * Why it waits. org_concurrency_full: the org's tests and sessions hold
29
+ * every slot it has; fleet_busy: the platform is at its fleet-wide cap;
30
+ * waiting_for_device: waiting for a free device.
31
+ */
32
+ reason: 'fleet_busy' | 'org_concurrency_full' | 'waiting_for_device';
33
+ /** Seconds since the session was created. Absent from older APIs. */
34
+ waited_s?: null | number;
22
35
  } | null;
23
36
  time_remaining_s: null | number;
24
37
  idle_remaining_s: null | number;
@@ -38,6 +51,23 @@ export interface DeviceSession {
38
51
  } | null;
39
52
  warnings: string[];
40
53
  monitor_url: string;
54
+ /**
55
+ * Who started the session, and how that stands to you. Absent from an API
56
+ * that predates it.
57
+ */
58
+ started_by?: DeviceSessionStarter;
59
+ }
60
+ /** Who started a session. */
61
+ export interface DeviceSessionStarter {
62
+ /** The name of the API key that started it, when one did: its label, never the key. */
63
+ key_name: null | string;
64
+ client_label: null | string;
65
+ /** The person who started it, when a person did. */
66
+ email: null | string;
67
+ /** Started from this connection (the same `dcd mcp` process). */
68
+ this_client: boolean;
69
+ /** Started by you: this person, or this API key. */
70
+ you: boolean;
41
71
  }
42
72
  /**
43
73
  * GET .../human and POST .../request-human (ILiveHumanStatus in the API):
@@ -92,8 +122,28 @@ export interface DeviceInstalledApp {
92
122
  binary_upload_id: string;
93
123
  reused: boolean;
94
124
  }
125
+ /**
126
+ * Where a flow failed, as the device worked it out from the flow files.
127
+ * Absent from older APIs, and when only a position is known.
128
+ */
129
+ export interface DeviceFailureLocation {
130
+ /** The runFlow lines that led there, outermost first, e.g. `main.yaml:4`. */
131
+ call_chain: string[];
132
+ /** The command as written, on one line; null when only a line is known. */
133
+ command: null | string;
134
+ /** The file, as a path inside the bundle; `flow.yaml` for a flow sent inline. */
135
+ file: string;
136
+ /** 1-based line in that file. */
137
+ line: number;
138
+ }
139
+ /** Where a failure was: one place, or several that all fit the error. */
140
+ export interface DeviceFailedAt {
141
+ failed_at?: DeviceFailureLocation;
142
+ /** Two or more commands fit the error, and any of them may have failed. */
143
+ failed_at_candidates?: DeviceFailureLocation[];
144
+ }
95
145
  /** One flow of a run, as newer APIs report it in `result.flows`. */
96
- export interface DeviceFlowResult {
146
+ export interface DeviceFlowResult extends DeviceFailedAt {
97
147
  error: null | string;
98
148
  /** The flow's path inside the bundle; null for a single flow. */
99
149
  file: null | string;
@@ -147,7 +197,7 @@ export type DeviceActionRequest = {
147
197
  export declare const DEVICE_KEYS: readonly ["back", "home", "enter", "backspace", "tab", "volume_up", "volume_down", "lock", "power"];
148
198
  export declare const SWIPE_DIRECTIONS: readonly DeviceSwipeDirection[];
149
199
  /** The result of a typed action, a launch or a run. */
150
- export interface DeviceCommandResult {
200
+ export interface DeviceCommandResult extends DeviceFailedAt {
151
201
  error?: string;
152
202
  /** Each flow of a run. Absent from APIs older than this field. */
153
203
  flows?: DeviceFlowResult[];
@@ -193,6 +243,19 @@ export interface DeviceScreenshot {
193
243
  data_url: string;
194
244
  fresh: boolean;
195
245
  }
246
+ /** GET .../screenshot?full=true: a PNG at the device's own resolution, as a link. */
247
+ export interface DeviceFullScreenshot {
248
+ bytes: null | number;
249
+ captured_at: string;
250
+ content_type: string;
251
+ /** How long `url` works, in seconds. */
252
+ expires_in_s: number;
253
+ full: true;
254
+ /** In the device's own pixels; null when the device could not say. */
255
+ height: null | number;
256
+ url: string;
257
+ width: null | number;
258
+ }
196
259
  /** POST .../run and GET .../commands/:id. */
197
260
  export interface DeviceRunResponse {
198
261
  command_id: string;
@@ -205,9 +268,16 @@ export interface DeviceRunResponse {
205
268
  export interface DeviceLogs {
206
269
  app_id: null | string;
207
270
  lines: string[];
271
+ /** How many lines were looked through before the filters. Absent from older APIs. */
272
+ scanned?: number;
208
273
  /** logcat, ios-unified-log, or none before an app is installed. */
209
274
  source: string;
275
+ /** The answer's size cap (24 KB) dropped older lines. Absent when it did not. */
276
+ truncated?: true;
210
277
  }
278
+ /** The filters GET .../logs takes. */
279
+ export declare const LOG_LEVELS: readonly ["warning", "error"];
280
+ export type DeviceLogLevel = (typeof LOG_LEVELS)[number];
211
281
  /** A short-lived download link for one stored artifact. */
212
282
  export interface DeviceArtifactLink {
213
283
  bytes: null | number;
@@ -16,3 +16,5 @@ export const DEVICE_KEYS = [
16
16
  'power',
17
17
  ];
18
18
  export const SWIPE_DIRECTIONS = ['up', 'down', 'left', 'right'];
19
+ /** The filters GET .../logs takes. */
20
+ export const LOG_LEVELS = ['warning', 'error'];
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Checks for an API URL given by hand (`--api-url`, `DCD_API_URL`), before
3
+ * any credential is sent to it: the API key or login session goes with every
4
+ * request, and a repository's MCP config can set DCD_API_URL. No imports, so
5
+ * the telemetry service can use it too.
6
+ */
7
+ export type ApiUrlCheck = {
8
+ ok: false;
9
+ reason: string;
10
+ } | {
11
+ ok: true;
12
+ origin: string;
13
+ warning: null | string;
14
+ };
15
+ /**
16
+ * Whether credentials may be sent to `raw`: an http(s) URL with no user name
17
+ * or password in it, and plain http only to this machine. A host that is not
18
+ * devicecloud.dev passes with a warning (a staging or self-run API).
19
+ */
20
+ export declare function checkApiUrl(raw: string): ApiUrlCheck;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Checks for an API URL given by hand (`--api-url`, `DCD_API_URL`), before
3
+ * any credential is sent to it: the API key or login session goes with every
4
+ * request, and a repository's MCP config can set DCD_API_URL. No imports, so
5
+ * the telemetry service can use it too.
6
+ */
7
+ /** This machine: plain http is fine, for a local API. */
8
+ function isLocalHost(host) {
9
+ return host === 'localhost' || host.endsWith('.localhost') || host === '127.0.0.1' || host === '[::1]';
10
+ }
11
+ /** DeviceCloud's own hosts. */
12
+ function isDeviceCloudHost(host) {
13
+ return host === 'devicecloud.dev' || host.endsWith('.devicecloud.dev');
14
+ }
15
+ /**
16
+ * Whether credentials may be sent to `raw`: an http(s) URL with no user name
17
+ * or password in it, and plain http only to this machine. A host that is not
18
+ * devicecloud.dev passes with a warning (a staging or self-run API).
19
+ */
20
+ export function checkApiUrl(raw) {
21
+ let url;
22
+ try {
23
+ url = new URL(raw);
24
+ }
25
+ catch {
26
+ return { ok: false, reason: `The API URL "${raw}" is not a URL. Use one like https://api.devicecloud.dev.` };
27
+ }
28
+ const host = url.hostname.toLowerCase();
29
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
30
+ return { ok: false, reason: `The API URL must start with https://, not ${url.protocol}//.` };
31
+ }
32
+ if (url.username || url.password) {
33
+ return { ok: false, reason: 'The API URL must not contain a user name or password.' };
34
+ }
35
+ if (url.protocol === 'http:' && !isLocalHost(host)) {
36
+ return {
37
+ ok: false,
38
+ reason: `Refusing to send your API key or login session to ${url.origin} over plain http, where anyone on the way can read it. Use https.`,
39
+ };
40
+ }
41
+ const trusted = isDeviceCloudHost(host) || isLocalHost(host);
42
+ return {
43
+ ok: true,
44
+ origin: url.origin,
45
+ warning: trusted
46
+ ? null
47
+ : `The API URL ${url.origin} is not a devicecloud.dev host. Your API key or login session is sent to it with every request.`,
48
+ };
49
+ }
@@ -1,6 +1,12 @@
1
1
  import type { AuthContext } from '../types/domain/auth.types.js';
2
2
  /** The platform a local build is for, from its file name; undefined if unknown. */
3
3
  export declare function platformOfAppFile(filePath: string): 'android' | 'ios' | undefined;
4
+ /**
5
+ * The platform a build at a URL is for, from the file name in its path:
6
+ * install from a URL takes an Android .apk or a zipped iOS simulator .app.
7
+ * Undefined when the path names neither (a signed link with no file name).
8
+ */
9
+ export declare function platformOfAppUrl(url: string): 'android' | 'ios' | undefined;
4
10
  export interface UploadLocalAppOptions {
5
11
  apiUrl: string;
6
12
  auth: AuthContext;
@@ -14,6 +14,25 @@ export function platformOfAppFile(filePath) {
14
14
  return 'ios';
15
15
  return undefined;
16
16
  }
17
+ /**
18
+ * The platform a build at a URL is for, from the file name in its path:
19
+ * install from a URL takes an Android .apk or a zipped iOS simulator .app.
20
+ * Undefined when the path names neither (a signed link with no file name).
21
+ */
22
+ export function platformOfAppUrl(url) {
23
+ let pathname;
24
+ try {
25
+ pathname = decodeURIComponent(new URL(url).pathname).toLowerCase();
26
+ }
27
+ catch {
28
+ return undefined;
29
+ }
30
+ if (pathname.endsWith('.apk'))
31
+ return 'android';
32
+ if (pathname.endsWith('.zip'))
33
+ return 'ios';
34
+ return undefined;
35
+ }
17
36
  /**
18
37
  * Upload a local build the way `dcd upload` does, and return its binary id:
19
38
  * an Expo `.tar.gz` is unpacked to its `.app`, a `.zip` is checked, and the
@@ -21,13 +21,17 @@ export declare function getConfigPath(): string;
21
21
  export declare function readConfig(): StoredConfig | null;
22
22
  /**
23
23
  * Resolve the API URL a command should talk to. Precedence:
24
- * 1. explicit --api-url flag
24
+ * 1. explicit --api-url flag (or DCD_API_URL, for the MCP server)
25
25
  * 2. api_url stored by `dcd login` (honors the env the user logged into)
26
26
  * 3. prod default
27
27
  *
28
28
  * Without this, session commands default to prod and a dev/staging Bearer
29
29
  * token is rejected with a misleading "Invalid or expired JWT". `switch-org`
30
30
  * has always done this; this helper extends it to every command.
31
+ *
32
+ * An explicit URL is checked first, since the credentials go to it
33
+ * (checkApiUrl): plain http is refused except to this machine, and a host
34
+ * other than devicecloud.dev gets a warning on stderr, once.
31
35
  */
32
36
  export declare function resolveApiUrl(flag: string | undefined): string;
33
37
  export declare function writeConfig(config: StoredConfig): void;
@@ -11,6 +11,8 @@ import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync
11
11
  import { homedir } from 'node:os';
12
12
  import * as path from 'node:path';
13
13
  import { ENVIRONMENTS } from '../config/environments.js';
14
+ import { checkApiUrl } from './api-url.js';
15
+ import { CliError } from './cli.js';
14
16
  export const CONFIG_SCHEMA_VERSION = 1;
15
17
  export function getConfigDir() {
16
18
  if (process.env.DCD_CONFIG_DIR)
@@ -45,20 +47,34 @@ export function readConfig() {
45
47
  return null;
46
48
  }
47
49
  }
50
+ /** Hosts already warned about in this process: the MCP server resolves its URL again and again. */
51
+ const warnedHosts = new Set();
48
52
  /**
49
53
  * Resolve the API URL a command should talk to. Precedence:
50
- * 1. explicit --api-url flag
54
+ * 1. explicit --api-url flag (or DCD_API_URL, for the MCP server)
51
55
  * 2. api_url stored by `dcd login` (honors the env the user logged into)
52
56
  * 3. prod default
53
57
  *
54
58
  * Without this, session commands default to prod and a dev/staging Bearer
55
59
  * token is rejected with a misleading "Invalid or expired JWT". `switch-org`
56
60
  * has always done this; this helper extends it to every command.
61
+ *
62
+ * An explicit URL is checked first, since the credentials go to it
63
+ * (checkApiUrl): plain http is refused except to this machine, and a host
64
+ * other than devicecloud.dev gets a warning on stderr, once.
57
65
  */
58
66
  export function resolveApiUrl(flag) {
59
67
  const explicit = flag?.trim();
60
- if (explicit)
68
+ if (explicit) {
69
+ const check = checkApiUrl(explicit);
70
+ if (!check.ok)
71
+ throw new CliError(check.reason);
72
+ if (check.warning && !warnedHosts.has(check.origin)) {
73
+ warnedHosts.add(check.origin);
74
+ process.stderr.write(`Warning: ${check.warning}\n`);
75
+ }
61
76
  return explicit;
77
+ }
62
78
  return readConfig()?.api_url ?? ENVIRONMENTS.prod.apiUrl;
63
79
  }
64
80
  export function writeConfig(config) {
@@ -43,6 +43,11 @@ export interface DownloadArtifactOptions {
43
43
  /** How many times to try each file before reporting it failed. */
44
44
  attempts?: number;
45
45
  }
46
+ /**
47
+ * Download one link to `target`, tried twice, making its folder. A failed
48
+ * download leaves no partial file behind.
49
+ */
50
+ export declare function downloadFile(url: string, target: string, options?: DownloadArtifactOptions): Promise<void>;
46
51
  /**
47
52
  * Download every file with a link into `dir`, four at a time. Each file is
48
53
  * tried twice (a stalled CDN response usually succeeds on a second
@@ -165,6 +165,28 @@ async function downloadOnce(url, target, idleMs, totalMs) {
165
165
  clearTimeout(total);
166
166
  }
167
167
  }
168
+ /**
169
+ * Download one link to `target`, tried twice, making its folder. A failed
170
+ * download leaves no partial file behind.
171
+ */
172
+ export async function downloadFile(url, target, options = {}) {
173
+ const idleMs = options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
174
+ const totalMs = options.totalTimeoutMs ?? DEFAULT_TOTAL_TIMEOUT_MS;
175
+ const attempts = Math.max(1, options.attempts ?? DEFAULT_ATTEMPTS);
176
+ await mkdir(path.dirname(target), { recursive: true });
177
+ let lastError;
178
+ for (let attempt = 1; attempt <= attempts; attempt++) {
179
+ try {
180
+ await downloadOnce(url, target, idleMs, totalMs);
181
+ return;
182
+ }
183
+ catch (error) {
184
+ lastError = error;
185
+ }
186
+ }
187
+ await rm(target, { force: true }).catch(() => { });
188
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
189
+ }
168
190
  /**
169
191
  * Download every file with a link into `dir`, four at a time. Each file is
170
192
  * tried twice (a stalled CDN response usually succeeds on a second