diff --git a/CHANGELOG.md b/CHANGELOG.md index 473ce1e..0c4033c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,38 @@ # Changelog +## [5.16.0](https://github.com/devicecloud-dev/dcd-cli/compare/v5.15.0...v5.16.0) (2026-11-30) + + +### Features + +* **e2e:** link each test's video to its part of the session recording ([#362](https://github.com/devicecloud-dev/dcd-cli/issues/362)) ([924181e](https://github.com/devicecloud-dev/dcd-cli/commit/924181effca63f04bb7e16542988f862916560d6)) +* **e2e:** run e2e tests on DeviceCloud devices with @devicecloud.dev/dcd/e2e ([#346](https://github.com/devicecloud-dev/dcd-cli/issues/346)) ([d772c53](https://github.com/devicecloud-dev/dcd-cli/commit/d772c533bf56165292e30420a0598f21469af86a)) +* **e2e:** set the device's locale from the e2e provider ([#355](https://github.com/devicecloud-dev/dcd-cli/issues/355)) ([ba43df4](https://github.com/devicecloud-dev/dcd-cli/commit/ba43df49e655d54f3e78fab9d6ce853213c7d0e7)) +* **encryption:** always encrypt uploads; ignore --no-encrypt and DCD_ENCRYPT=0 ([#363](https://github.com/devicecloud-dev/dcd-cli/issues/363)) ([a2c4f76](https://github.com/devicecloud-dev/dcd-cli/commit/a2c4f76c19f471f363636bd2e8a3fbdf85e7016a)) +* **telemetry:** honour DO_NOT_TRACK, and document what telemetry sends ([#364](https://github.com/devicecloud-dev/dcd-cli/issues/364)) ([422012a](https://github.com/devicecloud-dev/dcd-cli/commit/422012a7c8ad73dbf1ffa1e7305e58e90c86668d)) +* **upload:** upload straight to the final storage path with a signed token ([#360](https://github.com/devicecloud-dev/dcd-cli/issues/360)) ([00b2807](https://github.com/devicecloud-dev/dcd-cli/commit/00b2807f59138737fb00a112d088d4c96a884fe2)) + + +### Bug Fixes + +* keep chalk's colour output in nested and multi-line text ([#353](https://github.com/devicecloud-dev/dcd-cli/issues/353)) ([bb273f0](https://github.com/devicecloud-dev/dcd-cli/commit/bb273f0f88d5cc7bc9d123f5e7eda50103df1993)) +* **artifacts:** save into a folder given as the artifacts path, and d… ([#354](https://github.com/devicecloud-dev/dcd-cli/issues/354)) ([9d9adc2](https://github.com/devicecloud-dev/dcd-cli/commit/9d9adc2065c9787399422651e5cfb57740b186b9)) +* **device:** drop iOS 17 from the help text ([#356](https://github.com/devicecloud-dev/dcd-cli/issues/356)) ([c3e0fdf](https://github.com/devicecloud-dev/dcd-cli/commit/c3e0fdfc49ffb73a9ee49e041ef6d929968d1f86)) +* **download:** show a manifest 400/403/404 instead of re-requesting the inline route ([#357](https://github.com/devicecloud-dev/dcd-cli/issues/357)) ([03c01df](https://github.com/devicecloud-dev/dcd-cli/commit/03c01dfc256081aede92d8250f1f2f398465250a)) +* **upload:** refresh the upload token when Storage reports it expired ([#361](https://github.com/devicecloud-dev/dcd-cli/issues/361)) ([161c428](https://github.com/devicecloud-dev/dcd-cli/commit/161c4284af227d119439ffe92420c387f11b2e1d)) +* **upload:** send resumable uploads to the configured Supabase URL ([#358](https://github.com/devicecloud-dev/dcd-cli/issues/358)) ([edf10a7](https://github.com/devicecloud-dev/dcd-cli/commit/edf10a7e9d46dcd50660188da8c4c02f00a8bfcf)) +* **upload:** send Storage uploads with fetch in the standalone binary ([#359](https://github.com/devicecloud-dev/dcd-cli/issues/359)) ([e03a78e](https://github.com/devicecloud-dev/dcd-cli/commit/e03a78ed4cdf25eeeb074d667b3b418646715019)) + + +### Dependencies + +* bump the minor-and-patch group with 3 updates ([#348](https://github.com/devicecloud-dev/dcd-cli/issues/348)) ([64f0942](https://github.com/devicecloud-dev/dcd-cli/commit/64f0942ab1244656aabec30785ca3ef30d04969e)) + + +### Code Refactoring + +* replace chalk with node:util styleText ([#352](https://github.com/devicecloud-dev/dcd-cli/issues/352)) ([2e2377b](https://github.com/devicecloud-dev/dcd-cli/commit/2e2377bfd357bdebfd7a69beb7122d65e8af4818)) + ## [5.15.0](https://github.com/devicecloud-dev/dcd-cli/compare/v5.14.1...v5.15.0) (2026-11-19) diff --git a/CLAUDE.md b/CLAUDE.md index d3e8a6b..f4aa91d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,7 +8,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co - `pnpm build` — clean, compile TypeScript to `dist/`, and `chmod +x dist/index.js dist/mcp/index.js` so both published binaries are directly executable. - `pnpm build:binaries` — `scripts/build-binaries.mjs` produces the bun-compiled, self-contained `dcd--` binaries published to GitHub Releases (the install `dcd upgrade` self-updates). The platform/arch keys must stay in sync with `ASSET_BY_PLATFORM` in `src/commands/upgrade.ts`. - `pnpm lint` — ESLint over `src/` and `test/`. -- `pnpm typecheck` — `tsc --noEmit -p tsconfig.test.json` over `src/` and `test/` (strict mode; `pnpm build` only compiles `src/`). Requires Node `>=22`. +- `pnpm typecheck` — `tsc --noEmit -p tsconfig.test.json` over `src/` and `test/` (strict mode; `pnpm build` only compiles `src/`). Requires Node `>=22.8`. - `pnpm test` — runs `scripts/test-runner.mjs`: builds the CLI, boots the mock API if one is available, then runs mocha. TypeScript is loaded by **tsx** (`.mocharc.json`'s `node-option: ["import=tsx"]`), *not* ts-node — Mocha 11 imports specs as ESM, which bypasses the `require: ts-node/register` hook. The runner isolates `DCD_CONFIG_DIR` to a temp dir so tests never touch your real `dcd login` session. - `pnpm test:unit` — the same runner with `--unit`: unit specs only, no mock API. **This is what CI runs.** - Tests split into `test/unit/*` (pure, no backend) and `test/integration/*` (drive the built CLI against a Prism mock of the dcd API on port 3001). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6907aa1..aa315cc 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -19,7 +19,7 @@ is a one-time step. PRs cannot be merged until the CLA check is green. ## Getting started -You need **Node.js 22+** and **[pnpm](https://pnpm.io)** (`packageManager` pins +You need **Node.js 22.8+** and **[pnpm](https://pnpm.io)** (`packageManager` pins the exact version; [Corepack](https://nodejs.org/api/corepack.html) will pick it up automatically). diff --git a/README.md b/README.md index 3f5f607..54eb192 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ On Windows: irm https://get.devicecloud.dev/install.ps1 | iex ``` -Or via npm if you already have Node 22+: +Or via npm if you already have Node 22.8+: ```sh-session $ npm install -g @devicecloud.dev/dcd @@ -105,7 +105,7 @@ $ claude mcp add --scope user devicecloud -- dcd mcp $ codex mcp add devicecloud -- dcd mcp ``` -If you use the npm package instead of the standalone binary, the command is `npx` with `"args": ["-y", "@devicecloud.dev/dcd", "mcp"]`. That needs Node 22 or newer on the app's PATH, and it checks npm each time it starts. +If you use the npm package instead of the standalone binary, the command is `npx` with `"args": ["-y", "@devicecloud.dev/dcd", "mcp"]`. That needs Node 22.8 or newer on the app's PATH, and it checks npm each time it starts. It signs in the same way as the CLI: with your `dcd login` session, which it renews as it runs, or with `DEVICE_CLOUD_API_KEY`. Point it at a non-prod environment with `DCD_API_URL` (https, or plain http to `localhost` only). @@ -144,10 +144,59 @@ The npm package also ships `dcd-mcp`, an older server with the same `dcd_*` tool `--package` matters: the package's default bin is `dcd`, so `npx @devicecloud.dev/dcd dcd-mcp` would run `dcd dcd-mcp` (an unknown command) instead of the server. It signs in like `dcd mcp`, and takes `--read-only` and `DCD_MCP_READONLY=1` the same way. +## e2e tests on DeviceCloud devices (early access) + +`@devicecloud.dev/dcd/e2e` is a device provider for [e2e](https://github.com/e2e-inc/e2e). Each e2e worker gets its own DeviceCloud device session, and e2e drives the device directly. The session shows in the console, is recorded, and is billed like any other. Your organization needs this turned on by DeviceCloud first. + +```ts +// e2e.config.ts +import type { E2EConfig } from 'e2e'; +import { mobile } from '@e2e-dev/mobile'; +import { deviceCloud } from '@devicecloud.dev/dcd/e2e'; + +const engine = mobile({ platform: 'android', device: deviceCloud() }); + +export default { + targets: [{ name: 'android', engine, app: { bundleId: 'com.example.app', appPath: './build/app.apk' } }], + // The first screen read after a launch can take a few seconds. + assertionTimeout: 20_000, +} satisfies E2EConfig; +``` + +Run `npx e2e run` with `DEVICE_CLOUD_API_KEY` set. The provider uploads `appPath` once per run and each session installs it, so e2e installs nothing itself. To use a build you already uploaded, pass `deviceCloud({ appBinaryId })`. It also takes `model`, `os`, `maxDurationMin`, and `locale` (such as `en_US`) for the device's language and region, set before your build is installed. Each session's console link is printed as the run starts, and the session is stopped when e2e is done with it. + +With e2e's `video` option on (any setting but `'off'`), each test's video in e2e's report is a console link to that test's part of the session's recording. The session is recorded as one video, so the link plays the part from the test's start to its end; it works once the session has ended and its video has uploaded, for as long as the session's files are kept. + +Face ID works on iOS devices. Enrol it with `device.enrollBiometrics('faceid', true)` before the step that opens the prompt. Then `device.setBiometrics('faceid', 'match')` or `'nonmatch'` answers the prompt that is open or opens next, so call it straight after that step: DeviceCloud waits up to 8 seconds for the prompt to open and answers once it can take the answer. On iOS 18, the first time your app asks for Face ID, iOS asks whether the app may use it and opens the prompt only once that is answered: accept it with `device.alert('accept')` before answering. After a match iOS plays a short success animation, and a tap in the second that follows can be lost, so wait for your app's own response before the next tap. A non-match leaves the prompt up showing "Face Not Recognised", as on a phone, and your app hears nothing until the test cancels it with `device.alert('dismiss')` or presses **Try Face ID Again** and answers again. Touch ID and Android fingerprints aren't available: every DeviceCloud iOS device has Face ID, and the Android devices have no screen lock or enrolled fingerprint. Passkey sheets ("Save a passkey?", "Sign In") are drawn by iOS outside your app, so screen reads don't list their buttons; an agent step can press them from the screenshot, or a test can tap their coordinates. + + +## Telemetry + +The CLI sends a small amount of usage and error data to the DeviceCloud API. We use it only for debugging and development: to find and fix bugs, and to see which commands and options are used. It is not used for marketing, and it is not sold. + +**What is sent**, for each command run: + +- the command name and its arguments, with secrets removed (API keys, `--env` values, text typed into a device, and the query part of any URL, which is where signed links keep their credential) +- whether it succeeded, how long it took, and the error message if it failed (URLs redacted the same way) +- the CLI version, how it was installed, the Node.js version, the OS and CPU architecture +- how you signed in (API key or `dcd login`), your organization ID, and a random ID for this run +- whether the app, flows and env vars were encrypted + +Nothing is sent until a command has signed in, so `--help`, `--version` and `dcd login` itself send nothing. Telemetry goes to the same API the command uses (`--api-url`, or the default). A failure to send it never affects the command. + +**Turning it off.** Set either of these in your environment: + +```sh-session +$ export DO_NOT_TRACK=1 # the cross-tool convention, see consoledonottrack.com +$ export DCD_TELEMETRY_DISABLED=1 +``` + +`0`, `false` or an empty value leaves telemetry on. For the MCP server, add the variable to the `env` block of your MCP client's config. + ## Development -Requires Node 22+ and [pnpm](https://pnpm.io). `pnpm install` builds the CLI and installs the git hooks automatically. +Requires Node 22.8+ and [pnpm](https://pnpm.io). `pnpm install` builds the CLI and installs the git hooks automatically. ```sh-session $ pnpm install # install deps, build, set up git hooks diff --git a/eslint.config.cjs b/eslint.config.cjs index aded632..ccaa2c4 100644 --- a/eslint.config.cjs +++ b/eslint.config.cjs @@ -6,9 +6,6 @@ const js = require('@eslint/js'); const tseslint = require('typescript-eslint'); -// This plugin ships as ESM with a `default` export under CJS interop. -const unicornPlugin = - require('eslint-plugin-unicorn').default ?? require('eslint-plugin-unicorn'); module.exports = tseslint.config( { @@ -21,16 +18,6 @@ module.exports = tseslint.config( js.configs.recommended, ...tseslint.configs.recommended, { - // `unicorn` is only registered so legacy - // `// eslint-disable-next-line unicorn/...` comments scattered through - // the source resolve. We don't enable any rules from it. - // `eslint-plugin-import` used to be registered here for the same reason, - // but it was dropped: it dragged in minimatch@3 -> brace-expansion@1.x, - // which has an unpatched DoS advisory (GHSA-mh99-v99m-4gvg, no 1.x - // backport) and failed `pnpm audit`. No rules from it were ever enabled. - plugins: { - unicorn: unicornPlugin, - }, languageOptions: { ecmaVersion: 2022, sourceType: 'module', diff --git a/package.json b/package.json index bb43a3d..b9eb1c4 100644 --- a/package.json +++ b/package.json @@ -7,9 +7,7 @@ "dependencies": { "@clack/prompts": "^1.6.0", "@modelcontextprotocol/sdk": "^1.31.0", - "@supabase/supabase-js": "^2.108.2", - "bplist-parser": "^0.5.0", - "chalk": "^6.0.0", + "bplist-parser": "^0.6.0", "citty": "^0.2.2", "js-yaml": "^5.2.2", "node-stream-zip": "^1.15.0", @@ -29,7 +27,6 @@ "chai": "^6.2.2", "eslint": "^10.15.0", "eslint-config-prettier": "^10.1.8", - "eslint-plugin-unicorn": "^79.0.0", "husky": "^9.1.7", "mocha": "^12.0.0", "prettier": "^3.8.4", @@ -38,7 +35,7 @@ "typescript-eslint": "^8.73.0" }, "engines": { - "node": ">=22.0.0" + "node": ">=22.8.0" }, "files": [ "/dist" @@ -66,7 +63,7 @@ "test:unit": "node scripts/test-runner.mjs --unit", "typecheck": "tsc --noEmit -p tsconfig.test.json" }, - "version": "5.15.0", + "version": "5.16.0", "bugs": { "url": "https://discord.gg/gm3mJwcNw8" }, @@ -79,18 +76,20 @@ "testing" ], "types": "dist/index.d.ts", + "exports": { + ".": "./dist/index.js", + "./e2e": { + "types": "./dist/e2e/index.d.ts", + "default": "./dist/e2e/index.js" + }, + "./package.json": "./package.json", + "./dist/*": "./dist/*" + }, "packageManager": "pnpm@10.17.1", "pnpm": { "overrides": { "minimatch@>=10.0.0 <11.0.1": "11.0.1", "glob@>=9.0.0 <14.0.2": "14.0.2" - }, - "auditConfig": { - "ignoreGhsas": [ - "GHSA-frvp-7c67-39w9", - "GHSA-vfj7-8cjw-p6xm", - "GHSA-fc5q-39xc-vjpf" - ] } } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 91c6355..c9ca986 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -18,15 +18,9 @@ importers: '@modelcontextprotocol/sdk': specifier: ^1.31.0 version: 1.32.2(zod@4.6.7) - '@supabase/supabase-js': - specifier: ^2.108.2 - version: 2.119.0 bplist-parser: - specifier: ^0.5.0 - version: 0.5.0 - chalk: - specifier: ^6.0.0 - version: 6.0.1 + specifier: ^0.6.0 + version: 0.6.0 citty: specifier: ^0.2.2 version: 0.2.2 @@ -38,7 +32,7 @@ importers: version: 1.16.0 plist: specifier: ^5.0.0 - version: 5.1.1 + version: 5.1.2 tar: specifier: ^7.5.16 version: 7.5.23 @@ -76,9 +70,6 @@ importers: eslint-config-prettier: specifier: ^10.1.8 version: 10.1.8(eslint@10.15.0) - eslint-plugin-unicorn: - specifier: ^79.0.0 - version: 79.0.0(eslint@10.15.0)(typescript@6.0.3) husky: specifier: ^9.1.7 version: 9.1.7 @@ -292,10 +283,6 @@ packages: resolution: {integrity: sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ==} engines: {node: ^20.19.0 || ^22.13.0 || >=24} - '@eslint/css-tree@4.1.2': - resolution: {integrity: sha512-rVcxLmwSkEL3aWS3vAgsTRrQHoYE1b0XcgDtKHDJ92XOkyUpcbS/g0tUJKhvCtlEhYzgKBWsgDd+Z/aPhd166w==} - engines: {node: ^20.19.0 || ^22.13.0 || >=24} - '@eslint/js@10.0.1': resolution: {integrity: sha512-zeR9k5pd4gxjZ0abRoIaxdc7I3nDktoXZk2qOv9gCNWx3mVwEn32VRhyLaRsDiJjTs0xq/T8mfPtyuXu7GWBcA==} engines: {node: ^20.19.0 || ^22.13.0 || >=24} @@ -368,44 +355,9 @@ packages: '@cfworker/json-schema': optional: true - '@supabase/auth-js@2.119.0': - resolution: {integrity: sha512-WI7KqJRxqZjm77PlRO/VfKretL4SG8g8stWfBmpyx9To+fFapZlSbXA8QkduoMvr72rRpIF24ZLrjktBrp+ZFA==} - engines: {node: '>=22.0.0'} - - '@supabase/functions-js@2.119.0': - resolution: {integrity: sha512-0aOdF/Y4lA+62K02nwZClfAthXmFEml0od42q3yy/9t3bBitomAOYEatTFSnxT/5UeeIDNn2DOnXTdAP0sqGNQ==} - engines: {node: '>=22.0.0'} - - '@supabase/phoenix@0.4.5': - resolution: {integrity: sha512-aAn9H9ovVyeApKy11OWOrrOGq8DV68yWeH4ud2lN9fzn4aO8Zb5GLL9m1pUg9nLqIcT+ZDfAcsZe0E/nqdv2lw==} - - '@supabase/postgrest-js@2.119.0': - resolution: {integrity: sha512-qBmcjEFO7Ptyf5qvOXYJa1s4bfA4zsMIFf2i+h2zd6RRTDLwquX8z1mnS9djNOJjbiO1OGFh5Y2Lc2k2pA8TMw==} - engines: {node: '>=22.0.0'} - - '@supabase/realtime-js@2.119.0': - resolution: {integrity: sha512-fPzxt+SAYweqsZUCSZma2dvN+HT6lVjwWj8BbkVwapW6wNf1odUi+ATYN7svX4Zm9vt0kz0l0VzINAUAA38FEg==} - engines: {node: '>=22.0.0'} - - '@supabase/storage-js@2.119.0': - resolution: {integrity: sha512-htx1dSCnSJVPlx2BNSgLSUDvLMxuGbYa6pUPl5xoCs4as4cIhBVwuxj78zbggCyPHxLnEXjsV/qvlDsVjpodKw==} - engines: {node: '>=22.0.0'} - - '@supabase/supabase-js@2.119.0': - resolution: {integrity: sha512-MKP49G6bJbPhvsZDegZ/IXS/ITApPgplDCF5+F65KZ5kIArS5Y90WFxwvWYALx2bsxdrSuHvkCiXHYr3dU8+sw==} - engines: {node: '>=22.0.0'} - peerDependencies: - '@opentelemetry/api': '>=1.0.0' - peerDependenciesMeta: - '@opentelemetry/api': - optional: true - '@types/chai@5.2.3': resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} - '@types/debug@4.1.13': - resolution: {integrity: sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==} - '@types/deep-eql@4.0.2': resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} @@ -421,9 +373,6 @@ packages: '@types/mocha@10.0.10': resolution: {integrity: sha512-xPyYSz1cMPnJQhl0CLMH68j3gprKZaTjG3s5Vi+fDgx+uhG9NOXwbVt52eFS8ECyXhyKcjDLCBEqBExKuiZb7Q==} - '@types/ms@2.1.0': - resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==} - '@types/node@26.6.6': resolution: {integrity: sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==} @@ -536,18 +485,13 @@ packages: resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} engines: {node: 18 || 20 || >=22} - baseline-browser-mapping@2.11.34: - resolution: {integrity: sha512-Aqr8mA1kIvyJ3UY5YAY7ib8LSo1DmDMbMnVqGPtsKW1LxaFQFwn9Eb3yvq2fUKJsRvaXjnAV7R5osqETapzNiA==} - engines: {node: '>=6.0.0'} - hasBin: true - body-parser@2.4.0: resolution: {integrity: sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==} engines: {node: '>=18'} - bplist-parser@0.5.0: - resolution: {integrity: sha512-owgQ0RGbndIGNrQkpHe99HVSslIK59t31nVyAPDRqhq9mNDc2kRl5HwYO292GuKjHqiJRdJNiaI63a02hjLFIQ==} - engines: {node: '>=20.19.0'} + bplist-parser@0.6.0: + resolution: {integrity: sha512-ob85QPs+XClfFTx7KabrRUhpFbRPjabGrOi8oFzFaeftq3exQuyWawg/MlR8WwRl5CGa4gClg7YlN5wzZxvi7Q==} + engines: {node: '>=22.12.0'} brace-expansion@5.0.12: resolution: {integrity: sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==} @@ -556,11 +500,6 @@ packages: browser-stdout@1.3.1: resolution: {integrity: sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw==} - browserslist@4.29.5: - resolution: {integrity: sha512-khTmKu5NGYTotqcYo8Bew2k4RAE9PuXRSFRXG2lQBrCEQHyeQ/vX6gKMxfokwywBsLiXZMnHsmWMG1pnO8J7uQ==} - engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} - hasBin: true - buffer-crc32@1.0.0: resolution: {integrity: sha512-Db1SbgBS/fg/392AblrMJk97KggmvYhr4pB5ZIMTWtaivCPMWLkmb7m21cJvpvgK+J3nsU2CmmixNBZx4vFj/w==} engines: {node: '>=8.0.0'} @@ -568,10 +507,6 @@ packages: buffer-from@1.1.2: resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==} - builtin-modules@5.4.0: - resolution: {integrity: sha512-JCWSCdun+4Ovd9BhM/Vtlmwb7oD6Wl4YiPRXXwhAuwlPhW1un/MKgXn7GZoFm53ginnoNzus69V8JWx0K393jg==} - engines: {node: '>=18.20'} - bytes@3.1.2: resolution: {integrity: sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==} engines: {node: '>= 0.8'} @@ -587,23 +522,10 @@ packages: resolution: {integrity: sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==} engines: {node: '>= 0.4'} - caniuse-lite@1.0.30001820: - resolution: {integrity: sha512-gfWD6MxqVCqAOwmODfZf7DchWvlrA+SRdNX7ceLfg3xRqe5ssjjpF7EgslC/0tiLiNTajdaNN/q8c/5u/7Gz8w==} - chai@6.3.0: resolution: {integrity: sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==} engines: {node: '>=18'} - chalk@6.0.1: - resolution: {integrity: sha512-/Ce6KNm3vIbWdMlNna6RVIZ/ICQxnJxCicet5LBKK9ZffBkqzDw0xh9EiKSljdRtiIQ1S1z4YgcscUUGzNCWrA==} - engines: {node: '>=22'} - - change-case@5.4.4: - resolution: {integrity: sha512-HRQyTk2/YPEkt9TnUPbOpr64Uw3KOicFWPVBb+xiHvd6eBx/qPr9xqfBFDT8P2vWsvvz4jbEkfDe71W3VyNu2w==} - - character-entities@2.0.2: - resolution: {integrity: sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==} - chokidar@5.0.0: resolution: {integrity: sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==} engines: {node: '>= 20.19.0'} @@ -612,10 +534,6 @@ packages: resolution: {integrity: sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==} engines: {node: '>=18'} - ci-info@4.4.0: - resolution: {integrity: sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg==} - engines: {node: '>=8'} - citty@0.2.2: resolution: {integrity: sha512-+6vJA3L98yv+IdfKGZHBNiGW5KHn22e/JwID0Strsz8h4S/csAu/OuICwxrg44k5MRiZHWIo8XXuJgQTriRP4w==} @@ -642,10 +560,6 @@ packages: resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==} engines: {node: '>= 0.6'} - core-js-compat@3.51.0: - resolution: {integrity: sha512-52r6fkXgxv4GLMjmFcMWRx7X9bw071xTTdrDcdyPGRqU2oE+9pCG0bAOMifSBdLw0JRBZKEF0q3B55qPlLuE8g==} - engines: {node: '>=6.4.0'} - cors@2.8.6: resolution: {integrity: sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==} engines: {node: '>= 0.10'} @@ -666,9 +580,6 @@ packages: supports-color: optional: true - decode-named-character-reference@1.3.0: - resolution: {integrity: sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==} - deep-is@0.1.4: resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} @@ -676,17 +587,6 @@ packages: resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==} engines: {node: '>= 0.8'} - dequal@2.0.3: - resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} - engines: {node: '>=6'} - - detect-indent@7.0.2: - resolution: {integrity: sha512-y+8xyqdGLL+6sh0tVeHcfP/QDd8gUgbasolJJpY7NgeQGSZ739bDtSiaiDgtoicy+mtYB81dKLxO9xRhCyIB3A==} - engines: {node: '>=12.20'} - - devlop@1.1.0: - resolution: {integrity: sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==} - diff@9.0.0: resolution: {integrity: sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw==} engines: {node: '>=0.3.1'} @@ -698,17 +598,10 @@ packages: ee-first@1.1.1: resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==} - electron-to-chromium@1.5.468: - resolution: {integrity: sha512-8XdEp3sIqO+PzmVPxhzqHq/3+yCxp44m27cm2WY1sRn3ZhwKyKmqSi2hx6gEhmnOXmh8NUuYE00z6Onzn5m6DA==} - encodeurl@2.0.1: resolution: {integrity: sha512-Ev/hIyePLZtpL98x562lvPtenrUfGr0lfaf44HFZ+hDEwso7ccV9QAZrEVLg0hxNAzygaAFxy2dYaAKKM0G06A==} engines: {node: '>= 0.8'} - entities@8.1.0: - resolution: {integrity: sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==} - engines: {node: '>=20.19.0'} - es-define-property@1.0.1: resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} engines: {node: '>= 0.4'} @@ -726,10 +619,6 @@ packages: engines: {node: '>=18'} hasBin: true - escalade@3.2.0: - resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} - engines: {node: '>=6'} - escape-html@1.0.3: resolution: {integrity: sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==} @@ -743,16 +632,6 @@ packages: peerDependencies: eslint: '>=7.0.0' - eslint-plugin-unicorn@79.0.0: - resolution: {integrity: sha512-k7MWrjoVTVCnjKpgaxBuScPNSPomLvDpsd9uADpWrIFzrnwiec27eWhGrmmyuTj1bC3xVNYP4QfG3MEzEw6ifg==} - engines: {node: '>=22'} - peerDependencies: - eslint: '>=10.4' - typescript: '*' - peerDependenciesMeta: - typescript: - optional: true - eslint-scope@9.1.2: resolution: {integrity: sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ==} engines: {node: ^20.19.0 || ^22.13.0 || >=24} @@ -900,10 +779,6 @@ packages: resolution: {integrity: sha512-vfMgTR2djMHPUchsJMLpZlYQvtjVL+mHpEr5wPpoCbQs2vr/FBNK+3Gnl9Ara1DSs4Aeg4eG9HiADb5/rkY/ZA==} engines: {node: 18 || 20 || >=22} - globals@17.13.0: - resolution: {integrity: sha512-RwMTC61u7hrG3ZJMkZQOK4JLJrKS8QtoTii63EmWvFXHqycY9FObBJQCbsLxSO8kjKhWE5kV1GC+Vb1g3RI0Zg==} - engines: {node: '>=18'} - gopd@1.2.0: resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==} engines: {node: '>= 0.4'} @@ -946,18 +821,10 @@ packages: engines: {node: '>=18'} hasBin: true - iceberg-js@0.8.1: - resolution: {integrity: sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA==} - engines: {node: '>=20.0.0'} - iconv-lite@0.7.3: resolution: {integrity: sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==} engines: {node: '>=0.10.0'} - identifier-regex@1.1.0: - resolution: {integrity: sha512-SLX4H/vtcYlYnL7XqnuJKHU7Z8517TgsW9nmQiGOgMCjQ8V/deLYu6bEmbGoXe7WMMhc9+EUGyFFneHja8KabA==} - engines: {node: '>=18'} - ignore@5.3.2: resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} engines: {node: '>= 4'} @@ -970,10 +837,6 @@ packages: resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} engines: {node: '>=0.8.19'} - indent-string@5.0.0: - resolution: {integrity: sha512-m6FAo/spmsW2Ab2fU35JTYwtOKa2yAwXSwgjSv1TJzh4Mh7mC3lzAOVLBprb72XsTrgkEIsl7YrFNAiDiRhIGg==} - engines: {node: '>=12'} - inherits@2.0.4: resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} @@ -985,10 +848,6 @@ packages: resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==} engines: {node: '>= 0.10'} - is-builtin-module@5.0.0: - resolution: {integrity: sha512-f4RqJKBUe5rQkJ2eJEJBXSticB3hGbN9j0yxxMQFqIW89Jp9WYFtzfTcRlstDKVUTRzSOTLKRfO9vIztenwtxA==} - engines: {node: '>=18.20'} - is-extglob@2.1.1: resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} engines: {node: '>=0.10.0'} @@ -1025,11 +884,6 @@ packages: resolution: {integrity: sha512-paNr4LFIFPjeeSmwNYdrb8FafLLG/Cr2Af3GjbsHJ5CxIjH4r0c2emlmRdAtpPAieP1gRVzk6buBbVP5gBMGAg==} hasBin: true - jsesc@3.1.0: - resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==} - engines: {node: '>=6'} - hasBin: true - json-schema-traverse@0.4.1: resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==} @@ -1085,9 +939,6 @@ packages: resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} engines: {node: '>= 0.4'} - mdn-data@2.37.2: - resolution: {integrity: sha512-rz9YOBGItdSbe7HcSArUbhiAv4SB/4DKRYg96CSFS2CcIYMbUvBtZlzA1NCbk2AdgbmYwMqwNblLpR441lLeiQ==} - media-typer@1.1.1: resolution: {integrity: sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==} engines: {node: '>= 0.8'} @@ -1096,69 +947,6 @@ packages: resolution: {integrity: sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==} engines: {node: '>=18'} - micromark-core-commonmark@2.0.4: - resolution: {integrity: sha512-wxEeE8v8XVvOrxn1TZj74qYhAtTQsSqufHVS3uNVyT1MupXxhyaHk8/9xDNPh9BmL77QNDgWTkZ3RsYHB2ry7w==} - - micromark-factory-destination@2.0.1: - resolution: {integrity: sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==} - - micromark-factory-label@2.0.1: - resolution: {integrity: sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==} - - micromark-factory-space@2.1.0: - resolution: {integrity: sha512-fS8hnLIjnjvdQIj39Geug8wWsR0HrYZ43KShKxNfwT7t2LOHo/LbWZEzEaSOjwtjdCsjoE6syHhonEzW0zv0+Q==} - - micromark-factory-title@2.0.1: - resolution: {integrity: sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==} - - micromark-factory-whitespace@2.0.1: - resolution: {integrity: sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==} - - micromark-util-character@2.1.1: - resolution: {integrity: sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==} - - micromark-util-chunked@2.0.1: - resolution: {integrity: sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==} - - micromark-util-classify-character@2.0.1: - resolution: {integrity: sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q==} - - micromark-util-combine-extensions@2.0.1: - resolution: {integrity: sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==} - - micromark-util-decode-numeric-character-reference@2.0.2: - resolution: {integrity: sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw==} - - micromark-util-edit-map@1.0.0: - resolution: {integrity: sha512-Pa2ljlsEL6sVwFaYeyrOLSYbQt73JvGbPOYFq+9AElXiSnfI5Q4465RRZ1sHv7lDjDOnGRDDaqPXqClqWK/q1Q==} - - micromark-util-encode@2.0.1: - resolution: {integrity: sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==} - - micromark-util-html-tag-name@2.0.1: - resolution: {integrity: sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==} - - micromark-util-normalize-identifier@2.0.1: - resolution: {integrity: sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==} - - micromark-util-resolve-all@2.0.1: - resolution: {integrity: sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==} - - micromark-util-sanitize-uri@2.0.1: - resolution: {integrity: sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==} - - micromark-util-subtokenize@2.1.0: - resolution: {integrity: sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA==} - - micromark-util-symbol@2.0.1: - resolution: {integrity: sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==} - - micromark-util-types@2.0.3: - resolution: {integrity: sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg==} - - micromark@4.0.3: - resolution: {integrity: sha512-oGYfQzHSG5dOMovQcJ3fyTmZlWAWpi0XA0sJwJs+i6OT88o1+Jtw/8z0CmdowSLxGhhFK89rQ/oXph/wN02PNw==} - mime-db@1.54.0: resolution: {integrity: sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==} engines: {node: '>= 0.6'} @@ -1198,10 +986,6 @@ packages: resolution: {integrity: sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==} engines: {node: '>=18'} - node-releases@2.0.62: - resolution: {integrity: sha512-A0Eq+qVDQI97IbAD6g/HriIuv256el9N8EwF4+xqJ49pwrdRYpdCSmLk0sO4I3fnS6hpYE5v22B73Bk+WArEoQ==} - engines: {node: '>=18'} - node-stream-zip@1.16.0: resolution: {integrity: sha512-ObaRrRoR8T68wF6suxHd7R4XQNamij6ZQHrwG7Dx1D2zeHcDNLsIOBcWrIwtDm7AsCXBguaPHgXhcjxDa2szrg==} engines: {node: '>=0.12.0'} @@ -1233,9 +1017,6 @@ packages: resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} engines: {node: '>=10'} - parse5@8.0.1: - resolution: {integrity: sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==} - parseurl@1.3.3: resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==} engines: {node: '>= 0.8'} @@ -1266,14 +1047,10 @@ packages: resolution: {integrity: sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==} engines: {node: '>=16.20.0'} - plist@5.1.1: - resolution: {integrity: sha512-n55fGiwWNHf6zFdP9qvtr1x7P898lfJ/rbDvB3pYqVRcO+iG3sl5SSkGSLiIoAI9ZZc2F3Ga/5wPtM8EqhgSqA==} + plist@5.1.2: + resolution: {integrity: sha512-sAsRKAzFGIdewBCE1IptS7Ncvi0JTjTkFrhjwjT6dDS+R3PIrSLosErSJCfpfnpJ1v5lRh7ZLQnERZnEiUDj/A==} engines: {node: '>=18'} - pluralize@8.0.0: - resolution: {integrity: sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA==} - engines: {node: '>=4'} - prelude-ls@1.2.1: resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} engines: {node: '>= 0.8.0'} @@ -1305,10 +1082,6 @@ packages: querystringify@2.2.0: resolution: {integrity: sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==} - quote-js-string@0.1.0: - resolution: {integrity: sha512-Y3NoRtprEEZQD8RfxMCfS0ZTqc4e+i18OrXEXAvpM6TfC/3y+0L5rNbZiSnbBBEkDfFzbpd8o+cE8q3/anjMGA==} - engines: {node: '>=22'} - range-parser@1.3.0: resolution: {integrity: sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==} engines: {node: '>= 0.6'} @@ -1321,10 +1094,6 @@ packages: resolution: {integrity: sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==} engines: {node: '>= 20.19.0'} - regjsparser@0.13.4: - resolution: {integrity: sha512-EWV80YgFaVgFrjGCAsV7oybp4GOxbls5RzBg8OB0nKEVXsBJR1JlV8Di1JhCROg3MzTfe1RI8yitIm1eOs68iA==} - hasBin: true - require-from-string@2.0.2: resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} engines: {node: '>=0.10.0'} @@ -1332,10 +1101,6 @@ packages: requires-port@1.0.0: resolution: {integrity: sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==} - reserved-identifiers@1.2.0: - resolution: {integrity: sha512-yE7KUfFvaBFzGPs5H3Ops1RevfUEsDc5Iz65rOwWg4lE8HJSYtle77uul3+573457oHvBKuHYDl/xqUkKpEEdw==} - engines: {node: '>=18'} - retry@0.12.0: resolution: {integrity: sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==} engines: {node: '>= 4'} @@ -1347,11 +1112,6 @@ packages: safer-buffer@2.1.2: resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} - semver@7.8.5: - resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} - engines: {node: '>=10'} - hasBin: true - semver@7.8.6: resolution: {integrity: sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==} engines: {node: '>=10'} @@ -1403,18 +1163,10 @@ packages: resolution: {integrity: sha512-2WCqLdt12eN6ehLI50S2/ZxoowXU3DD1KVPRyVP0WEsFahrGZZmCdq1K59qjJljMRIDTwx1D9YaRK+hDneBUMg==} engines: {node: '>=20'} - source-map-js@1.2.2: - resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} - engines: {node: '>=0.10.0'} - statuses@2.0.2: resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==} engines: {node: '>= 0.8'} - strip-indent@4.1.1: - resolution: {integrity: sha512-SlyRoSkdh1dYP0PzclLE7r0M9sgbFKKMFXpFRUMNuKhQSbC6VQIGzq3E0qsfvGJaUFJPGv6Ws1NZ/haTAjfbMA==} - engines: {node: '>=12'} - strip-json-comments@5.0.3: resolution: {integrity: sha512-1tB5mhVo7U+ETBKNf92xT4hrQa3pm0MZ0PQvuDnWgAAGHDsfp4lPSpiS6psrSiet87wyGPh9ft6wmhOMQ0hDiw==} engines: {node: '>=14.16'} @@ -1441,9 +1193,6 @@ packages: peerDependencies: typescript: '>=4.8.4' - tslib@2.8.1: - resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} - tsx@4.23.15: resolution: {integrity: sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==} engines: {node: '>=18.0.0'} @@ -1480,12 +1229,6 @@ packages: resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==} engines: {node: '>= 0.8'} - update-browserslist-db@1.3.4: - resolution: {integrity: sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==} - hasBin: true - peerDependencies: - browserslist: '>= 4.21.0' - uri-js@4.4.1: resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} @@ -1519,11 +1262,6 @@ packages: resolution: {integrity: sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==} engines: {node: '>=18'} - yaml@2.9.1: - resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==} - engines: {node: '>= 14.6'} - hasBin: true - yazl@3.3.1: resolution: {integrity: sha512-BbETDVWG+VcMUle37k5Fqp//7SDOK2/1+T7X8TD96M3D9G8jK5VLUdQVdVjGi8im7FGkazX7kk5hkU8X4L5Bng==} @@ -1667,11 +1405,6 @@ snapshots: dependencies: '@types/json-schema': 7.0.15 - '@eslint/css-tree@4.1.2': - dependencies: - mdn-data: 2.37.2 - source-map-js: 1.2.2 - '@eslint/js@10.0.1(eslint@10.15.0)': optionalDependencies: eslint: 10.15.0 @@ -1741,47 +1474,11 @@ snapshots: transitivePeerDependencies: - supports-color - '@supabase/auth-js@2.119.0': - dependencies: - tslib: 2.8.1 - - '@supabase/functions-js@2.119.0': - dependencies: - tslib: 2.8.1 - - '@supabase/phoenix@0.4.5': {} - - '@supabase/postgrest-js@2.119.0': - dependencies: - tslib: 2.8.1 - - '@supabase/realtime-js@2.119.0': - dependencies: - '@supabase/phoenix': 0.4.5 - tslib: 2.8.1 - - '@supabase/storage-js@2.119.0': - dependencies: - iceberg-js: 0.8.1 - tslib: 2.8.1 - - '@supabase/supabase-js@2.119.0': - dependencies: - '@supabase/auth-js': 2.119.0 - '@supabase/functions-js': 2.119.0 - '@supabase/postgrest-js': 2.119.0 - '@supabase/realtime-js': 2.119.0 - '@supabase/storage-js': 2.119.0 - '@types/chai@5.2.3': dependencies: '@types/deep-eql': 4.0.2 assertion-error: 2.0.1 - '@types/debug@4.1.13': - dependencies: - '@types/ms': 2.1.0 - '@types/deep-eql@4.0.2': {} '@types/esrecurse@4.3.1': {} @@ -1792,8 +1489,6 @@ snapshots: '@types/mocha@10.0.10': {} - '@types/ms@2.1.0': {} - '@types/node@26.6.6': dependencies: undici-types: 8.9.0 @@ -1934,8 +1629,6 @@ snapshots: balanced-match@4.0.4: {} - baseline-browser-mapping@2.11.34: {} - body-parser@2.4.0: dependencies: bytes: 3.1.2 @@ -1950,7 +1643,7 @@ snapshots: transitivePeerDependencies: - supports-color - bplist-parser@0.5.0: {} + bplist-parser@0.6.0: {} brace-expansion@5.0.12: dependencies: @@ -1958,20 +1651,10 @@ snapshots: browser-stdout@1.3.1: {} - browserslist@4.29.5: - dependencies: - baseline-browser-mapping: 2.11.34 - caniuse-lite: 1.0.30001820 - electron-to-chromium: 1.5.468 - node-releases: 2.0.62 - update-browserslist-db: 1.3.4(browserslist@4.29.5) - buffer-crc32@1.0.0: {} buffer-from@1.1.2: {} - builtin-modules@5.4.0: {} - bytes@3.1.2: {} cacheable@2.5.0: @@ -1992,24 +1675,14 @@ snapshots: call-bind-apply-helpers: 1.0.2 get-intrinsic: 1.3.0 - caniuse-lite@1.0.30001820: {} - chai@6.3.0: {} - chalk@6.0.1: {} - - change-case@5.4.4: {} - - character-entities@2.0.2: {} - chokidar@5.0.0: dependencies: readdirp: 5.1.1 chownr@3.0.0: {} - ci-info@4.4.0: {} - citty@0.2.2: {} combine-errors@3.0.3: @@ -2027,10 +1700,6 @@ snapshots: cookie@0.7.2: {} - core-js-compat@3.51.0: - dependencies: - browserslist: 4.29.5 - cors@2.8.6: dependencies: object-assign: 4.1.1 @@ -2050,22 +1719,10 @@ snapshots: optionalDependencies: supports-color: 8.1.1 - decode-named-character-reference@1.3.0: - dependencies: - character-entities: 2.0.2 - deep-is@0.1.4: {} depd@2.0.0: {} - dequal@2.0.3: {} - - detect-indent@7.0.2: {} - - devlop@1.1.0: - dependencies: - dequal: 2.0.3 - diff@9.0.0: {} dunder-proto@1.0.1: @@ -2076,12 +1733,8 @@ snapshots: ee-first@1.1.1: {} - electron-to-chromium@1.5.468: {} - encodeurl@2.0.1: {} - entities@8.1.0: {} - es-define-property@1.0.1: {} es-errors@1.3.0: {} @@ -2119,8 +1772,6 @@ snapshots: '@esbuild/win32-ia32': 0.28.2 '@esbuild/win32-x64': 0.28.2 - escalade@3.2.0: {} - escape-html@1.0.3: {} escape-string-regexp@4.0.0: {} @@ -2129,36 +1780,6 @@ snapshots: dependencies: eslint: 10.15.0 - eslint-plugin-unicorn@79.0.0(eslint@10.15.0)(typescript@6.0.3): - dependencies: - '@eslint-community/eslint-utils': 4.10.1(eslint@10.15.0) - '@eslint/css-tree': 4.1.2 - browserslist: 4.29.5 - change-case: 5.4.4 - ci-info: 4.4.0 - core-js-compat: 3.51.0 - detect-indent: 7.0.2 - entities: 8.1.0 - eslint: 10.15.0 - find-up-simple: 1.0.1 - globals: 17.13.0 - identifier-regex: 1.1.0 - indent-string: 5.0.0 - is-builtin-module: 5.0.0 - micromark: 4.0.3 - parse5: 8.0.1 - pluralize: 8.0.0 - quote-js-string: 0.1.0 - regjsparser: 0.13.4 - reserved-identifiers: 1.2.0 - semver: 7.8.5 - strip-indent: 4.1.1 - yaml: 2.9.1 - optionalDependencies: - typescript: 6.0.3 - transitivePeerDependencies: - - supports-color - eslint-scope@9.1.2: dependencies: '@types/esrecurse': 4.3.1 @@ -2361,8 +1982,6 @@ snapshots: minipass: 7.1.3 path-scurry: 3.0.0 - globals@17.13.0: {} - gopd@1.2.0: {} graceful-fs@4.2.11: {} @@ -2395,34 +2014,22 @@ snapshots: husky@9.1.7: {} - iceberg-js@0.8.1: {} - iconv-lite@0.7.3: dependencies: safer-buffer: 2.1.2 - identifier-regex@1.1.0: - dependencies: - reserved-identifiers: 1.2.0 - ignore@5.3.2: {} ignore@7.0.14: {} imurmurhash@0.1.4: {} - indent-string@5.0.0: {} - inherits@2.0.4: {} ip-address@10.7.5: {} ipaddr.js@1.9.1: {} - is-builtin-module@5.0.0: - dependencies: - builtin-modules: 5.4.0 - is-extglob@2.1.1: {} is-glob@4.0.3: @@ -2447,8 +2054,6 @@ snapshots: dependencies: argparse: 3.0.3 - jsesc@3.1.0: {} - json-schema-traverse@0.4.1: {} json-schema-traverse@1.0.0: {} @@ -2500,144 +2105,10 @@ snapshots: math-intrinsics@1.1.0: {} - mdn-data@2.37.2: {} - media-typer@1.1.1: {} merge-descriptors@2.0.0: {} - micromark-core-commonmark@2.0.4: - dependencies: - decode-named-character-reference: 1.3.0 - devlop: 1.1.0 - micromark-factory-destination: 2.0.1 - micromark-factory-label: 2.0.1 - micromark-factory-space: 2.1.0 - micromark-factory-title: 2.0.1 - micromark-factory-whitespace: 2.0.1 - micromark-util-character: 2.1.1 - micromark-util-chunked: 2.0.1 - micromark-util-classify-character: 2.0.1 - micromark-util-edit-map: 1.0.0 - micromark-util-html-tag-name: 2.0.1 - micromark-util-normalize-identifier: 2.0.1 - micromark-util-resolve-all: 2.0.1 - micromark-util-subtokenize: 2.1.0 - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.3 - - micromark-factory-destination@2.0.1: - dependencies: - micromark-util-character: 2.1.1 - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.3 - - micromark-factory-label@2.0.1: - dependencies: - devlop: 1.1.0 - micromark-util-character: 2.1.1 - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.3 - - micromark-factory-space@2.1.0: - dependencies: - micromark-util-character: 2.1.1 - micromark-util-types: 2.0.3 - - micromark-factory-title@2.0.1: - dependencies: - micromark-factory-space: 2.1.0 - micromark-util-character: 2.1.1 - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.3 - - micromark-factory-whitespace@2.0.1: - dependencies: - micromark-factory-space: 2.1.0 - micromark-util-character: 2.1.1 - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.3 - - micromark-util-character@2.1.1: - dependencies: - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.3 - - micromark-util-chunked@2.0.1: - dependencies: - micromark-util-symbol: 2.0.1 - - micromark-util-classify-character@2.0.1: - dependencies: - micromark-util-character: 2.1.1 - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.3 - - micromark-util-combine-extensions@2.0.1: - dependencies: - micromark-util-chunked: 2.0.1 - micromark-util-types: 2.0.3 - - micromark-util-decode-numeric-character-reference@2.0.2: - dependencies: - micromark-util-symbol: 2.0.1 - - micromark-util-edit-map@1.0.0: - dependencies: - micromark-util-types: 2.0.3 - - micromark-util-encode@2.0.1: {} - - micromark-util-html-tag-name@2.0.1: {} - - micromark-util-normalize-identifier@2.0.1: - dependencies: - micromark-util-symbol: 2.0.1 - - micromark-util-resolve-all@2.0.1: - dependencies: - micromark-util-types: 2.0.3 - - micromark-util-sanitize-uri@2.0.1: - dependencies: - micromark-util-character: 2.1.1 - micromark-util-encode: 2.0.1 - micromark-util-symbol: 2.0.1 - - micromark-util-subtokenize@2.1.0: - dependencies: - devlop: 1.1.0 - micromark-util-chunked: 2.0.1 - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.3 - - micromark-util-symbol@2.0.1: {} - - micromark-util-types@2.0.3: {} - - micromark@4.0.3: - dependencies: - '@types/debug': 4.1.13 - debug: 4.4.3(supports-color@8.1.1) - decode-named-character-reference: 1.3.0 - devlop: 1.1.0 - micromark-core-commonmark: 2.0.4 - micromark-factory-space: 2.1.0 - micromark-util-character: 2.1.1 - micromark-util-chunked: 2.0.1 - micromark-util-combine-extensions: 2.0.1 - micromark-util-decode-numeric-character-reference: 2.0.2 - micromark-util-edit-map: 1.0.0 - micromark-util-encode: 2.0.1 - micromark-util-normalize-identifier: 2.0.1 - micromark-util-resolve-all: 2.0.1 - micromark-util-sanitize-uri: 2.0.1 - micromark-util-subtokenize: 2.1.0 - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.3 - transitivePeerDependencies: - - supports-color - mime-db@1.54.0: {} mime-types@3.0.2: @@ -2687,8 +2158,6 @@ snapshots: dependencies: content-type: 2.1.0 - node-releases@2.0.62: {} - node-stream-zip@1.16.0: {} object-assign@4.1.1: {} @@ -2720,10 +2189,6 @@ snapshots: dependencies: p-limit: 3.1.0 - parse5@8.0.1: - dependencies: - entities: 8.1.0 - parseurl@1.3.3: {} path-exists@4.0.0: {} @@ -2743,13 +2208,11 @@ snapshots: pkce-challenge@5.0.1: {} - plist@5.1.1: + plist@5.1.2: dependencies: '@xmldom/xmldom': 0.9.12 xmlbuilder: 15.1.1 - pluralize@8.0.0: {} - prelude-ls@1.2.1: {} prettier@3.10.1: {} @@ -2778,8 +2241,6 @@ snapshots: querystringify@2.2.0: {} - quote-js-string@0.1.0: {} - range-parser@1.3.0: {} raw-body@3.0.2: @@ -2791,16 +2252,10 @@ snapshots: readdirp@5.1.1: {} - regjsparser@0.13.4: - dependencies: - jsesc: 3.1.0 - require-from-string@2.0.2: {} requires-port@1.0.0: {} - reserved-identifiers@1.2.0: {} - retry@0.12.0: {} router@2.2.0: @@ -2815,8 +2270,6 @@ snapshots: safer-buffer@2.1.2: {} - semver@7.8.5: {} - semver@7.8.6: {} send@1.2.1: @@ -2886,12 +2339,8 @@ snapshots: sisteransi@2.0.0: {} - source-map-js@1.2.2: {} - statuses@2.0.2: {} - strip-indent@4.1.1: {} - strip-json-comments@5.0.3: {} supports-color@8.1.1: @@ -2917,8 +2366,6 @@ snapshots: dependencies: typescript: 6.0.3 - tslib@2.8.1: {} - tsx@4.23.15: dependencies: esbuild: 0.28.2 @@ -2963,12 +2410,6 @@ snapshots: unpipe@1.0.0: {} - update-browserslist-db@1.3.4(browserslist@4.29.5): - dependencies: - browserslist: 4.29.5 - escalade: 3.2.0 - picocolors: 1.1.1 - uri-js@4.4.1: dependencies: punycode: 2.3.1 @@ -2994,8 +2435,6 @@ snapshots: yallist@5.0.0: {} - yaml@2.9.1: {} - yazl@3.3.1: dependencies: buffer-crc32: 1.0.0 diff --git a/server.json b/server.json index 18de93b..e150f71 100644 --- a/server.json +++ b/server.json @@ -2,7 +2,7 @@ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", "name": "dev.devicecloud/dcd", "description": "Run Maestro mobile app tests on devicecloud.dev: submit flows, check status, download artifacts.", - "version": "5.15.0", + "version": "5.16.0", "repository": { "url": "https://github.com/devicecloud-dev/dcd-cli", "source": "github" @@ -11,7 +11,7 @@ { "registryType": "npm", "identifier": "@devicecloud.dev/dcd", - "version": "5.15.0", + "version": "5.16.0", "runtimeHint": "npx", "runtimeArguments": [ { @@ -48,11 +48,6 @@ "name": "DCD_API_URL", "description": "Override the API base URL (e.g. for a non-production environment).", "isRequired": false - }, - { - "name": "DCD_ENCRYPT", - "description": "Uploads (app binary, flows, env vars) are encrypted on your machine by default. Set to 0 to upload them without envelope encryption; a run's encrypt input overrides this.", - "isRequired": false } ] } diff --git a/src/commands/artifacts.ts b/src/commands/artifacts.ts index c0a5c2c..1732a55 100644 --- a/src/commands/artifacts.ts +++ b/src/commands/artifacts.ts @@ -11,6 +11,7 @@ import { import { resolveAuth } from '../utils/auth.js'; import { CliError, logger, validateEnum } from '../utils/cli.js'; import { resolveApiUrl } from '../utils/config-store.js'; +import { forStderr } from '../utils/styling.js'; import { ui } from '../utils/ui.js'; const DOWNLOAD_OPTIONS = ['ALL', 'FAILED'] as const; @@ -41,7 +42,7 @@ export const artifactsCommand = defineCommand({ 'artifacts-path': { type: 'string', description: - 'Custom file path for downloaded artifacts (default: ./artifacts.zip). Requires --download-artifacts.', + 'File path for downloaded artifacts, or a folder to save artifacts.zip in (default: ./artifacts.zip). Requires --download-artifacts.', }, 'result-id': { type: 'string', @@ -104,7 +105,7 @@ export const artifactsCommand = defineCommand({ // deprecation notice nor the API's submit warning reaches it. const deprecation = reportFormatDeprecation(report); if (deprecation) { - process.stderr.write(`${ui.deprecation(deprecation)}\n`); + process.stderr.write(`${forStderr(ui.deprecation(deprecation))}\n`); } const auth = await resolveAuth({ apiKeyFlag }); diff --git a/src/commands/cloud.ts b/src/commands/cloud.ts index bf03ebb..59cc44f 100644 --- a/src/commands/cloud.ts +++ b/src/commands/cloud.ts @@ -1,4 +1,3 @@ -/* eslint-disable complexity */ import { defineCommand } from 'citty'; import { existsSync } from 'node:fs'; import * as path from 'node:path'; @@ -80,7 +79,6 @@ process.on('warning', (warning) => { ) { return; } - // eslint-disable-next-line no-console console.warn(warning.stack ?? `${warning.name}: ${warning.message}`); }); @@ -122,7 +120,6 @@ export const cloudCommand = defineCommand({ description: 'The flow file to run against the app, e.g. test.yaml', }, }, - // eslint-disable-next-line complexity async run({ args, rawArgs }) { const cliVersion = getCliVersion(); const deviceValidationService = new DeviceValidationService(); @@ -200,9 +197,8 @@ export const cloudCommand = defineCommand({ const googlePlay = Boolean(args['google-play']); const ignoreShaCheck = Boolean(args['ignore-sha-check']); // Client-side envelope encryption of every sensitive artifact: the - // binary (#1138), the flow zip (#1151), and env vars (#1152). Kept as - // given (--no-encrypt is an explicit false) and resolved once the - // compatibility data, which carries the server default, is in. + // binary (#1138), the flow zip (#1151), and env vars (#1152). Always + // on; read only so --no-encrypt can be reported as ignored. const encryptFlag = args.encrypt as boolean | undefined; const includeTags = coerceArray( collectRepeatedFlag(rawArgs, ['--include-tags']), @@ -393,10 +389,7 @@ export const cloudCommand = defineCommand({ } const encryption = await checkKekForEncryption( - resolveEncryption({ - flag: encryptFlag, - serverDefault: compatibilityData.encryption?.defaultOn, - }), + resolveEncryption({ flag: encryptFlag }), apiUrl, ); const encrypt = encryption.enabled; @@ -534,7 +527,7 @@ export const cloudCommand = defineCommand({ })); // Validated after the notices, so a notice aimed at a removed device or - // OS version (e.g. removed-ios-17-2026-11-02) is shown before the + // OS version (e.g. removed-ios-17-2026-11-24) is shown before the // rejection it explains. deviceValidationService.validateiOSDevice(iOSVersion, iOSDevice, compatibilityData, { debug, @@ -814,10 +807,6 @@ export const cloudCommand = defineCommand({ return; } - if (encrypt && encryption.source === 'server') { - out(ui.note('Encrypting uploads; opt out with --no-encrypt')); - } - if (!finalBinaryId) { if (!finalAppFile) { throw new CliError( @@ -1015,7 +1004,7 @@ export const cloudCommand = defineCommand({ if (!results?.length) { throw new CliError('No tests created: ' + message); } - out(`${ui.success('Submitted')} ${colors.dim(message)}`); + out(message ? `${ui.success('Submitted')} ${colors.dim(message)}` : ui.success('Submitted')); const testNames = results .map((r) => r.test_file_name) diff --git a/src/commands/live.ts b/src/commands/live.ts index fa38a9c..273f30f 100644 --- a/src/commands/live.ts +++ b/src/commands/live.ts @@ -10,7 +10,7 @@ import type { LiveSession } from '../types/domain/live.types.js'; import { resolveAuth } from '../utils/auth.js'; import { CliError, logger, validateEnum, wantsJson } from '../utils/cli.js'; import { resolveApiUrl } from '../utils/config-store.js'; -import { colors, formatUrl } from '../utils/styling.js'; +import { colors, formatUrl, forStderr } from '../utils/styling.js'; import { type Field, ui } from '../utils/ui.js'; const PLATFORM_OPTIONS = ['android', 'ios'] as const; @@ -722,7 +722,7 @@ export const liveCommand = defineCommand({ subCommands, // Runs before any subcommand. On stderr, so --json output is unchanged. setup() { - process.stderr.write(`${LIVE_DEPRECATION}\n`); + process.stderr.write(`${forStderr(LIVE_DEPRECATION)}\n`); }, // citty's runCommand does not early-return after dispatching to a // subcommand — it still invokes the parent `run` afterwards. So when a diff --git a/src/commands/login.ts b/src/commands/login.ts index 5ec68df..ac8e1ef 100644 --- a/src/commands/login.ts +++ b/src/commands/login.ts @@ -46,7 +46,7 @@ import { canPrompt } from '../utils/ci.js'; import { CliError, logger } from '../utils/cli.js'; import { readConfig, writeConfig } from '../utils/config-store.js'; import { fetchOrgs, selectOrg } from '../utils/orgs.js'; -import { colors } from '../utils/styling.js'; +import { colors, forStderr } from '../utils/styling.js'; import { ui } from '../utils/ui.js'; interface ClaimedSession { @@ -105,7 +105,7 @@ export const loginCommand = defineCommand({ // Login is interactive, so under --json the human rows and prompts move to // stderr (the user still needs the URL) and stdout gets only the result. const say = (m: string) => { - if (json) process.stderr.write(`${m}\n`); + if (json) process.stderr.write(`${forStderr(m)}\n`); else logger.log(m); }; const promptOutput = json ? process.stderr : undefined; diff --git a/src/commands/status.ts b/src/commands/status.ts index 2e99d4f..d1e8896 100644 --- a/src/commands/status.ts +++ b/src/commands/status.ts @@ -85,7 +85,6 @@ export const statusCommand = defineCommand({ description: 'UUID of the upload to check status for', }, }, - // eslint-disable-next-line complexity async run({ args }) { const apiKeyFlag = args['api-key'] as string | undefined; const apiUrl = resolveApiUrl(args['api-url'] as string | undefined); diff --git a/src/commands/upload.ts b/src/commands/upload.ts index 3aca6f2..7681a1a 100644 --- a/src/commands/upload.ts +++ b/src/commands/upload.ts @@ -8,7 +8,6 @@ import { uploadBinary, verifyAppZip } from '../methods.js'; import { telemetry } from '../services/telemetry.service.js'; import { resolveAuth } from '../utils/auth.js'; import { CliError, logger } from '../utils/cli.js'; -import { fetchCompatibilityData } from '../utils/compatibility.js'; import { resolveApiUrl } from '../utils/config-store.js'; import { checkKekForEncryption, resolveEncryption } from '../utils/envelope.js'; import { downloadExpoUrl, extractTarGz, findAppBundle, isUrl } from '../utils/expo.js'; @@ -46,31 +45,16 @@ export const uploadCommand = defineCommand({ const apiUrl = resolveApiUrl(args['api-url'] as string | undefined); const appUrl = args['app-url'] as string | undefined; const ignoreShaCheck = Boolean(args['ignore-sha-check']); - // Kept as given, so --no-encrypt is an explicit false and a missing flag - // leaves DCD_ENCRYPT and then the server default to decide. + // Uploads are always encrypted. Read only so --no-encrypt can be + // reported as ignored. const encryptFlag = args.encrypt as boolean | undefined; const debug = Boolean(args.debug); const positional = args.appFile as string | undefined; const auth = await resolveAuth({ apiKeyFlag }); - // Same order as `dcd cloud`, whose compatibility fetch carries the org's - // encryption default. `dcd upload` never needed that data before, so a - // failed fetch leaves the default off rather than failing the upload. - let serverDefault: boolean | undefined; - try { - const compatibilityData = await fetchCompatibilityData(apiUrl, auth); - serverDefault = compatibilityData.encryption?.defaultOn; - } catch (error) { - if (debug) { - out( - `[DEBUG] Failed to fetch compatibility data, so the org's encryption default is off: ${error instanceof Error ? error.message : String(error)}`, - ); - } - } - const encryption = await checkKekForEncryption( - resolveEncryption({ flag: encryptFlag, serverDefault }), + resolveEncryption({ flag: encryptFlag }), apiUrl, ); if (encryption.notice) out(ui.note(encryption.notice)); @@ -112,12 +96,7 @@ export const uploadCommand = defineCommand({ out(ui.section('Uploading app binary')); out( - ui.branch([ - ...ui.fields([['file', colors.highlight(resolvedFile)]]), - ...(encryption.enabled && encryption.source === 'server' - ? [ui.note('Encrypting uploads; opt out with --no-encrypt')] - : []), - ]), + ui.branch(ui.fields([['file', colors.highlight(resolvedFile)]])), ); const appBinaryId = await uploadBinary({ diff --git a/src/config/environments.ts b/src/config/environments.ts index 07b8509..7a9870e 100644 --- a/src/config/environments.ts +++ b/src/config/environments.ts @@ -20,9 +20,9 @@ export interface DcdEnvironment { */ legacyApiUrls?: string[]; frontendUrl: string; + /** Supabase Storage is reached at `${url}/storage/v1/...`. */ supabase: { url: string; - projectRef: string; }; } @@ -32,7 +32,6 @@ export const ENVIRONMENTS: Record = { frontendUrl: 'https://console.devicecloud.dev', supabase: { url: 'https://cloud.devicecloud.dev', - projectRef: 'pgydnphbimetinsgfkbo', }, }, dev: { @@ -41,7 +40,6 @@ export const ENVIRONMENTS: Record = { frontendUrl: 'https://dev.console.devicecloud.dev', supabase: { url: 'https://lbmsowehtjwnqlurpemb.supabase.co', - projectRef: 'lbmsowehtjwnqlurpemb', }, }, }; diff --git a/src/config/flags/binary.flags.ts b/src/config/flags/binary.flags.ts index 96111f3..83a4cfa 100644 --- a/src/config/flags/binary.flags.ts +++ b/src/config/flags/binary.flags.ts @@ -27,6 +27,6 @@ export const binaryFlags = { encrypt: { type: 'boolean', description: - 'Encrypt the app binary, flow zip, and env vars before upload (client-side envelope encryption; each gets its own key). On by default; --no-encrypt or DCD_ENCRYPT=0 turns it off. The binary is still deduplicated across runs, so an unchanged app is not re-uploaded.', + 'No longer needed: the app binary, flow zip and env vars are always encrypted before upload (client-side envelope encryption; each gets its own key). Kept so existing scripts still run. --no-encrypt and DCD_ENCRYPT=0 are ignored with a warning.', }, } as const satisfies ArgsDef; diff --git a/src/config/flags/output.flags.ts b/src/config/flags/output.flags.ts index eeeac3c..b8817a8 100644 --- a/src/config/flags/output.flags.ts +++ b/src/config/flags/output.flags.ts @@ -16,7 +16,7 @@ export const outputFlags = { 'artifacts-path': { type: 'string', description: - 'Custom file path for downloaded artifacts (default: ./artifacts.zip). Requires --download-artifacts.', + 'File path for downloaded artifacts, or a folder to save artifacts.zip in (default: ./artifacts.zip). Requires --download-artifacts.', }, 'junit-path': { type: 'string', diff --git a/src/e2e/index.ts b/src/e2e/index.ts new file mode 100644 index 0000000..febcb7d --- /dev/null +++ b/src/e2e/index.ts @@ -0,0 +1,62 @@ +/** + * `@devicecloud.dev/dcd/e2e`: run e2e (https://github.com/e2e-inc/e2e) tests + * on DeviceCloud devices. + * + * import { mobile } from '@e2e-dev/mobile'; + * import { deviceCloud } from '@devicecloud.dev/dcd/e2e'; + * + * const engine = mobile({ platform: 'android', device: deviceCloud() }); + * + * Each e2e worker gets its own DeviceCloud device session, which shows in the + * console, is recorded, and is billed like any other. With `video` on, each + * test's video is a link to its part of the session in the console. Reads + * `DEVICE_CLOUD_API_KEY` from the run's environment. Early access: the + * organization needs it turned on by DeviceCloud. + * + * Importing this module has no side effects; it does not start the CLI. + */ +import { uploadLocalApp } from '../utils/app-upload.js'; +import { getCliVersion } from '../utils/cli.js'; + +import { + createProvider, + type DeviceCloudOptions, + type DeviceCloudProvider, +} from './provider.js'; + +export type { + DeviceCloudOptions, + DeviceCloudProvider, + E2eDeviceLease, + E2eDeviceRequest, + E2eRecordContext, + E2eRecording, + E2eRecordingResult, + E2eReleaseContext, +} from './provider.js'; + +/** A DeviceCloud device provider, for `mobile({ device })` in an e2e config. */ +export function deviceCloud( + options: DeviceCloudOptions = {}, +): DeviceCloudProvider { + return createProvider(options, { + fetch: (input, init) => fetch(input, init), + pollMs: 3000, + startTimeoutMs: 20 * 60_000, + upload: ({ apiKey, apiUrl, filePath, log }) => + uploadLocalApp({ + apiUrl, + auth: { + headers: { + 'x-app-api-key': apiKey, + 'x-dcd-cli-version': getCliVersion(), + }, + mode: 'apiKey', + }, + filePath, + log, + showProgress: false, + }), + version: getCliVersion(), + }); +} diff --git a/src/e2e/provider.ts b/src/e2e/provider.ts new file mode 100644 index 0000000..96e4a78 --- /dev/null +++ b/src/e2e/provider.ts @@ -0,0 +1,529 @@ +/** + * The DeviceCloud device provider for e2e (https://github.com/e2e-inc/e2e), + * published as `@devicecloud.dev/dcd/e2e`. The public entry point is + * `./index.ts`; this module takes its dependencies as arguments so the unit + * tests can replace the network and the upload. + * + * Each e2e worker slot gets its own DeviceCloud device session. The provider + * starts it, waits until its device is up and the build is installed, then + * asks for the device's engine (`POST /device/sessions/:id/engine`). The + * answer is the address of the session's own agent-device daemon, reached + * through DeviceCloud's relay, and a token for it: that is what an e2e lease + * is. e2e then drives the device directly, so its calls do not pass through + * the API's command queue. `release` stops the session. + * + * When a test records video, `record` gives e2e a link for it instead of a + * file: the session's page in the DeviceCloud console, at that test's part of + * the session's own recording (`?from=&to=`, clock times). The recording is + * one video for the whole session, finished when the session ends, so no + * per-test file exists when the test does. + * + * The types below describe e2e's provider contract (`DeviceProvider` in + * `@e2e-dev/mobile`) by shape, for the fields this provider uses, so the + * package does not depend on e2e. An object of this type can be passed to + * `mobile({ device })`. + */ +import { checkApiUrl } from '../utils/api-url.js'; + +/** What e2e asks for: one device for one worker slot of a run. */ +export interface E2eDeviceRequest { + readonly platform: 'android' | 'ios'; + /** The agent-device version the e2e client speaks. */ + readonly agentDeviceVersion: string; + /** The target's `app.bundleId`, when the config names one. */ + readonly app?: string | undefined; + /** The target's `app.appPath`, resolved to an absolute path, when the config names one. */ + readonly appPath?: string | undefined; + /** The run's environment. A provider reads its credentials from here, never `process.env`. */ + readonly env: Readonly>; + /** Aborts when the run is interrupted. */ + readonly signal: AbortSignal; + /** One line of progress in the run's output. */ + readonly log: (line: string) => void; +} + +/** One leased device, as `acquire` returns it and `release` gets it back. */ +export interface E2eDeviceLease { + /** The device session's id. */ + readonly id: string; + readonly daemon?: + { readonly authToken: string; readonly baseUrl: string } | undefined; + readonly deviceId?: string | undefined; + /** The bundle id or package of the build this provider installed from the request's `appPath`. */ + readonly installedApp?: string | undefined; +} + +/** Handed to `release`, once per lease at the end of the run. */ +export interface E2eReleaseContext { + readonly env: Readonly>; + readonly signal: AbortSignal; + readonly log: (line: string) => void; +} + +/** Handed to `record`, once per test attempt that records video. */ +export interface E2eRecordContext { + readonly attemptId: string; + readonly env: Readonly>; + readonly runId: string; + readonly signal: AbortSignal; + readonly targetName: string; +} + +/** What a stopped recording became: here always a link, with its media type. */ +export interface E2eRecordingResult { + readonly mediaType: string; + readonly url: string; +} + +/** A test attempt's recording, as `record` starts it (`ProviderRecording` in `@e2e-dev/core/engine`). */ +export interface E2eRecording { + /** When it started, as an ISO time. */ + readonly startedAt: string; + stop(context: { + readonly dir: string; + readonly signal: AbortSignal; + }): Promise; +} + +/** A source of DeviceCloud devices for e2e, the shape of `@e2e-dev/mobile`'s `DeviceProvider`. */ +export interface DeviceCloudProvider { + readonly name: string; + acquire(request: E2eDeviceRequest): Promise; + /** A test attempt's video: a console link to its part of the session's recording. */ + record( + lease: E2eDeviceLease, + context: E2eRecordContext, + ): Promise; + release(lease: E2eDeviceLease, context: E2eReleaseContext): Promise; +} + +export interface DeviceCloudOptions { + /** + * The DeviceCloud API key. Without it, `DEVICE_CLOUD_API_KEY` from the run's + * environment. The key needs access to device sessions. + */ + apiKey?: string; + /** The DeviceCloud API. Without it, `DCD_API_URL` from the run's environment, then https://api.devicecloud.dev. */ + apiUrl?: string; + /** + * A build already uploaded (the id `dcd upload` prints). Without it, the + * provider uploads the target's `app.appPath`, when the config names one, + * once per run. Either way the session installs the build, and e2e + * installs nothing itself. + */ + appBinaryId?: string; + /** Device model, as `GET /device/models` lists them. The platform's default without. */ + model?: string; + /** OS version for that model. Its default without. */ + os?: string; + /** How long each session may last, in minutes. The organization's limit without. */ + maxDurationMin?: number; + /** + * The device's locale, as `en_US` or `en-US`: set before the build is + * installed or opened. The device's own default without. + */ + locale?: string; +} + +/** What the provider calls out to: the network, the upload, and the clock. */ +export interface ProviderDeps { + fetch: typeof fetch; + /** Uploads a local build the way `dcd upload` does and answers its binary id. */ + upload: (args: { + apiKey: string; + apiUrl: string; + filePath: string; + log: (line: string) => void; + }) => Promise; + /** Sent as `x-dcd-cli-version`, so the API knows which provider version called. */ + version: string; + /** Between polls. */ + pollMs: number; + /** How long a session may take to be ready: queued, starting, installing. */ + startTimeoutMs: number; + /** The clock, in ms. `Date.now` without. */ + now?: () => number; +} + +const DEFAULT_API_URL = 'https://api.devicecloud.dev'; +const ENDED = new Set(['expired', 'failed', 'released']); +/** How many times to ask for the engine while the device is up but not quite ready for it (425). */ +const ENGINE_ATTEMPTS = 10; +/** + * How many times a request that is safe to repeat is sent again after the + * network failed it (no answer at all). Polls run for minutes, and one lost + * request must not end a run. Never a session start: sent twice, it could + * start two sessions. + */ +const NETWORK_RETRIES = 4; + +interface SessionBlock { + id: string; + install?: { error?: null | string; status?: string } | null; + monitor_url?: string; + release_reason?: null | string; + state: string; +} + +interface EngineBlock { + agentDeviceVersion?: string; + daemon: { authToken: string; baseUrl: string }; + deviceId: string; +} + +interface Reply { + json: Record | null; + status: number; + text: string; +} + +const wait = (ms: number, signal: AbortSignal | undefined) => + new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(signal.reason ?? new Error('Interrupted')); + return; + } + + const onAbort = () => { + clearTimeout(timer); + reject(signal?.reason ?? new Error('Interrupted')); + }; + + const timer = setTimeout(() => { + signal?.removeEventListener('abort', onAbort); + resolve(); + }, ms); + signal?.addEventListener('abort', onAbort, { once: true }); + }); + +/** The API's own words for a failed request: its message, or the start of the body. */ +function failure(what: string, reply: Reply): Error { + const message = reply.json?.message; + const said = Array.isArray(message) + ? message.join('; ') + : String(message ?? reply.text).slice(0, 300); + const code = + typeof reply.json?.error === 'string' && reply.json.error !== said + ? ` (${reply.json.error})` + : ''; + return new Error( + `DeviceCloud: ${what} answered ${reply.status}: ${said}${code}`, + ); +} + +/** Where to send requests, and with which key: checked before the key goes anywhere. */ +function connection( + options: DeviceCloudOptions, + env: Readonly>, + log: (line: string) => void, +): { apiKey: string; apiUrl: string } { + const apiKey = (options.apiKey ?? env.DEVICE_CLOUD_API_KEY ?? '').trim(); + if (!apiKey) { + throw new Error( + 'DeviceCloud: no API key. Set DEVICE_CLOUD_API_KEY in the environment e2e runs with, or pass apiKey to deviceCloud().', + ); + } + + const raw = + (options.apiUrl ?? env.DCD_API_URL ?? '').trim() || DEFAULT_API_URL; + const check = checkApiUrl(raw); + if (!check.ok) throw new Error(`DeviceCloud: ${check.reason}`); + if (check.warning) log(check.warning); + return { apiKey, apiUrl: check.origin }; +} + +/** A locale as the API takes it, `en_US`, from that or `en-US`. */ +const LOCALE = /^[a-z]{2,3}_[A-Z]{2}$/; + +function deviceLocale(locale: string | undefined): string | undefined { + if (locale === undefined) return undefined; + const normalised = locale.trim().replace('-', '_'); + if (!LOCALE.test(normalised)) { + throw new Error( + `DeviceCloud: "${locale}" is not a locale. Use a language and region, such as en_US or en-US.`, + ); + } + + return normalised; +} + +export function createProvider( + options: DeviceCloudOptions, + deps: ProviderDeps, +): DeviceCloudProvider { + // Checked when the config is read, before any session is started or billed. + const locale = deviceLocale(options.locale); + // One upload per build per run: e2e acquires every worker slot at once. + const uploads = new Map>(); + const now = deps.now ?? Date.now; + // Each lease's page in the console, read once per worker process: e2e + // records in the worker, which has the lease's id but not the session. + const pages = new Map>(); + + const client = + (apiKey: string, apiUrl: string) => + async ( + method: 'DELETE' | 'GET' | 'POST', + path: string, + body?: unknown, + signal?: AbortSignal, + { repeatable = method !== 'POST' }: { repeatable?: boolean } = {}, + ): Promise => { + let response: Response; + for (let attempt = 0; ; attempt++) { + try { + response = await deps.fetch(`${apiUrl}${path}`, { + headers: { + 'x-app-api-key': apiKey, + 'x-dcd-cli-version': deps.version, + 'x-dcd-source': 'cli', + ...(body === undefined + ? {} + : { 'content-type': 'application/json' }), + }, + method, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + ...(signal ? { signal } : {}), + }); + break; + } catch (error) { + if (signal?.aborted) throw signal.reason ?? error; + if (!repeatable || attempt >= NETWORK_RETRIES) { + const cause = ( + error as { cause?: { code?: string; message?: string } } + ).cause; + const why = + cause?.code ?? cause?.message ?? (error as Error).message; + throw new Error( + `DeviceCloud: ${method} ${path} could not reach ${apiUrl} (${why})`, + { cause: error }, + ); + } + + await wait(deps.pollMs * (attempt + 1), signal); + } + } + + const text = await response.text(); + let json: null | Record = null; + try { + json = JSON.parse(text) as Record; + } catch { + // Not JSON: the status and the text say what happened. + } + + return { json, status: response.status, text }; + }; + + const binaryFor = async ( + request: E2eDeviceRequest, + apiKey: string, + apiUrl: string, + ): Promise => { + if (options.appBinaryId) { + if (request.appPath) + request.log( + `installing build ${options.appBinaryId}, not uploading ${request.appPath}`, + ); + return options.appBinaryId; + } + + if (!request.appPath) return undefined; + let upload = uploads.get(request.appPath); + if (!upload) { + request.log(`uploading ${request.appPath}`); + upload = deps.upload({ + apiKey, + apiUrl, + filePath: request.appPath, + log: request.log, + }); + uploads.set(request.appPath, upload); + // A failed upload is tried again by the next run, not remembered. + upload.catch(() => uploads.delete(request.appPath!)); + } + + return upload; + }; + + return { + async acquire(request) { + // e2e cannot install a build on a DeviceCloud device; the session does. + // e2e is told so (installedApp), which needs the build's bundle id. + if (request.appPath && !request.app) { + throw new Error( + "DeviceCloud: the target names app.appPath but not app.bundleId. Set app.bundleId to the build's bundle id or package name.", + ); + } + + const { apiKey, apiUrl } = connection(options, request.env, request.log); + const api = client(apiKey, apiUrl); + const binaryUploadId = await binaryFor(request, apiKey, apiUrl); + + const started = await api( + 'POST', + '/device/sessions', + { + clientLabel: 'e2e', + platform: request.platform, + ...(binaryUploadId ? { binaryUploadId } : {}), + ...(options.model ? { model: options.model } : {}), + ...(options.os ? { os: options.os } : {}), + ...(options.maxDurationMin + ? { maxDurationMin: options.maxDurationMin } + : {}), + ...(locale ? { deviceLocale: locale } : {}), + }, + request.signal, + ); + if (started.status >= 300 || !started.json?.session) + throw failure('starting a device session', started); + let session = started.json.session as SessionBlock; + const path = `/device/sessions/${encodeURIComponent(session.id)}`; + // A session left running is billed until it idles out. + const stop = () => api('DELETE', path).catch(() => {}); + + try { + if (session.monitor_url) request.log(`watch at ${session.monitor_url}`); + // Queued, then starting, then installing: minutes when the fleet is busy. + const deadline = Date.now() + deps.startTimeoutMs; + for (;;) { + if (ENDED.has(session.state)) { + throw new Error( + `DeviceCloud: session ${session.id} ended before it was ready (${session.release_reason ?? session.state})`, + ); + } + + if (session.install?.status === 'failed') { + throw new Error( + `DeviceCloud: the build could not be installed on session ${session.id}: ${session.install.error ?? 'no reason given'}`, + ); + } + + if ( + (session.state === 'ready' || session.state === 'active') && + session.install?.status !== 'installing' + ) + break; + if (Date.now() > deadline) { + throw new Error( + `DeviceCloud: session ${session.id} was not ready within ${Math.round(deps.startTimeoutMs / 60_000)} minutes`, + ); + } + + await wait(deps.pollMs, request.signal); + const read = await api('GET', path, undefined, request.signal); + if (read.status >= 300 || !read.json?.session) + throw failure('reading the device session', read); + session = read.json.session as SessionBlock; + } + + // The device is up; its engine may need a moment more (425). + let engine: EngineBlock | null = null; + for (let attempt = 0; attempt < ENGINE_ATTEMPTS && !engine; attempt++) { + // Asking again is safe: the session has one engine, and every answer names it. + const asked = await api( + 'POST', + `${path}/engine`, + {}, + request.signal, + { repeatable: true }, + ); + if (asked.status === 425) { + await wait(deps.pollMs, request.signal); + continue; + } + + if (asked.status >= 300 || !asked.json?.engine) + throw failure("asking for the device's engine", asked); + engine = asked.json.engine as EngineBlock; + } + + if (!engine) + throw new Error( + `DeviceCloud: session ${session.id} never became ready for e2e`, + ); + if ( + engine.agentDeviceVersion && + engine.agentDeviceVersion !== request.agentDeviceVersion + ) { + // Same wire protocol; said so that a difference can be read off a report. + request.log( + `the device runs agent-device ${engine.agentDeviceVersion}, this e2e ${request.agentDeviceVersion}`, + ); + } + + return { + daemon: engine.daemon, + deviceId: engine.deviceId, + id: session.id, + // Only when the target names a build (appPath): the session installed one, so e2e installs nothing. + ...(request.appPath ? { installedApp: request.app } : {}), + }; + } catch (error) { + await stop(); + throw error; + } + }, + + name: 'devicecloud', + + async record(lease, context) { + // The test starts once this returns: from now on is its part. + const startedAt = new Date(now()).toISOString(); + let page = pages.get(lease.id); + if (!page) { + page = (async () => { + const { apiKey, apiUrl } = connection(options, context.env, () => {}); + const read = await client(apiKey, apiUrl)( + 'GET', + `/device/sessions/${encodeURIComponent(lease.id)}`, + undefined, + context.signal, + ); + if (read.status >= 300 || !read.json?.session) + throw failure(`reading device session ${lease.id}`, read); + const { monitor_url: monitorUrl } = read.json.session as SessionBlock; + if (!monitorUrl) + throw new Error( + `DeviceCloud: session ${lease.id} has no console page to link a test's video to`, + ); + return monitorUrl; + })(); + pages.set(lease.id, page); + // A failed read is tried again by the next attempt, not remembered. + page.catch(() => pages.delete(lease.id)); + } + + const monitorUrl = await page; + return { + startedAt, + // No request here: stopping can't fail once the test is over. + async stop() { + const url = new URL(monitorUrl); + url.searchParams.set('from', startedAt); + url.searchParams.set('to', new Date(now()).toISOString()); + return { mediaType: 'text/html', url: url.href }; + }, + }; + }, + + async release(lease, context) { + const { apiKey, apiUrl } = connection(options, context.env, context.log); + const stopped = await client(apiKey, apiUrl)( + 'DELETE', + `/device/sessions/${encodeURIComponent(lease.id)}`, + undefined, + context.signal, + ); + // 404 and 409: already gone, which is what was asked for. + if ( + stopped.status >= 300 && + stopped.status !== 404 && + stopped.status !== 409 + ) { + throw failure(`stopping device session ${lease.id}`, stopped); + } + }, + }; +} diff --git a/src/gateways/api-gateway.ts b/src/gateways/api-gateway.ts index ef65682..a5d1e43 100644 --- a/src/gateways/api-gateway.ts +++ b/src/gateways/api-gateway.ts @@ -1,6 +1,5 @@ import { createWriteStream, mkdirSync } from 'node:fs'; import { rm } from 'node:fs/promises'; -import { homedir } from 'node:os'; import * as path from 'node:path'; import { Readable } from 'node:stream'; import { pipeline } from 'node:stream/promises'; @@ -20,13 +19,10 @@ import type { } from '../types/domain/live.types.js'; import type { TeamSettings } from '../types/domain/team-settings.types.js'; import { components, paths } from '../types/generated/schema.types.js'; +import type { SignedUpload } from './supabase-gateway.js'; +import { expandHome } from '../utils/paths.js'; import { assertCompleteZip, IncompleteZipError } from '../utils/zip-integrity.js'; -/** Expand a leading `~` to the home directory, as the download paths allow. */ -function expandHome(p: string): string { - return p.replace(/^~(?=$|\/|\\)/, homedir()); -} - /** Extra checks a bundle download makes before it trusts the manifest. */ interface BundleDownloadOptions { /** @@ -35,9 +31,24 @@ interface BundleDownloadOptions { * tells an API that applied the filter from an older one that ignored it. */ requiredFilenamePrefix?: string; + /** + * Throws the error the inline route gives for the same answer. Called for a + * manifest status in {@link FINAL_MANIFEST_STATUSES} instead of falling + * back, so the caller's message is the one the user saw before. + */ + throwFinalError?: (res: Response) => Promise; unsupportedMessage?: string; } +/** + * Manifest answers the inline route would only repeat: a bad request, a key + * that can't reach the run, a run that isn't there. Falling back on them cost + * a second request for the same error. 413 (too many files for the bundle) + * and 501 (no bundle delivery here) still fall back, since the inline route + * can serve those. + */ +const FINAL_MANIFEST_STATUSES: ReadonlySet = new Set([400, 403, 404]); + /** What went wrong in a bundle attempt, minus the route/timing added later. */ type BundleFailure = Omit< BundleFallbackTelemetry, @@ -59,6 +70,16 @@ function errorDetail(error: unknown): Pick< }; } +/** + * A Node file-system error (EACCES, ENOSPC, EISDIR…) on the local side of a + * download. These name a `syscall` and a `path`; network errors from fetch + * carry neither. + */ +function isLocalFileError(error: unknown): boolean { + const e = error as { path?: unknown; syscall?: unknown } | null; + return typeof e?.syscall === 'string' && typeof e?.path === 'string'; +} + function failure( reason: BundleFallbackReason, extra: Omit = {}, @@ -125,6 +146,15 @@ export interface ResultsPollCache { etag?: string; } +/** + * An upload-URL response. `signedUpload` comes only from an API that supports + * direct uploads, and only when the request asked for it; without it the + * client uploads to `tempPath`. + */ +type UploadUrlResponse = components['schemas']['IGetBinaryUploadUrlResponse'] & { + signedUpload?: SignedUpload; +}; + export const ApiGateway = { /** * Enhances generic "fetch failed" errors with more specific diagnostic information @@ -295,8 +325,8 @@ export const ApiGateway = { * the bundle path is unavailable or anything about it doesn't pan out — a * `501` (deployment doesn't offer it), a non-OK manifest response, a body * that isn't a manifest, or a delivery-service error — so the caller can fall - * back to the inline download endpoint. Definitive errors (e.g. not found) - * surface through that inline path instead. + * back to the inline download endpoint. A manifest 400, 403 or 404 throws + * `throwFinalError`'s error instead, without a fallback. */ async tryBundleDownload( baseUrl: string, @@ -352,9 +382,16 @@ export const ApiGateway = { return failure('manifest_request_failed', errorDetail(error)); } - // 501 => this deployment has no bundle delivery; any other non-OK => let - // the inline path re-request and surface the real error. + // 400/403/404 => the inline route would answer the same, so throw its + // error now. 501 => this deployment has no bundle delivery; any other + // non-OK (413, 5xx) => the inline path may still deliver. if (!manifestRes.ok) { + if ( + options.throwFinalError && + FINAL_MANIFEST_STATUSES.has(manifestRes.status) + ) { + await options.throwFinalError(manifestRes); + } return failure( manifestRes.status === 501 ? 'manifest_unavailable' : 'manifest_http_error', { status: manifestRes.status }, @@ -422,6 +459,10 @@ export const ApiGateway = { operation, ); } catch (error) { + // The destination can't be written (a permission, a full disk): the + // inline path would hit the same wall, after making the API build the + // whole ZIP. Report it as it is instead of falling back. + if (isLocalFileError(error)) throw error; return failure('bundle_stream_failed', { ...errorDetail(error), bytes_received: bytesReceived, @@ -549,14 +590,18 @@ export const ApiGateway = { (filtered ? `&resultId=${resultId}` : ''), artifactsPath, 'Failed to download artifacts', - filtered - ? { - // What the API names a bundle it narrowed to one result. - requiredFilenamePrefix: 'artifacts-result-', - unsupportedMessage: - 'Failed to download artifacts: this API does not support downloading one result yet. Download without --result-id or --flow.', - } - : {}, + { + throwFinalError: (res) => + this.handleApiError(res, 'Failed to download artifacts'), + ...(filtered + ? { + // What the API names a bundle it narrowed to one result. + requiredFilenamePrefix: 'artifacts-result-', + unsupportedMessage: + 'Failed to download artifacts: this API does not support downloading one result yet. Download without --result-id or --flow.', + } + : {}), + }, ) ) { return; @@ -607,8 +652,13 @@ export const ApiGateway = { */ shaPlain?: string; supabaseSuccess: boolean; + /** + * True when `path` is the final path a signed token uploaded to. The API + * then checks the object is there and skips its copy. + */ + useTus?: boolean; }) { - const { baseUrl, auth, id, metadata, path, sha, shaPlain, supabaseSuccess, backblazeSuccess, bytes } = config; + const { baseUrl, auth, id, metadata, path, sha, shaPlain, supabaseSuccess, backblazeSuccess, bytes, useTus } = config; try { const res = await fetch(`${baseUrl}/uploads/finaliseUpload`, { body: JSON.stringify({ @@ -616,10 +666,11 @@ export const ApiGateway = { bytes, id, metadata, - path, // This is tempPath for TUS uploads + path, // tempPath, or the signed final path when useTus is set ...(sha ? { sha } : {}), ...(shaPlain ? { shaPlain } : {}), supabaseSuccess, + ...(useTus ? { useTus } : {}), }), headers: { 'content-type': 'application/json', @@ -651,7 +702,9 @@ export const ApiGateway = { ) { try { const res = await fetch(`${baseUrl}/uploads/getBinaryUploadUrl`, { - body: JSON.stringify({ platform, fileSize }), + // signedUpload: ask for a token to upload straight to the final + // path. An API without direct uploads ignores the field. + body: JSON.stringify({ platform, fileSize, signedUpload: true }), headers: { 'content-type': 'application/json', ...auth.headers, @@ -662,9 +715,7 @@ export const ApiGateway = { await this.handleApiError(res, 'Failed to get upload URL'); } - return await parseJsonResponse< - paths['/uploads/getBinaryUploadUrl']['post']['responses']['201']['content']['application/json'] - >(res, 'Failed to get upload URL'); + return await parseJsonResponse(res, 'Failed to get upload URL'); } catch (error) { if (error instanceof TypeError && error.message === 'fetch failed') { throw this.enhanceFetchError(error, `${baseUrl}/uploads/getBinaryUploadUrl`); @@ -972,7 +1023,7 @@ export const ApiGateway = { ) { try { const res = await fetch(`${baseUrl}/uploads/getFlowUploadUrl`, { - body: JSON.stringify({ fileSize, useTus: true }), + body: JSON.stringify({ fileSize, signedUpload: true, useTus: true }), headers: { 'content-type': 'application/json', ...auth.headers, @@ -983,10 +1034,8 @@ export const ApiGateway = { await this.handleApiError(res, 'Failed to get flow upload URL'); } - // Same response shape as getBinaryUploadUrl: { id, tempPath, finalPath, path, b2?, token? }. - return await parseJsonResponse< - components['schemas']['IGetBinaryUploadUrlResponse'] - >(res, 'Failed to get flow upload URL'); + // Same response shape as getBinaryUploadUrl. + return await parseJsonResponse(res, 'Failed to get flow upload URL'); } catch (error) { if (error instanceof TypeError && error.message === 'fetch failed') { throw this.enhanceFetchError(error, `${baseUrl}/uploads/getFlowUploadUrl`); @@ -996,6 +1045,39 @@ export const ApiGateway = { } }, + /** + * A fresh signed upload token for a path an upload-URL response gave us, + * so an upload whose token expired can carry on. The API refuses a path + * outside the caller's org and an upload that is already finalised. + */ + async refreshUploadToken(baseUrl: string, auth: AuthContext, path: string): Promise { + try { + const res = await fetch(`${baseUrl}/uploads/refreshUploadToken`, { + body: JSON.stringify({ path }), + headers: { + 'content-type': 'application/json', + ...auth.headers, + }, + method: 'POST', + }); + if (!res.ok) { + await this.handleApiError(res, 'Failed to refresh upload token'); + } + + const { signedUpload } = await parseJsonResponse<{ signedUpload: SignedUpload }>( + res, + 'Failed to refresh upload token', + ); + return signedUpload; + } catch (error) { + if (error instanceof TypeError && error.message === 'fetch failed') { + throw this.enhanceFetchError(error, `${baseUrl}/uploads/refreshUploadToken`); + } + + throw error; + } + }, + /** * Submits a flow test that references an already-uploaded zip (JSON body, no * multipart). The response is identical to the legacy `POST /uploads/flow`. @@ -1144,6 +1226,17 @@ export const ApiGateway = { const finalReportPath = reportPath || path.resolve(process.cwd(), defaultFilename); const url = `${baseUrl}${endpoint}`; + // The error for a non-OK answer, from the inline route or, for the html + // report, a final answer from its bundle route. + const throwHttpError = async (res: Response): Promise => { + const errorText = await res.text(); + if (res.status === 404) { + throw new Error(notFoundMessage); + } + + throw new Error(`${errorPrefix}: ${res.status} ${errorText}`); + }; + // The HTML report is a ZIP bundle; prefer bundle delivery when available. // (junit is a single small file and allure has its own endpoint — both stay // on the inline path.) @@ -1155,6 +1248,7 @@ export const ApiGateway = { `/results/${uploadId}/report-bundle`, finalReportPath, errorPrefix, + { throwFinalError: throwHttpError }, )) ) { return; @@ -1170,12 +1264,7 @@ export const ApiGateway = { }); if (!res.ok) { - const errorText = await res.text(); - if (res.status === 404) { - throw new Error(notFoundMessage); - } - - throw new Error(`${errorPrefix}: ${res.status} ${errorText}`); + await throwHttpError(res); } await this.streamResponseToFile(res, finalReportPath, errorPrefix); diff --git a/src/gateways/fetch-http-stack.ts b/src/gateways/fetch-http-stack.ts new file mode 100644 index 0000000..928b85c --- /dev/null +++ b/src/gateways/fetch-http-stack.ts @@ -0,0 +1,130 @@ +import { Readable } from 'node:stream'; + +import type { HttpRequest, HttpResponse, HttpStack } from 'tus-js-client'; + +/** + * A tus `HttpStack` that sends each request with `fetch` and a fully-read body. + * + * tus-js-client's default Node stack pipes the chunk into a `node:http` + * request. Under Bun (the standalone `dcd` binary is `bun build --compile`d), + * that fails on the upload-creating POST with "The socket connection was + * closed unexpectedly", so every Storage upload from the binary failed while + * the npm package, on Node, worked. Bun's own `fetch` sends the same request + * fine, so the binary uses this stack instead (see `tusHttpStack`). + * + * Each body is read into memory before it is sent. tus sends at most one + * chunk per request (6 MB for Supabase), so that is one chunk at a time. + * `fetch` can't report upload progress, so progress moves once per chunk. + */ +export class FetchHttpStack implements HttpStack { + createRequest(method: string, url: string): HttpRequest { + return new FetchHttpRequest(method, url); + } + + getName(): string { + return 'FetchHttpStack'; + } +} + +class FetchHttpRequest implements HttpRequest { + private readonly controller = new AbortController(); + private readonly headers: Record = {}; + private progress: (bytesSent: number) => void = () => {}; + + constructor( + private readonly method: string, + private readonly url: string, + ) {} + + getMethod(): string { + return this.method; + } + + getURL(): string { + return this.url; + } + + setHeader(header: string, value: string): void { + this.headers[header] = value; + } + + getHeader(header: string): string | undefined { + return this.headers[header]; + } + + setProgressHandler(handler: (bytesSent: number) => void): void { + this.progress = handler; + } + + async send(body?: unknown): Promise { + const data = await readBody(body); + const res = await fetch(this.url, { + method: this.method, + headers: this.headers, + body: data, + signal: this.controller.signal, + }); + if (data) this.progress(data.byteLength); + const text = await res.text(); + return new FetchHttpResponse(res, text); + } + + abort(): Promise { + this.controller.abort(); + return Promise.resolve(); + } + + getUnderlyingObject(): unknown { + return this.controller; + } +} + +class FetchHttpResponse implements HttpResponse { + constructor( + private readonly res: Response, + private readonly body: string, + ) {} + + getStatus(): number { + return this.res.status; + } + + getHeader(header: string): string | undefined { + return this.res.headers.get(header) ?? undefined; + } + + getBody(): string { + return this.body; + } + + getUnderlyingObject(): unknown { + return this.res; + } +} + +/** The slice tus hands to `send`: nothing, a Buffer, or a file ReadStream. */ +async function readBody(body: unknown): Promise | undefined> { + if (body === null || body === undefined) return undefined; + // A Node Buffer slice, always backed by an ArrayBuffer (not a shared one). + if (body instanceof Uint8Array) return body as Uint8Array; + if (body instanceof Readable) { + const parts: Buffer[] = []; + for await (const part of body) { + parts.push(typeof part === 'string' ? Buffer.from(part) : (part as Buffer)); + } + return Buffer.concat(parts); + } + throw new TypeError(`FetchHttpStack can't send a body of type ${typeof body}`); +} + +/** + * tus options that pick the HTTP stack: `FetchHttpStack` under Bun, and no + * key at all under Node, so tus keeps its default stack (what the npm package + * has always used). It must be no key, not `httpStack: undefined`: tus spreads + * the options over its defaults, so an `undefined` would replace the default. + */ +export function tusHttpStackOptions( + isBun = 'bun' in process.versions, +): { httpStack?: HttpStack } { + return isBun ? { httpStack: new FetchHttpStack() } : {}; +} diff --git a/src/gateways/supabase-gateway.ts b/src/gateways/supabase-gateway.ts index c37efa7..c2e9459 100644 --- a/src/gateways/supabase-gateway.ts +++ b/src/gateways/supabase-gateway.ts @@ -1,10 +1,10 @@ import { createReadStream } from 'node:fs'; -import { createClient } from '@supabase/supabase-js'; import * as tus from 'tus-js-client'; import { ENVIRONMENTS, type DcdEnvName } from '../config/environments.js'; import { getSupabaseKey, supabaseKeyHeaders } from '../config/supabase-key.js'; +import { tusHttpStackOptions } from './fetch-http-stack.js'; /** Disk-backed upload descriptor — see UploadSource in src/methods.ts. */ export interface ResumableUploadSource { @@ -14,32 +14,137 @@ export interface ResumableUploadSource { size: number; } +/** + * A signed upload for one storage path, from the API's upload-URL response. + * The token is sent as `x-signature` on every TUS request; it writes only + * `path` and never overwrites an existing object. + */ +export interface SignedUpload { + expiresInSeconds: number; + path: string; + token: string; +} + +/** Refresh this long before the token says it expires. */ +const REFRESH_MARGIN_MS = 10 * 60 * 1000; +/** Fresh tokens one upload may ask for before it gives up. */ +const MAX_TOKEN_REFRESHES = 5; +const RETRY_DELAYS = [0, 3000, 5000, 10_000, 20_000]; + +/** + * Whether a TUS error response says the upload token was refused, which a + * fresh token for the same path fixes. Storage answers with a 400 whose body + * is the verifier's message, and those name no single word. Seen or expected: + * - "Invalid signature" (wrong path, or a tampered token) + * - "Invalid Compact JWS" (a token that is not a JWT at all) + * - `"exp" claim timestamp check failed` (an expired token: the JWT library + * checks expiry before Storage's own "The provided token has expired.") + */ +const SIGNATURE_ERROR = /jwt|jws|signature|expired|"exp" claim/i; + +export function isSignatureError(status: number, body: string): boolean { + return [400, 401, 403].includes(status) && SIGNATURE_ERROR.test(body); +} + +/** tus's own rule: retry anything but a 4xx, except 409 and 423. */ +function defaultShouldRetry(status: number): boolean { + return !(status >= 400 && status < 500) || status === 409 || status === 423; +} + export class SupabaseGateway { /** - * Upload to Supabase using resumable uploads (TUS protocol) - * Uploads to staging location (uploads/{id}/) using the publishable key - * File is later moved to final location by API after finalization - * @param env - Environment (dev or prod) - * @param path - Staging storage path (uploads/{id}/file.ext) - * @param source - Upload source descriptor; the file is streamed from disk - * @param debug - Enable debug logging - * @param onProgress - Optional callback for upload progress (bytesUploaded, bytesTotal) - * @returns Promise that resolves when upload completes + * Upload straight to the final storage path with a signed token, through + * `/storage/v1/upload/resumable/sign`. No storage key of the client's own + * is needed: the token is the permission. + * + * The token lasts a couple of hours and storage checks it on every + * request, so a long or resumed upload can outlive it. Before each request + * the token is refreshed when it is close to expiry, and a request refused + * for its signature is retried with a fresh one. Either way it is the same + * path, so the same TUS upload carries on. + * + * @param refreshToken - Asks the API for a fresh token for `signed.path` + * @param options.storageUrl - Test seam; defaults to the environment's URL */ - static async uploadResumable( + static async uploadResumableSigned( env: DcdEnvName, - path: string, + signed: SignedUpload, source: ResumableUploadSource, + refreshToken: (path: string) => Promise, debug = false, - onProgress?: (bytesUploaded: number, bytesTotal: number) => void, + options: { retryDelays?: number[]; storageUrl?: string } = {}, ): Promise { - const { projectRef } = ENVIRONMENTS[env].supabase; + const storageUrl = options.storageUrl ?? ENVIRONMENTS[env].supabase.url; const supabaseKey = await getSupabaseKey(env); - const storageUrl = `https://${projectRef}.storage.supabase.co`; + + let { token } = signed; + let expiresAt = Date.now() + signed.expiresInSeconds * 1000; + let stale = false; + let refreshes = 0; + let pending: Promise | undefined; + + const margin = Math.min(REFRESH_MARGIN_MS, (signed.expiresInSeconds * 1000) / 2); + const refresh = (): Promise => { + pending ??= (async () => { + refreshes += 1; + if (debug) console.log(`[DEBUG] Refreshing the upload token for ${signed.path}`); + const fresh = await refreshToken(signed.path); + token = fresh.token; + expiresAt = Date.now() + fresh.expiresInSeconds * 1000; + stale = false; + })().finally(() => { + pending = undefined; + }); + return pending; + }; + + await this.runTusUpload({ + debug, + endpoint: `${storageUrl}/storage/v1/upload/resumable/sign`, + // The gateway in front of Storage routes on the key; the token is the + // permission, and the upload is checked against it, not the key. + headers: supabaseKeyHeaders(supabaseKey), + async onBeforeRequest(req) { + if (stale || Date.now() >= expiresAt - margin) { + await refresh(); + } + + req.setHeader('x-signature', token); + }, + onShouldRetry(err) { + const status = err.originalResponse?.getStatus() ?? 0; + const body = err.originalResponse?.getBody() ?? ''; + if (isSignatureError(status, body)) { + if (refreshes >= MAX_TOKEN_REFRESHES) return false; + stale = true; + return true; + } + + return defaultShouldRetry(status); + }, + path: signed.path, + retryDelays: options.retryDelays ?? RETRY_DELAYS, + source, + }); + } + + /** One TUS upload of `source` to `path` in the organizations bucket. */ + private static runTusUpload(config: { + debug: boolean; + endpoint: string; + headers: Record; + onBeforeRequest?: (req: tus.HttpRequest) => Promise | void; + onProgress?: (bytesUploaded: number, bytesTotal: number) => void; + onShouldRetry?: (err: tus.DetailedError) => boolean; + path: string; + retryDelays: number[]; + source: ResumableUploadSource; + }): Promise { + const { debug, endpoint, headers, onBeforeRequest, onProgress, onShouldRetry, path, retryDelays, source } = config; if (debug) { console.log(`[DEBUG] Resumable upload starting...`); - console.log(`[DEBUG] Storage URL: ${storageUrl}`); + console.log(`[DEBUG] Endpoint: ${endpoint}`); console.log(`[DEBUG] Upload path: ${path}`); console.log(`[DEBUG] File name: ${source.name}`); console.log(`[DEBUG] File size: ${(source.size / 1024 / 1024).toFixed(2)} MB`); @@ -52,18 +157,14 @@ export class SupabaseGateway { const upload = new tus.Upload(createReadStream(source.diskPath), { uploadSize: source.size, - // TUS endpoint for Supabase Storage - endpoint: `${storageUrl}/storage/v1/upload/resumable`, - - // Retry configuration - will retry 5 times with increasing delays - retryDelays: [0, 3000, 5000, 10_000, 20_000], + // Bun's node:http can't send tus's create request; see FetchHttpStack. + ...tusHttpStackOptions(), - // Authentication and headers - // Publishable key for staging uploads to uploads/* folder - headers: { - ...supabaseKeyHeaders(supabaseKey), - 'x-upsert': 'true', // Allow overwriting existing files - }, + endpoint, + retryDelays, + headers, + ...(onBeforeRequest ? { onBeforeRequest } : {}), + ...(onShouldRetry ? { onShouldRetry } : {}), // Upload metadata metadata: { @@ -131,137 +232,41 @@ export class SupabaseGateway { }); } - static async uploadToSignedUrl( - env: DcdEnvName, - path: string, - token: string, - file: File, - debug = false, - ) { - const { url: SUPABASE_URL } = ENVIRONMENTS[env].supabase; - - if (debug) { - console.log(`[DEBUG] Supabase upload starting...`); - console.log(`[DEBUG] Supabase URL: ${SUPABASE_URL}`); - console.log(`[DEBUG] Upload path: ${path}`); - console.log(`[DEBUG] File name: ${file.name}`); - console.log(`[DEBUG] File type: ${file.type}`); - } - - try { - const supabase = createClient(SUPABASE_URL, await getSupabaseKey(env)); - const uploadToUrl = await supabase.storage - .from('organizations') - .uploadToSignedUrl(path, token, file); - - if (uploadToUrl.error) { - const error = uploadToUrl.error as - | { message?: string; statusCode?: number | string } - | string; - const errorMessage = - typeof error === 'string' ? error : error?.message || 'Upload failed'; - - if (debug) { - console.error(`[DEBUG] Supabase upload error:`, error); - if (typeof error === 'object' && 'statusCode' in error) { - console.error(`[DEBUG] HTTP Status Code: ${error.statusCode}`); - } - } - - throw new Error(errorMessage); - } - - if (debug) { - console.log(`[DEBUG] Supabase upload successful`); - console.log( - `[DEBUG] Upload result path: ${uploadToUrl.data?.path || 'N/A'}`, - ); - } - } catch (error) { - if (debug) { - this.logUploadException(error, env, SUPABASE_URL, path, file); - } - - // Re-throw with additional context - const errorMsg = error instanceof Error ? error.message : String(error); - throw new Error(`Supabase upload error: ${errorMsg}`, { cause: error }); - } - } - - /** - * Logs network error details for debugging - * @param error - Error object to analyze for network-related issues - * @returns void - */ - private static logNetworkError(error: Error): void { - const errorMsg = error.message.toLowerCase(); - if (errorMsg.includes('econnrefused') || errorMsg.includes('connection refused')) { - console.error( - `[DEBUG] Network error: Connection refused - check internet connectivity`, - ); - } else if (errorMsg.includes('etimedout') || errorMsg.includes('timeout')) { - console.error( - `[DEBUG] Network error: Connection timeout - check internet connectivity or try again`, - ); - } else if (errorMsg.includes('enotfound') || errorMsg.includes('not found')) { - console.error( - `[DEBUG] Network error: DNS lookup failed - check internet connectivity`, - ); - } else if (errorMsg.includes('econnreset') || errorMsg.includes('connection reset') || errorMsg.includes('connection lost')) { - console.error( - `[DEBUG] Network error: Connection reset/lost - network unstable or interrupted`, - ); - } else if (errorMsg.includes('network')) { - console.error( - `[DEBUG] Network-related error detected - check internet connectivity`, - ); - } - } - /** - * Logs upload exception details for debugging - * @param error - Exception that occurred during upload + * Upload to Supabase using resumable uploads (TUS protocol) + * Uploads to staging location (uploads/{id}/) using the publishable key + * File is later moved to final location by API after finalization * @param env - Environment (dev or prod) - * @param supabaseUrl - Supabase URL being used - * @param path - Upload path - * @param file - File being uploaded - * @returns void + * @param path - Staging storage path (uploads/{id}/file.ext) + * @param source - Upload source descriptor; the file is streamed from disk + * @param debug - Enable debug logging + * @param onProgress - Optional callback for upload progress (bytesUploaded, bytesTotal) + * @returns Promise that resolves when upload completes */ - private static logUploadException( - error: unknown, - env: string, - supabaseUrl: string, + static async uploadResumable( + env: DcdEnvName, path: string, - file: File, - ): void { - console.error(`[DEBUG] === SUPABASE UPLOAD EXCEPTION ===`); - console.error(`[DEBUG] Exception caught:`, error); - console.error( - `[DEBUG] Error type: ${ - error instanceof Error ? error.name : typeof error - }`, - ); - console.error( - `[DEBUG] Error message: ${ - error instanceof Error ? error.message : String(error) - }`, - ); - - if (error instanceof Error && error.stack) { - console.error(`[DEBUG] Error stack:\n${error.stack}`); - } + source: ResumableUploadSource, + debug = false, + onProgress?: (bytesUploaded: number, bytesTotal: number) => void, + ): Promise { + // Prod's Supabase URL is our own custom domain, so customers' networks + // only need to reach devicecloud.dev, not supabase.co. + const storageUrl = ENVIRONMENTS[env].supabase.url; + const supabaseKey = await getSupabaseKey(env); - // Log additional context - console.error(`[DEBUG] Upload context:`); - console.error(`[DEBUG] - Environment: ${env}`); - console.error(`[DEBUG] - Supabase URL: ${supabaseUrl}`); - console.error(`[DEBUG] - Upload path: ${path}`); - console.error(`[DEBUG] - File name: ${file.name}`); - console.error(`[DEBUG] - File size: ${file.size} bytes`); - - // Check for common network errors - if (error instanceof Error) { - this.logNetworkError(error); - } + return this.runTusUpload({ + debug, + endpoint: `${storageUrl}/storage/v1/upload/resumable`, + // Publishable key for staging uploads to uploads/* folder + headers: { + ...supabaseKeyHeaders(supabaseKey), + 'x-upsert': 'true', // Allow overwriting existing files + }, + onProgress, + path, + retryDelays: RETRY_DELAYS, + source, + }); } } diff --git a/src/mcp/context.ts b/src/mcp/context.ts index 175cbc9..80126f6 100644 --- a/src/mcp/context.ts +++ b/src/mcp/context.ts @@ -11,10 +11,11 @@ import type { AuthContext } from '../types/domain/auth.types.js'; import { isAuthExpiring, resolveAuth } from '../utils/auth.js'; import { resolveApiUrl } from '../utils/config-store.js'; +import { forStderr } from '../utils/styling.js'; /** Write a line to stderr. Safe under stdio transport; stdout is reserved. */ export function logStderr(message: string): void { - process.stderr.write(`${message}\n`); + process.stderr.write(`${forStderr(message)}\n`); } export interface McpContext { diff --git a/src/mcp/tools/download-artifacts.ts b/src/mcp/tools/download-artifacts.ts index fde0eaa..f5761ed 100644 --- a/src/mcp/tools/download-artifacts.ts +++ b/src/mcp/tools/download-artifacts.ts @@ -6,6 +6,7 @@ import { z } from 'zod'; import { ReportDownloadService } from '../../services/report-download.service.js'; import { getContext, logStderr } from '../context.js'; import { jsonResult, runTool } from '../helpers.js'; +import { resolveArtifactsPath } from '../../utils/paths.js'; import { localOutput, markWritten } from '../local-files.js'; /** @@ -38,7 +39,9 @@ export function registerDownloadArtifacts(server: McpServer): void { artifactsPath: z .string() .optional() - .describe('Where to write the artifacts zip, inside the working directory (default ./artifacts.zip)'), + .describe( + 'Where to write the artifacts zip, inside the working directory: a file path, or a folder to put artifacts.zip in (default ./artifacts.zip)', + ), resultId: z .number() .int() @@ -85,7 +88,9 @@ export function registerDownloadArtifacts(server: McpServer): void { }; // Both checked before anything is downloaded. - const artifactsPath = localOutput(args.artifactsPath ?? './artifacts.zip'); + // A folder becomes artifacts.zip inside it before the checks, so they + // run on the file that gets written. + const artifactsPath = localOutput(resolveArtifactsPath(args.artifactsPath ?? './artifacts.zip')); const defaultReportPath = args.report ? { allure: 'report.html', html: 'report.zip', junit: 'report.xml' }[args.report] : undefined; diff --git a/src/mcp/tools/run-cloud-test.ts b/src/mcp/tools/run-cloud-test.ts index 1910a82..4db0fc1 100644 --- a/src/mcp/tools/run-cloud-test.ts +++ b/src/mcp/tools/run-cloud-test.ts @@ -128,12 +128,6 @@ export function registerRunCloudTest(server: McpServer): void { .optional() .describe('Force re-upload of the binary even if an identical one exists'), dryRun: z.boolean().optional().describe('Preview flows that would run without submitting'), - encrypt: z - .boolean() - .optional() - .describe( - 'true encrypts the binary, flow zip and env vars client-side before upload; false never does. Omit to follow DCD_ENCRYPT, then the default, which is on.', - ), wait: z .boolean() .optional() @@ -232,15 +226,9 @@ export function registerRunCloudTest(server: McpServer): void { }); } - // Client-side envelope encryption (binary/flow/env), in the same order - // as `dcd cloud`: the encrypt input, DCD_ENCRYPT, then the server default. - const encryption = await checkKekForEncryption( - resolveEncryption({ - flag: args.encrypt, - serverDefault: compatibilityData.encryption?.defaultOn, - }), - apiUrl, - ); + // Client-side envelope encryption (binary/flow/env), always on, as + // in `dcd cloud`. + const encryption = await checkKekForEncryption(resolveEncryption(), apiUrl); const encrypt = encryption.enabled; if (encryption.notice) logStderr(encryption.notice); // Filled in as each part is encrypted; sent on this call's telemetry. @@ -251,9 +239,6 @@ export function registerRunCloudTest(server: McpServer): void { source: encryption.source, }; telemetryExtra.encrypt = encryptTelemetry; - if (encrypt && encryption.source === 'server') { - logStderr('Encrypting uploads; opt out with encrypt: false'); - } // Resolve the binary: existing id, or upload the local file. let appBinaryId = args.appBinaryId; diff --git a/src/methods.ts b/src/methods.ts index 63ca5ac..4817908 100644 --- a/src/methods.ts +++ b/src/methods.ts @@ -16,7 +16,7 @@ import * as yazl from 'yazl'; import { inferEnvFromApiUrl } from './config/environments.js'; import { ApiError, ApiGateway } from './gateways/api-gateway.js'; -import { SupabaseGateway } from './gateways/supabase-gateway.js'; +import { type SignedUpload, SupabaseGateway } from './gateways/supabase-gateway.js'; import { detectFlutterEngine, MetadataExtractorService, @@ -105,7 +105,6 @@ export const compressFilesFromRelativePath = async ( }; export const verifyAppZip = async (zipPath: string) => { - // eslint-disable-next-line new-cap const zip = await new StreamZip.async({ file: zipPath, storeEntries: true, @@ -282,8 +281,8 @@ async function encryptUploadSource( const kek = await resolveKekPublicKey(apiUrl); if (!kek) { throw new Error( - 'Encryption is on (from --encrypt, DCD_ENCRYPT or the default) but no KEK public key is configured for this API. ' + - 'Set DCD_BINARY_KEK_PUBLIC=:, or pass --no-encrypt to upload without encryption.', + 'Encryption is on but no KEK public key is configured for this API. ' + + 'Set DCD_BINARY_KEK_PUBLIC=:.', ); } @@ -604,6 +603,63 @@ async function uploadToSupabase( } } +/** + * Where the Supabase copy went, and so which path to finalise with. + * `direct` means `path` is the final path a signed token uploaded to. + */ +export interface SupabaseUploadOutcome { + direct: boolean; + path: string; + result: UploadResult; +} + +/** + * Upload the Supabase copy. When the API offered a signed upload, go straight + * to the final path, so the API has nothing to copy when it finalises. If + * that fails, or none was offered, upload to the temp path as before. + * + * When everything fails, `path` is the temp path, which an API finalising a + * Backblaze-only upload accepts from any client. + */ +export async function uploadSupabaseCopy(config: { + apiUrl: string; + auth: AuthContext; + debug: boolean; + env: 'dev' | 'prod'; + signedUpload?: SignedUpload; + source: UploadSource; + tempPath: string; +}): Promise { + const { apiUrl, auth, debug, env, signedUpload, source, tempPath } = config; + + if (signedUpload?.path && signedUpload.token) { + if (debug) { + console.log(`[DEBUG] Uploading to Supabase (${env}) straight to the final path with a signed token`); + console.log(`[DEBUG] Final path: ${signedUpload.path}`); + } + + try { + await SupabaseGateway.uploadResumableSigned( + env, + signedUpload, + source, + (signedPath) => ApiGateway.refreshUploadToken(apiUrl, auth, signedPath), + debug, + ); + return { direct: true, path: signedUpload.path, result: { error: null, success: true } }; + } catch (error) { + if (debug) { + console.error( + `[DEBUG] Signed upload failed, falling back to the temp path: ${error instanceof Error ? error.message : String(error)}`, + ); + } + } + } + + const result = await uploadToSupabase(env, tempPath, source, debug); + return { direct: false, path: tempPath, result }; +} + interface BackblazeUploadConfig { auth: AuthContext; apiUrl: string; @@ -693,6 +749,7 @@ interface UploadPaths { b2: unknown; finalPath: string; id: string; + signedUpload?: SignedUpload; tempPath: string; } @@ -721,7 +778,12 @@ async function requestUploadPaths( try { const urlRequestStartTime = Date.now(); - const { id, tempPath, finalPath, b2 } = await ApiGateway.getBinaryUploadUrl(apiUrl, auth, platform, fileSize); + const { id, tempPath, finalPath, b2, signedUpload } = await ApiGateway.getBinaryUploadUrl( + apiUrl, + auth, + platform, + fileSize, + ); if (debug) { const hasStrategy = b2 && typeof b2 === 'object' && 'strategy' in b2; @@ -730,12 +792,13 @@ async function requestUploadPaths( console.log(`[DEBUG] Temp path (TUS upload): ${tempPath}`); console.log(`[DEBUG] Final path (after finalize): ${finalPath}`); console.log(`[DEBUG] Backblaze upload URL provided: ${Boolean(b2)}`); + console.log(`[DEBUG] Signed upload offered: ${Boolean(signedUpload)}`); if (hasStrategy) console.log(`[DEBUG] Backblaze strategy: ${(b2 as { strategy: string }).strategy}`); } if (!tempPath) throw new Error('No upload path provided by API'); - return { b2, finalPath, id, tempPath }; + return { b2, finalPath, id, signedUpload, tempPath }; } catch (error) { if (debug) { console.error('[DEBUG] === FAILED TO GET UPLOAD URL ==='); @@ -834,7 +897,13 @@ async function performUpload(config: PerformUploadConfig): Promise { const { filePath, apiUrl, auth, enc, source, sha, shaPlain, debug, startTime } = config; // Request upload URL and paths - const { id, tempPath, finalPath, b2 } = await requestUploadPaths(apiUrl, auth, filePath, source.size, debug); + const { id, tempPath, finalPath, b2, signedUpload } = await requestUploadPaths( + apiUrl, + auth, + filePath, + source.size, + debug, + ); // Extract app metadata from the original (plaintext) file. Attach the // envelope so it lands on binaries.metadata.enc (#1138). @@ -872,7 +941,8 @@ async function performUpload(config: PerformUploadConfig): Promise { console.log('[DEBUG] Uploading to Supabase...'); } - const supabaseResult: UploadResult = await uploadToSupabase(env, tempPath, source, debug); + const supabase = await uploadSupabaseCopy({ apiUrl, auth, debug, env, signedUpload, source, tempPath }); + const supabaseResult: UploadResult = supabase.result; // Validate results validateUploadResults(supabaseResult, backblazeResult, b2, debug); @@ -882,8 +952,11 @@ async function performUpload(config: PerformUploadConfig): Promise { console.log(`[DEBUG] Upload summary - Backblaze: ${backblazeResult.success ? '✓' : '✗'}, Supabase: ${supabaseResult.success ? '✓' : '✗'}`); console.log('[DEBUG] Finalizing upload...'); console.log(`[DEBUG] Target endpoint: ${apiUrl}/uploads/finaliseUpload`); - console.log(`[DEBUG] Uploaded to staging path: ${tempPath}`); - console.log(`[DEBUG] API will move to final path: ${finalPath}`); + console.log( + supabase.direct + ? `[DEBUG] Uploaded straight to final path: ${supabase.path}` + : `[DEBUG] Uploaded to staging path: ${tempPath}; API will move it to ${finalPath}`, + ); console.log(`[DEBUG] Backblaze upload status: ${backblazeResult.success ? 'SUCCESS' : 'FAILED'}`); console.log(`[DEBUG] Supabase upload status: ${supabaseResult.success ? 'SUCCESS' : 'FAILED'}`); if (!backblazeResult.success && supabaseResult.success) console.log('[DEBUG] ⚠ Warning: File only exists in Supabase (Backblaze failed)'); @@ -898,11 +971,12 @@ async function performUpload(config: PerformUploadConfig): Promise { bytes: source.size, id, metadata, - path: tempPath, + path: supabase.path, // sha is undefined when hash calculation failed — omit it explicitly ...(sha ? { sha } : {}), ...(shaPlain ? { shaPlain } : {}), supabaseSuccess: supabaseResult.success, + ...(supabase.direct ? { useTus: true } : {}), }); if (debug) { @@ -963,7 +1037,7 @@ export const uploadFlowZip = async (config: { // Same response shape as getBinaryUploadUrl. A 404 here means the API // predates the client-direct flow path — let it propagate so the caller // falls back to the multipart endpoint. - const { id, tempPath, finalPath, b2 } = await ApiGateway.getFlowUploadUrl( + const { id, tempPath, finalPath, b2, signedUpload } = await ApiGateway.getFlowUploadUrl( apiUrl, auth, buffer.length, @@ -984,7 +1058,8 @@ export const uploadFlowZip = async (config: { }); // Always upload to Supabase (always-on alongside Backblaze) - const supabaseResult = await uploadToSupabase(env, tempPath, source, debug); + const supabase = await uploadSupabaseCopy({ apiUrl, auth, debug, env, signedUpload, source, tempPath }); + const supabaseResult = supabase.result; validateUploadResults(supabaseResult, backblazeResult, b2, debug); @@ -996,7 +1071,8 @@ export const uploadFlowZip = async (config: { backblazeSuccess: backblazeResult.success, bytes: buffer.length, id, - path: tempPath, + // The signed final path or the temp path; submitFlowTest takes either. + path: supabase.path, supabaseSuccess: supabaseResult.success, useTus: true, }; diff --git a/src/services/execution-plan.service.ts b/src/services/execution-plan.service.ts index 069d035..fbe8297 100644 --- a/src/services/execution-plan.service.ts +++ b/src/services/execution-plan.service.ts @@ -602,7 +602,6 @@ export async function plan(options: PlanOptions): Promise { throw error; } - // eslint-disable-next-line unicorn/no-array-reduce const configPerFlowFile = unfilteredFlowFiles.reduce( (acc, filePath) => { const { config } = readTestYamlFileAsJson(filePath); @@ -645,7 +644,6 @@ export async function plan(options: PlanOptions): Promise { allFlows.map((filePath) => checkDependencies(filePath)), ).then((results) => [...new Set(results.flat())]); - // eslint-disable-next-line unicorn/no-array-reduce const pathsByName = allFlows.reduce((acc, filePath) => { const config = configPerFlowFile[filePath]; const name = (config?.name as string) || path.parse(filePath).name; diff --git a/src/services/moropo.service.ts b/src/services/moropo.service.ts index 89e877b..00656f5 100644 --- a/src/services/moropo.service.ts +++ b/src/services/moropo.service.ts @@ -146,7 +146,6 @@ export class MoropoService { } private async extractZipFile(zipPath: string, extractPath: string): Promise { - // eslint-disable-next-line new-cap const zip = new StreamZip.async({ file: zipPath }); await zip.extract(null, extractPath); await zip.close(); diff --git a/src/services/report-download.service.ts b/src/services/report-download.service.ts index 68ce24d..dbf7690 100644 --- a/src/services/report-download.service.ts +++ b/src/services/report-download.service.ts @@ -3,6 +3,7 @@ import * as path from 'node:path'; import { ApiGateway } from '../gateways/api-gateway.js'; import type { AuthContext } from '../types/domain/auth.types.js'; import { refreshAuth } from '../utils/auth.js'; +import { resolveArtifactsPath } from '../utils/paths.js'; import { deviceFromResultRow } from './results-polling.service.js'; export interface DownloadOptions { @@ -137,12 +138,13 @@ export class ReportDownloadService { auth, uploadId, downloadType, - artifactsPath = './artifacts.zip', debug = false, flow, logger, warnLogger, } = options; + // A folder gets artifacts.zip inside it; the message and result name the file. + const artifactsPath = resolveArtifactsPath(options.artifactsPath ?? './artifacts.zip'); try { if (debug && logger) { diff --git a/src/services/results-polling.service.ts b/src/services/results-polling.service.ts index 17937a7..e07b226 100644 --- a/src/services/results-polling.service.ts +++ b/src/services/results-polling.service.ts @@ -254,7 +254,6 @@ export class ResultsPollingService { try { // Poll in a loop until all tests complete - // eslint-disable-next-line no-constant-condition while (true) { try { nextPollAt = null; @@ -463,7 +462,6 @@ export class ResultsPollingService { }, }, ...(hasFailedTests && { - // eslint-disable-next-line camelcase fail_reason: { get(row) { return row.status === 'FAILED' && row.fail_reason diff --git a/src/services/telemetry.service.ts b/src/services/telemetry.service.ts index b19b894..aa6d6c0 100644 --- a/src/services/telemetry.service.ts +++ b/src/services/telemetry.service.ts @@ -10,7 +10,8 @@ * - `flushSync()` — sync via `curl`, used inside `logger.error` right before * `process.exit` (no other way to send HTTP after exit is called) * - * Opt out: `DCD_TELEMETRY_DISABLED=1` in the environment. + * Opt out: `DCD_TELEMETRY_DISABLED=1` or `DO_NOT_TRACK=1` in the environment + * (see telemetryDisabled). */ import { execFileSync } from 'node:child_process'; import { randomUUID } from 'node:crypto'; @@ -82,6 +83,21 @@ interface TelemetryConfig { const DEFAULT_API_URL = 'https://api.devicecloud.dev'; +/** Set to something other than empty, `0` or `false` (in any case). */ +function isOn(value: string | undefined): boolean { + const v = value?.trim().toLowerCase(); + return v !== undefined && v !== '' && v !== '0' && v !== 'false'; +} + +/** + * Whether the user has turned telemetry off: `DCD_TELEMETRY_DISABLED`, or + * `DO_NOT_TRACK`, the cross-tool convention (https://consoledonottrack.com). + * `0` or `false` leaves telemetry on, so `DO_NOT_TRACK=0` means what it says. + */ +export function telemetryDisabled(env: NodeJS.ProcessEnv = process.env): boolean { + return isOn(env.DCD_TELEMETRY_DISABLED) || isOn(env.DO_NOT_TRACK); +} + class Telemetry { private buffer: TelemetryEvent[] = []; private config: TelemetryConfig | null = null; @@ -90,7 +106,7 @@ class Telemetry { private submitAttempts: number | undefined; private sessionId: string = randomUUID(); private startedAt: number = Date.now(); - private readonly disabled: boolean = !!process.env.DCD_TELEMETRY_DISABLED; + private readonly disabled: boolean = telemetryDisabled(); private readonly release: string = getCliVersion(); /** @@ -99,11 +115,16 @@ class Telemetry { * be sent. Commands that never reach `resolveAuth` (`--help`, `--version`, * `dcd login` before sign-in completes) will skip telemetry entirely — by * design, since those flows have no identity to attach. + * + * Events go where the command's requests go: the `--api-url` flag first, + * then `opts.apiUrl` (a login's stored API). Taking the login's API first + * sent events from a command aimed at another API (a local one, or dev) to + * that login's API instead. */ configure(opts: { auth: AuthContext; apiUrl?: string }) { if (this.disabled) return; this.config = { - apiUrl: opts.apiUrl ?? inferApiUrlFromArgv(), + apiUrl: argvApiUrl() ?? opts.apiUrl ?? DEFAULT_API_URL, auth: opts.auth, command: this.command, }; @@ -343,7 +364,6 @@ class Telemetry { nodeVersion: process.versions.node, platform: process.platform, arch: process.arch, - userEmail: this.config.auth.userEmail, orgId: this.config.auth.orgId, }; } @@ -448,11 +468,12 @@ function inferCommandFromArgv(): string { const API_URL_FLAGS = ['--api-url', '--apiURL', '--apiUrl']; -function inferApiUrlFromArgv(): string { +/** The `--api-url` this command was given, if it is one the command would use. */ +function argvApiUrl(): string | undefined { const args = process.argv.slice(2); // Only a URL the command itself would send credentials to: these events // carry them too, and may be sent before the command checks its flag. - const usable = (url: string) => (checkApiUrl(url.trim()).ok ? url.trim() : DEFAULT_API_URL); + const usable = (url: string) => (checkApiUrl(url.trim()).ok ? url.trim() : undefined); for (let i = 0; i < args.length; i++) { const arg = args[i]; for (const flag of API_URL_FLAGS) { @@ -460,7 +481,7 @@ function inferApiUrlFromArgv(): string { if (arg.startsWith(`${flag}=`)) return usable(arg.slice(flag.length + 1)); } } - return DEFAULT_API_URL; + return undefined; } export const telemetry = new Telemetry(); diff --git a/src/services/test-submission.service.ts b/src/services/test-submission.service.ts index 004d23d..54aa4c6 100644 --- a/src/services/test-submission.service.ts +++ b/src/services/test-submission.service.ts @@ -241,8 +241,8 @@ export class TestSubmissionService { const kek = await resolveKekPublicKey(apiUrl); if (!kek) { throw new Error( - 'Encryption is on (from --encrypt, DCD_ENCRYPT or the default) but no KEK public key is configured for this API. ' + - 'Set DCD_BINARY_KEK_PUBLIC=:, or pass --no-encrypt to upload without encryption.', + 'Encryption is on but no KEK public key is configured for this API. ' + + 'Set DCD_BINARY_KEK_PUBLIC=:.', ); } const flow = encryptFlowBuffer(plaintextZip, kek); @@ -448,7 +448,6 @@ export class TestSubmissionService { } private parseKeyValuePairs(pairs: string[]): Record { - // eslint-disable-next-line unicorn/no-array-reduce return pairs.reduce((acc, cur) => { const [key, ...value] = cur.split('='); // handle case where value includes an equals sign diff --git a/src/types/domain/device.types.ts b/src/types/domain/device.types.ts index eadaf1b..4d0344b 100644 --- a/src/types/domain/device.types.ts +++ b/src/types/domain/device.types.ts @@ -40,7 +40,6 @@ export enum EAndroidDevices { export enum EiOSVersions { 'eighteen' = '18', - 'seventeen' = '17', 'twentySeven' = '27', 'twentySix' = '26', } diff --git a/src/utils/app-upload.ts b/src/utils/app-upload.ts index e60ce46..1880be4 100644 --- a/src/utils/app-upload.ts +++ b/src/utils/app-upload.ts @@ -3,7 +3,6 @@ import { rm } from 'node:fs/promises'; import { uploadBinary, verifyAppZip } from '../methods.js'; import type { AuthContext } from '../types/domain/auth.types.js'; import { CliError } from './cli.js'; -import { fetchCompatibilityData } from './compatibility.js'; import { checkKekForEncryption, resolveEncryption } from './envelope.js'; import { extractTarGz, findAppBundle } from './expo.js'; @@ -47,8 +46,8 @@ export interface UploadLocalAppOptions { /** * Upload a local build the way `dcd upload` does, and return its binary id: - * an Expo `.tar.gz` is unpacked to its `.app`, a `.zip` is checked, and the - * org's encryption default applies. URLs are not handled here: `dcd device` + * an Expo `.tar.gz` is unpacked to its `.app`, a `.zip` is checked, and it + * is encrypted before upload. URLs are not handled here: `dcd device` * hands those to the API's install-from-URL instead. */ export async function uploadLocalApp(opts: UploadLocalAppOptions): Promise { @@ -60,17 +59,7 @@ export async function uploadLocalApp(opts: UploadLocalAppOptions): Promise( */ export function deviceProgress(json: boolean): (message: string) => void { return (message) => { - if (!json) process.stderr.write(`${message}\n`); + if (!json) process.stderr.write(`${forStderr(message)}\n`); }; } diff --git a/src/utils/envelope.ts b/src/utils/envelope.ts index d611d8e..42838d4 100644 --- a/src/utils/envelope.ts +++ b/src/utils/envelope.ts @@ -51,72 +51,59 @@ export interface EnvEnvelope extends BinaryEnvelope { ciphertext: string; } -/** What decided whether a run encrypts (dcd#1138); recorded in telemetry. */ -export type EncryptionSource = 'env' | 'flag' | 'off' | 'server'; +/** + * Whether a run's uploads were encrypted (dcd#1138); recorded in telemetry. + * `always` is the normal case. `no_kek` means the API publishes no KEK public + * key, so there was nothing to encrypt against. `off` means the command never + * reached an upload. + */ +export type EncryptionSource = 'always' | 'no_kek' | 'off'; export interface EncryptionDecision { enabled: boolean; - /** Kept when encryption is skipped, so telemetry shows what asked for it. */ source: EncryptionSource; - /** One line for the user when encryption was wanted but is skipped. */ + /** One line for the user: an ignored opt-out, or why encryption is skipped. */ notice?: string; } -/** `1`/`true` is on and `0`/`false` is off, in any case; anything else is unset. */ -function parseEncryptEnv(value: string | undefined): boolean | undefined { - switch (value?.trim().toLowerCase()) { - case '1': - case 'true': { - return true; - } - - case '0': - case 'false': { - return false; - } - - default: { - return undefined; - } - } +/** `0`/`false` in any case: a value that used to turn encryption off. */ +function isOptOutValue(value: string | undefined): boolean { + const v = value?.trim().toLowerCase(); + return v === '0' || v === 'false'; } /** - * Whether client-side envelope encryption is on, and what decided it. The - * first of these that is set wins: - * 1. `flag`: `--encrypt` / `--no-encrypt`, or the MCP tool's `encrypt` input. - * 2. `DCD_ENCRYPT`, then its legacy alias `DCD_ENCRYPT_BINARIES`. - * 3. `serverDefault`: `encryption.defaultOn` from the compatibility data, - * which the API turns on for every org unless its kill switch is set. - * 4. Off. An API too old to send `encryption` ends up here. - * When on, the binary, the flow zip, and the env map are each encrypted with - * their **own** per-upload DEK (all wrapped under the same per-env KEK). + * Uploads are always encrypted: the app binary, the flow zip and the env map + * each get their own per-upload DEK, all wrapped under the same per-env KEK. + * + * There is no opt-out any more. `--no-encrypt` (seen here as `flag: false`) + * and `DCD_ENCRYPT=0` / `DCD_ENCRYPT_BINARIES=0` are ignored with a warning, + * so scripts that still pass them keep working. `--encrypt` is a no-op. */ export function resolveEncryption(opts: { env?: NodeJS.ProcessEnv; flag?: boolean; - serverDefault?: boolean; -}): EncryptionDecision { - const { env = process.env, flag, serverDefault } = opts; - if (flag !== undefined) return { enabled: flag, source: 'flag' }; - - const fromEnv = - parseEncryptEnv(env.DCD_ENCRYPT) ?? parseEncryptEnv(env.DCD_ENCRYPT_BINARIES); - if (fromEnv !== undefined) return { enabled: fromEnv, source: 'env' }; +} = {}): EncryptionDecision { + const { env = process.env, flag } = opts; + const ignored: string[] = []; + if (flag === false) ignored.push('--no-encrypt'); + if (isOptOutValue(env.DCD_ENCRYPT)) ignored.push('DCD_ENCRYPT'); + if (isOptOutValue(env.DCD_ENCRYPT_BINARIES)) ignored.push('DCD_ENCRYPT_BINARIES'); - if (serverDefault === true) return { enabled: true, source: 'server' }; - return { enabled: false, source: 'off' }; + const decision: EncryptionDecision = { enabled: true, source: 'always' }; + if (ignored.length > 0) { + decision.notice = `Ignoring ${ignored.join(' and ')}: uploads are always encrypted.`; + } + return decision; } /** * Check that `apiUrl` has a KEK before a run encrypts against it: either * `DCD_BINARY_KEK_PUBLIC` is set or the API publishes one on `GET /cli-config` - * (see resolveKekPublicKey). Without one, an explicit `--encrypt` is an error, - * while encryption from DCD_ENCRYPT or the server default is skipped with a - * notice, so a run against an API that publishes no KEK uploads in plaintext - * as before. An API that cannot be asked at all is an error whatever decided - * encryption: silently falling back to plaintext would be the one outcome the - * org asked not to have. + * (see resolveKekPublicKey). An API that publishes no KEK gets plaintext + * uploads with a notice: that is the server's own switch, and the only way to + * turn encryption off. An API that cannot be asked at all is an error, since + * silently falling back to plaintext would hide the failure. */ export async function checkKekForEncryption( decision: EncryptionDecision, @@ -124,17 +111,10 @@ export async function checkKekForEncryption( ): Promise { if (!decision.enabled || (await resolveKekPublicKey(apiUrl))) return decision; - if (decision.source === 'flag') { - throw new Error( - `--encrypt needs the KEK public key of the API it uploads to, and ${apiUrl} does not publish one. ` + - 'Set DCD_BINARY_KEK_PUBLIC=: to encrypt against it, or drop --encrypt.', - ); - } - return { enabled: false, notice: `Not encrypting uploads: ${apiUrl} does not publish a KEK public key. Set DCD_BINARY_KEK_PUBLIC to encrypt against it.`, - source: decision.source, + source: 'no_kek', }; } diff --git a/src/utils/paths.ts b/src/utils/paths.ts index 713af1f..d5c6b35 100644 --- a/src/utils/paths.ts +++ b/src/utils/paths.ts @@ -1,5 +1,39 @@ +import { statSync } from 'node:fs'; +import { homedir } from 'node:os'; import * as path from 'node:path'; +/** Expand a leading `~` to the home directory, as the download paths allow. */ +export function expandHome(p: string): string { + return p.replace(/^~(?=$|\/|\\)/, homedir()); +} + +/** The file name an artifacts download gets when it is given a folder. */ +export const DEFAULT_ARTIFACTS_FILENAME = 'artifacts.zip'; + +/** + * Where an artifacts download goes. A folder, meaning one that exists or a + * path ending in a separator, gets `artifacts.zip` inside it. Anything else is + * a file path and is returned unchanged, so calling this twice is harmless. + * Writing to a folder path used to fail with EISDIR, after the download had + * started. + */ +export function resolveArtifactsPath(p: string): string { + const endsWithSeparator = /[/\\]$/.test(p); + if (endsWithSeparator || isDirectory(expandHome(p))) { + return path.join(p, DEFAULT_ARTIFACTS_FILENAME); + } + + return p; +} + +function isDirectory(p: string): boolean { + try { + return statSync(p).isDirectory(); + } catch { + return false; + } +} + /** * Convert an absolute path into the portable './'-prefixed, forward-slash * relative form used as flow keys across submission, metadata maps, and diff --git a/src/utils/progress.ts b/src/utils/progress.ts index 099b6b8..96e876b 100644 --- a/src/utils/progress.ts +++ b/src/utils/progress.ts @@ -100,7 +100,6 @@ class Action { this.current = null; this._status = ''; if (line) { - // eslint-disable-next-line no-console console.log(line); } } @@ -110,7 +109,6 @@ class Action { private print(line: string): void { if (line === this._lastPrinted) return; this._lastPrinted = line; - // eslint-disable-next-line no-console console.log(line); } } @@ -118,7 +116,6 @@ class Action { export const ux = { action: new Action(), info(message: string): void { - // eslint-disable-next-line no-console console.log(message); }, }; diff --git a/src/utils/styling.ts b/src/utils/styling.ts index 53d1e7b..94e672d 100644 --- a/src/utils/styling.ts +++ b/src/utils/styling.ts @@ -1,46 +1,117 @@ -import chalk from 'chalk'; +import { inspect } from 'node:util'; import { findEnvByApiUrl } from '../config/environments.js'; /** * Centralized styling utilities for CLI output * Provides consistent, developer-friendly visual formatting + * + * Text is styled only when stdout takes colour (see {@link takesColour}); text + * bound for stderr goes through {@link forStderr}. The escape codes come from + * `util.inspect.colors`, the table Node's `styleText` reads, and are applied + * by {@link style}. */ /** Strip ANSI color escape sequences for visible-width calculations. */ // eslint-disable-next-line no-control-regex -- matches ANSI escape sequences export const stripAnsi = (s: string): string => s.replace(/\u001B\[[0-9;]*m/g, ''); +/** + * Whether `stream` takes colour, by the rule Node's `styleText` applies: + * `FORCE_COLOR` decides when set; otherwise the stream must be a terminal + * whose colour depth (which folds in `NO_COLOR`, `NODE_DISABLE_COLORS` and + * `TERM=dumb`) is above monochrome. + */ +function takesColour(stream: NodeJS.WriteStream): boolean { + const force = process.env.FORCE_COLOR; + if (force !== undefined) return ['', '1', '2', '3', 'true'].includes(force); + return ( + stream.isTTY === true && + (typeof stream.getColorDepth !== 'function' || stream.getColorDepth() > 2) + ); +} + +/** The formats the palette uses. Combined styles nest single-format calls. */ +type StyleFormat = 'blue' | 'bold' | 'cyan' | 'gray' | 'green' | 'red' | 'underline' | 'yellow'; + +/** + * Apply `format` to `text` when stdout takes colour. + * + * This is not left to `util.styleText`, because its output differs across the + * runtimes the CLI ships on: bun 1.3 (which compiles the standalone binaries) + * and Node before 22.20 drop the outer colour after a nested span, and bun 1.3 + * and Node before 22.8 colour even when the stream can't show it. The rules + * here are the ones chalk applied, so output is the same everywhere: + * - an inner span that ends this style's colour re-opens it, so text after + * the span keeps the outer colour; + * - each line is closed and re-opened, so a line read on its own (a CI log, a + * pager) still carries its colour; + * - an empty string stays empty. + * + * Anything but a string is printed as `String(value)`, never fatal: the types + * may call a value a string that an API sent as null or a number. + */ +function style(format: StyleFormat, text: string): string { + const s = String(text); + const codes = inspect.colors[format]; + if (s === '' || !codes || !takesColour(process.stdout)) return s; + const open = `\u001B[${codes[0]}m`; + const close = `\u001B[${codes[1]}m`; + const body = s + .replaceAll(close, close + open) + .replaceAll(/\r?\n/g, (lineBreak) => close + lineBreak + open); + return open + body + close; +} + +const paint = + (format: StyleFormat) => + (text: string): string => + style(format, text); + +const cyan = paint('cyan'); +const underline = paint('underline'); + /** * Status symbols with associated colors */ export const symbols = { - cancelled: chalk.gray('⊘'), - deprecation: chalk.red('⚠'), - error: chalk.red('✗'), - info: chalk.blue('ℹ'), - pending: chalk.yellow('⏸'), - queued: chalk.gray('⏳'), - running: chalk.blue('▶'), - success: chalk.green('✓'), - unknown: chalk.gray('?'), - warning: chalk.yellow('⚠'), + cancelled: style('gray', '⊘'), + deprecation: style('red', '⚠'), + error: style('red', '✗'), + info: style('blue', 'ℹ'), + pending: style('yellow', '⏸'), + queued: style('gray', '⏳'), + running: style('blue', '▶'), + success: style('green', '✓'), + unknown: style('gray', '?'), + warning: style('yellow', '⚠'), } as const; /** * Color utility functions for semantic styling */ export const colors = { - bold: chalk.bold, - dim: chalk.gray, - error: chalk.red, - highlight: chalk.cyan, - info: chalk.blue, - success: chalk.green, - url: chalk.cyan.underline, - warning: chalk.yellow, + bold: paint('bold'), + dim: paint('gray'), + error: paint('red'), + highlight: cyan, + info: paint('blue'), + success: paint('green'), + url: (text: string): string => cyan(underline(text)), + warning: paint('yellow'), } as const; +/** + * Prepare styled text for stderr. The palette above follows stdout, so when + * stdout is a terminal but stderr is not (`dcd cloud 2> err.log`), the colour + * codes are stripped here to keep the file plain. + * @param text - Text that may carry colour codes from {@link colors} or {@link symbols} + * @returns The text, without colour codes unless stderr takes colour + */ +export function forStderr(text: string): string { + return takesColour(process.stderr) ? text : stripAnsi(text); +} + /** * Structural glyphs that give the CLI its tree-shaped layout. `section` marks a * top-level heading; `branch` opens the group of detail rows beneath it. @@ -148,7 +219,7 @@ export function formatTestSummary(summary: { total: number; }): string { const parts = [ - chalk.bold(`${summary.completed}/${summary.total}`), + colors.bold(`${summary.completed}/${summary.total}`), colors.success(`✓ ${summary.passed}`), colors.error(`✗ ${summary.failed}`), colors.info(`▶ ${summary.running}`), @@ -170,7 +241,6 @@ export function table( options: { printLine?: (line: string) => void } = {}, ): void { const printLine = options.printLine ?? ((line: string) => { - // eslint-disable-next-line no-console console.log(line); }); @@ -190,8 +260,8 @@ export function table( return s + ' '.repeat(Math.max(0, width - visibleLen)); }; - printLine(headers.map((h, i) => pad(chalk.bold(h), widths[i])).join(' ')); - printLine(widths.map((w) => chalk.gray('─'.repeat(w))).join(' ')); + printLine(headers.map((h, i) => pad(colors.bold(h), widths[i])).join(' ')); + printLine(widths.map((w) => colors.dim('─'.repeat(w))).join(' ')); for (const row of cells) { printLine(row.map((c, i) => pad(c, widths[i])).join(' ')); } diff --git a/test/unit/artifacts-path.test.ts b/test/unit/artifacts-path.test.ts new file mode 100644 index 0000000..e4ae63b --- /dev/null +++ b/test/unit/artifacts-path.test.ts @@ -0,0 +1,55 @@ +import { expect } from 'chai'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; + +import { localOutput } from '../../src/mcp/local-files.js'; +import { resolveArtifactsPath } from '../../src/utils/paths.js'; + +describe('resolveArtifactsPath', () => { + let tempDir: string; + + before(() => { + tempDir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'dcd-artifacts-path-'))); + }); + + after(() => { + fs.rmSync(tempDir, { force: true, recursive: true }); + }); + + it('puts artifacts.zip inside an existing folder', () => { + expect(resolveArtifactsPath(tempDir)).to.equal(path.join(tempDir, 'artifacts.zip')); + }); + + it('treats a trailing separator as a folder, even one that does not exist yet', () => { + const dir = path.join(tempDir, 'later') + '/'; + expect(resolveArtifactsPath(dir)).to.equal(path.join(tempDir, 'later', 'artifacts.zip')); + }); + + it('leaves a file path alone, existing or not', () => { + const file = path.join(tempDir, 'mine.zip'); + expect(resolveArtifactsPath(file)).to.equal(file); + fs.writeFileSync(file, 'x'); + expect(resolveArtifactsPath(file)).to.equal(file); + }); + + it('is harmless to apply twice', () => { + const once = resolveArtifactsPath(tempDir); + expect(resolveArtifactsPath(once)).to.equal(once); + }); + + it('checks a ~ path against the home folder and keeps the ~', () => { + expect(resolveArtifactsPath('~')).to.equal(path.join('~', 'artifacts.zip')); + }); + + // The MCP tool resolves the folder first, so its write check runs on the + // file. A folder given as is would be refused as "already exists". + it('lets the MCP write check pass for a folder inside the working directory', () => { + const dir = path.join(tempDir, 'out'); + fs.mkdirSync(dir); + expect(localOutput(resolveArtifactsPath(dir), tempDir)).to.equal( + path.join(dir, 'artifacts.zip'), + ); + expect(() => localOutput(dir, tempDir)).to.throw(/already exists/); + }); +}); diff --git a/test/unit/device-bundle.test.ts b/test/unit/device-bundle.test.ts index 9e037c4..6433b9a 100644 --- a/test/unit/device-bundle.test.ts +++ b/test/unit/device-bundle.test.ts @@ -5,7 +5,7 @@ import * as os from 'node:os'; import * as path from 'node:path'; import StreamZip from 'node-stream-zip'; -import { clearCompatibilityCache } from '../../src/utils/compatibility.js'; +import { resetCliConfigCache } from '../../src/config/cli-config.js'; import { bundleFiles, flowFileBundle, uploadFlowBundle } from '../../src/utils/device-bundle.js'; const API = 'https://api.devicecloud.dev'; @@ -22,7 +22,6 @@ describe('dcd device run : flow bundles', () => { const ORIGINAL_ENV = { ...process.env }; let dir: string; let calls: Call[]; - let encryptionDefault: boolean; beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dcd-bundle-test-')); @@ -35,8 +34,7 @@ describe('dcd device run : flow bundles', () => { fs.writeFileSync(path.join(dir, 'node_modules', 'x.js'), ''); delete process.env.DCD_ENCRYPT; delete process.env.DCD_ENCRYPT_BINARIES; - encryptionDefault = false; - clearCompatibilityCache(); + resetCliConfigCache(); calls = []; globalThis.fetch = (async (input: unknown, init?: RequestInit) => { const url = String(input); @@ -46,10 +44,10 @@ describe('dcd device run : flow bundles', () => { body: init?.body as Uint8Array | string | undefined, }; calls.push(call); - if (url.includes('/results/compatibility')) { - return new Response( - JSON.stringify({ statusCode: 200, data: { encryption: { defaultOn: encryptionDefault } } }), - ); + // The API publishes no KEK, so bundles go up in plaintext unless a + // test sets DCD_BINARY_KEK_PUBLIC. + if (url.endsWith('/cli-config')) { + return new Response(JSON.stringify({ supabase_publishable_key: 'sb_publishable_test' })); } if (url.endsWith('/device/bundles/upload-url')) { @@ -76,7 +74,7 @@ describe('dcd device run : flow bundles', () => { }); afterEach(() => { - clearCompatibilityCache(); + resetCliConfigCache(); globalThis.fetch = realFetch; process.env = { ...ORIGINAL_ENV }; fs.rmSync(dir, { force: true, recursive: true }); @@ -195,7 +193,7 @@ describe('dcd device run : flow bundles', () => { }); }); - it('uploads the zip to both copies and registers what landed', async () => { + it('uploads the zip to both copies and registers what landed (no KEK, so plaintext)', async () => { const bundle = await uploadFlowBundle({ apiUrl: API, auth, dir, log: () => {} }); expect(bundle.id).to.equal('b-1'); expect(bundle.files).to.equal(2); @@ -223,11 +221,11 @@ describe('dcd device run : flow bundles', () => { await zip.close(); }); - it("encrypts the zip when the org's default says so", async () => { + it('encrypts the zip whenever there is a KEK, even with DCD_ENCRYPT=0', async () => { const { publicKey } = generateKeyPairSync('x25519'); const raw = publicKey.export({ type: 'spki', format: 'der' }).subarray(12); process.env.DCD_BINARY_KEK_PUBLIC = `1:${raw.toString('base64')}`; - encryptionDefault = true; + process.env.DCD_ENCRYPT = '0'; const bundle = await uploadFlowBundle({ apiUrl: API, auth, dir, log: () => {} }); expect(bundle.encrypted).to.equal(true); diff --git a/test/unit/device-command.test.ts b/test/unit/device-command.test.ts index e14e60f..585864a 100644 --- a/test/unit/device-command.test.ts +++ b/test/unit/device-command.test.ts @@ -956,6 +956,8 @@ describe('dcd device', () => { return { body: { id: 'b-1', upload: { path: 'p', signedUrl: 'https://sb/put' }, mirror: null } }; } + // No KEK published, so the bundle goes up in plaintext. + if (call.url.endsWith('/cli-config')) return { body: { supabase_publishable_key: 'sb_publishable_test' } }; if (call.url === 'https://sb/put') return { body: {} }; if (call.url.endsWith('/device/bundles')) { return { body: { bundle: { id: 'b-1', sha: 's', bytes: 1, encrypted: false, created_at: 'now' } } }; @@ -1475,6 +1477,8 @@ describe('dcd device', () => { return { body: { id: 'b-1', upload: { path: 'p', signedUrl: 'https://sb/put' }, mirror: null } }; } + // No KEK published, so the bundle goes up in plaintext. + if (call.url.endsWith('/cli-config')) return { body: { supabase_publishable_key: 'sb_publishable_test' } }; if (call.url === 'https://sb/put') return { body: {} }; if (call.url.endsWith('/device/bundles')) { return { body: { bundle: { id: 'b-1', sha: 's', bytes: 1, encrypted: false, created_at: 'now' } } }; diff --git a/test/unit/device-validation.service.test.ts b/test/unit/device-validation.service.test.ts index 943020f..51b8a7b 100644 --- a/test/unit/device-validation.service.test.ts +++ b/test/unit/device-validation.service.test.ts @@ -11,7 +11,7 @@ import type { CompatibilityData } from '../../src/utils/compatibility.js'; */ const compat: CompatibilityData = { ios: { - 'iphone-14': ['17', '18'], + 'iphone-14': ['18'], 'iphone-16': ['18', '26', '27'], 'iphone-17': ['26', '27'], 'iphone-19': ['28'], @@ -117,7 +117,7 @@ describe('DeviceValidationService', () => { it('rejects an unsupported explicit pair with the device\'s versions', () => { expect(() => ios('27', 'iphone-14')).to.throw( - /^iphone-14 only supports these iOS versions: 17, 18$/, + /^iphone-14 only supports these iOS versions: 18$/, ); expect(() => android('34', 'pixel-10')).to.throw( /^pixel-10 only supports these Android API levels: 36, 37$/, @@ -136,7 +136,7 @@ describe('DeviceValidationService', () => { describe('requests that rely on a default', () => { it('tells a device-only iOS request to pass the version explicitly', () => { expect(() => ios(undefined, 'iphone-14')).to.throw( - 'iphone-14 only supports these iOS versions: 17, 18. No iOS version was given, so the default (26) was checked: pass one of those explicitly with --ios-version', + 'iphone-14 only supports these iOS versions: 18. No iOS version was given, so the default (26) was checked: pass one of those explicitly with --ios-version', ); }); diff --git a/test/unit/e2e-provider.test.ts b/test/unit/e2e-provider.test.ts new file mode 100644 index 0000000..fbae704 --- /dev/null +++ b/test/unit/e2e-provider.test.ts @@ -0,0 +1,603 @@ +import { expect } from 'chai'; + +import { + createProvider, + type DeviceCloudOptions, + type E2eDeviceRequest, + type ProviderDeps, +} from '../../src/e2e/provider.js'; + +/** + * The e2e device provider (`@devicecloud.dev/dcd/e2e`): one DeviceCloud + * device session per e2e worker, handed to e2e as the address of the + * session's own agent-device daemon. + */ + +interface Call { + body: unknown; + headers: Record; + method: string; + path: string; +} + +type Answer = { body: unknown; status: number }; + +/** A fake API: answers each `METHOD /path` from a queue, the last answer repeating. */ +function fakeApi(routes: Record) { + const calls: Call[] = []; + const fetchFake = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = new URL(String(input)); + const method = init?.method ?? 'GET'; + calls.push({ + body: init?.body ? JSON.parse(String(init.body)) : undefined, + headers: (init?.headers ?? {}) as Record, + method, + path: url.pathname, + }); + const queue = routes[`${method} ${url.pathname}`]; + if (!queue?.length) + return new Response(JSON.stringify({ message: 'no route' }), { + status: 404, + }); + const answer = queue.length > 1 ? queue.shift()! : queue[0]; + return new Response(JSON.stringify(answer.body), { status: answer.status }); + }) as typeof fetch; + return { calls, fetch: fetchFake }; +} + +const session = (state: string, extra: Record = {}) => ({ + session: { + id: 'brave-teal-otter', + monitor_url: 'https://console.example/device/brave-teal-otter', + state, + ...extra, + }, +}); +const engine = { + engine: { + agentDeviceVersion: '0.21.36', + daemon: { + authToken: 'daemon-token', + baseUrl: 'https://relay.example/engine/7/agent-device', + }, + deviceId: 'emulator-5554', + }, +}; + +/** The happy path: queued, then ready; the engine needs one more moment. */ +const happyRoutes = (): Record => ({ + 'DELETE /device/sessions/brave-teal-otter': [ + { body: session('released'), status: 200 }, + ], + 'GET /device/sessions/brave-teal-otter': [ + { body: session('provisioning'), status: 200 }, + { + body: session('ready', { install: { status: 'installed' } }), + status: 200, + }, + ], + 'POST /device/sessions': [{ body: session('queued'), status: 201 }], + 'POST /device/sessions/brave-teal-otter/engine': [ + { body: { error: 'LIVE_NOT_READY', message: 'Not yet.' }, status: 425 }, + { body: engine, status: 200 }, + ], +}); + +function setup( + routes: Record, + options: DeviceCloudOptions = {}, + deps: Partial = {}, +) { + const api = fakeApi(routes); + const uploads: string[] = []; + const provider = createProvider(options, { + fetch: api.fetch, + pollMs: 1, + startTimeoutMs: 60_000, + upload: async ({ filePath }) => { + uploads.push(filePath); + return 'uploaded-binary-id'; + }, + version: '9.9.9', + ...deps, + }); + return { api, provider, uploads }; +} + +function request( + overrides: Partial = {}, +): E2eDeviceRequest & { lines: string[] } { + const lines: string[] = []; + return { + agentDeviceVersion: '0.21.37', + env: { DEVICE_CLOUD_API_KEY: 'key-from-env' }, + lines, + log: (line) => lines.push(line), + platform: 'android', + signal: new AbortController().signal, + ...overrides, + }; +} + +async function rejection(promise: Promise): Promise { + try { + await promise; + } catch (error) { + return error as Error; + } + + throw new Error('expected a rejection'); +} + +describe('the e2e device provider', () => { + it('starts a session, waits for its device, and leases the device engine', async () => { + const { api, provider } = setup(happyRoutes(), { + appBinaryId: 'binary-1', + maxDurationMin: 15, + }); + const req = request(); + + const lease = await provider.acquire(req); + + expect(lease).to.deep.equal({ + daemon: { + authToken: 'daemon-token', + baseUrl: 'https://relay.example/engine/7/agent-device', + }, + deviceId: 'emulator-5554', + id: 'brave-teal-otter', + }); + const start = api.calls[0]; + expect(start.method).to.equal('POST'); + expect(start.path).to.equal('/device/sessions'); + expect(start.body).to.deep.equal({ + binaryUploadId: 'binary-1', + clientLabel: 'e2e', + maxDurationMin: 15, + platform: 'android', + }); + expect(start.headers).to.include({ + 'x-app-api-key': 'key-from-env', + 'x-dcd-cli-version': '9.9.9', + }); + // Two reads until ready, then the engine twice (425, then 200). Nothing stopped. + expect(api.calls.map((c) => `${c.method} ${c.path}`)).to.deep.equal([ + 'POST /device/sessions', + 'GET /device/sessions/brave-teal-otter', + 'GET /device/sessions/brave-teal-otter', + 'POST /device/sessions/brave-teal-otter/engine', + 'POST /device/sessions/brave-teal-otter/engine', + ]); + expect(req.lines).to.include( + 'watch at https://console.example/device/brave-teal-otter', + ); + expect(req.lines.some((l) => l.includes('agent-device 0.21.36'))).to.equal( + true, + ); + }); + + it('sends requests to https://api.devicecloud.dev unless told otherwise', async () => { + const seen: string[] = []; + const api = fakeApi(happyRoutes()); + const { provider } = setup( + happyRoutes(), + {}, + { + fetch: (async (input: RequestInfo | URL, init?: RequestInit) => { + seen.push(new URL(String(input)).origin); + return api.fetch(input, init); + }) as typeof fetch, + }, + ); + + await provider.acquire(request()); + + expect(new Set(seen)).to.deep.equal( + new Set(['https://api.devicecloud.dev']), + ); + }); + + it('starts the device in the locale asked for, written either way', async () => { + for (const locale of ['en_US', 'en-US', ' en-US ']) { + const { api, provider } = setup(happyRoutes(), { locale }); + await provider.acquire(request()); + expect( + (api.calls[0].body as { deviceLocale?: string }).deviceLocale, + ).to.equal('en_US'); + } + + const { api, provider } = setup(happyRoutes(), { locale: 'pt-BR' }); + await provider.acquire(request()); + expect( + (api.calls[0].body as { deviceLocale?: string }).deviceLocale, + ).to.equal('pt_BR'); + }); + + it("leaves the device's own locale without one", async () => { + const { api, provider } = setup(happyRoutes()); + await provider.acquire(request()); + expect(api.calls[0].body).to.not.have.property('deviceLocale'); + }); + + it('refuses a locale it cannot send when the config is read, before any session starts', () => { + for (const locale of ['english', 'en_us', 'EN-US', 'en', 'en_USA', '']) { + expect(() => setup(happyRoutes(), { locale }), locale).to.throw( + 'is not a locale. Use a language and region, such as en_US or en-US.', + ); + } + }); + + it('takes the key from the options before the environment', async () => { + const { api, provider } = setup(happyRoutes(), { + apiKey: 'key-from-options', + }); + await provider.acquire(request()); + expect(api.calls[0].headers['x-app-api-key']).to.equal('key-from-options'); + }); + + it('refuses to start without a key, and names the variable to set', async () => { + const { api, provider } = setup(happyRoutes()); + const error = await rejection(provider.acquire(request({ env: {} }))); + expect(error.message).to.include('DEVICE_CLOUD_API_KEY'); + expect(api.calls).to.have.length(0); + }); + + it('refuses an API URL that would send the key in the clear, before sending anything', async () => { + const { api, provider } = setup(happyRoutes(), { + apiUrl: 'http://api.example.com', + }); + const error = await rejection(provider.acquire(request())); + expect(error.message).to.include('over plain http'); + expect(api.calls).to.have.length(0); + }); + + it('uploads the target build once for every worker, and tells e2e not to install it', async () => { + const { api, provider, uploads } = setup(happyRoutes()); + const one = request({ app: 'com.example.app', appPath: '/builds/app.apk' }); + const two = request({ app: 'com.example.app', appPath: '/builds/app.apk' }); + + const leases = await Promise.all([ + provider.acquire(one), + provider.acquire(two), + ]); + + expect(uploads).to.deep.equal(['/builds/app.apk']); + expect(leases.map((l) => l.installedApp)).to.deep.equal([ + 'com.example.app', + 'com.example.app', + ]); + const starts = api.calls.filter( + (c) => c.method === 'POST' && c.path === '/device/sessions', + ); + expect( + starts.map((c) => (c.body as { binaryUploadId?: string }).binaryUploadId), + ).to.deep.equal(['uploaded-binary-id', 'uploaded-binary-id']); + }); + + it('installs a given build instead of uploading the target one', async () => { + const { api, provider, uploads } = setup(happyRoutes(), { + appBinaryId: 'binary-1', + }); + const lease = await provider.acquire( + request({ app: 'com.example.app', appPath: '/builds/app.apk' }), + ); + expect(uploads).to.deep.equal([]); + expect( + (api.calls[0].body as { binaryUploadId: string }).binaryUploadId, + ).to.equal('binary-1'); + // e2e must still not install: DeviceCloud devices take builds from the session only. + expect(lease.installedApp).to.equal('com.example.app'); + }); + + it('needs the bundle id beside a target build', async () => { + const { api, provider } = setup(happyRoutes()); + const error = await rejection( + provider.acquire(request({ appPath: '/builds/app.apk' })), + ); + expect(error.message).to.include('app.bundleId'); + expect(api.calls).to.have.length(0); + }); + + it('stops the session and says why when the build fails to install', async () => { + const routes = happyRoutes(); + routes['GET /device/sessions/brave-teal-otter'] = [ + { + body: session('ready', { + install: { + error: 'The app is not signed for a simulator.', + status: 'failed', + }, + }), + status: 200, + }, + ]; + const { api, provider } = setup(routes, { appBinaryId: 'binary-1' }); + + const error = await rejection(provider.acquire(request())); + + expect(error.message).to.include('The app is not signed for a simulator.'); + expect(api.calls.at(-1)).to.include({ + method: 'DELETE', + path: '/device/sessions/brave-teal-otter', + }); + }); + + it("stops the session and passes on the API's words when the engine is refused", async () => { + const routes = happyRoutes(); + routes['POST /device/sessions/brave-teal-otter/engine'] = [ + { + body: { + error: 'LIVE_ENGINE_NOT_ENABLED', + message: 'e2e is not enabled for this organization.', + }, + status: 403, + }, + ]; + const { api, provider } = setup(routes); + + const error = await rejection(provider.acquire(request())); + + expect(error.message).to.include( + 'e2e is not enabled for this organization.', + ); + expect(error.message).to.include('LIVE_ENGINE_NOT_ENABLED'); + expect(api.calls.at(-1)).to.include({ + method: 'DELETE', + path: '/device/sessions/brave-teal-otter', + }); + }); + + it('asks again when the network loses a poll, rather than ending the run', async () => { + const api = fakeApi(happyRoutes()); + let lost = 0; + const { provider } = setup( + happyRoutes(), + {}, + { + fetch: (async (input: RequestInfo | URL, init?: RequestInit) => { + // The second read of the session, and the first ask for the engine, never arrive. + const key = `${init?.method} ${new URL(String(input)).pathname}`; + const reads = api.calls.filter( + (c) => `${c.method} ${c.path}` === key, + ).length; + if ( + (key === 'GET /device/sessions/brave-teal-otter' && + reads === 1 && + lost === 0) || + (key === 'POST /device/sessions/brave-teal-otter/engine' && + reads === 0 && + lost === 1) + ) { + lost++; + throw new TypeError('fetch failed', { + cause: { code: 'ECONNRESET' }, + }); + } + + return api.fetch(input, init); + }) as typeof fetch, + }, + ); + + const lease = await provider.acquire(request()); + + expect(lost).to.equal(2); + expect(lease.id).to.equal('brave-teal-otter'); + expect(api.calls.filter((c) => c.method === 'DELETE')).to.have.length(0); + }); + + it('never sends a session start twice, and says what could not be reached', async () => { + let starts = 0; + const { provider } = setup( + happyRoutes(), + {}, + { + fetch: (async () => { + starts++; + throw new TypeError('fetch failed', { cause: { code: 'ETIMEDOUT' } }); + }) as typeof fetch, + }, + ); + + const error = await rejection(provider.acquire(request())); + + expect(starts).to.equal(1); + expect(error.message).to.equal( + 'DeviceCloud: POST /device/sessions could not reach https://api.devicecloud.dev (ETIMEDOUT)', + ); + }); + + it('stops the session when the network stays down while it waits', async () => { + const api = fakeApi(happyRoutes()); + const { provider } = setup( + happyRoutes(), + {}, + { + fetch: (async (input: RequestInfo | URL, init?: RequestInit) => { + if (init?.method === 'GET') + throw new TypeError('fetch failed', { + cause: { code: 'ENETUNREACH' }, + }); + return api.fetch(input, init); + }) as typeof fetch, + }, + ); + + const error = await rejection(provider.acquire(request())); + + expect(error.message).to.include( + 'could not reach https://api.devicecloud.dev (ENETUNREACH)', + ); + expect(api.calls.at(-1)).to.include({ + method: 'DELETE', + path: '/device/sessions/brave-teal-otter', + }); + }); + + it('gives up when the session ends before it is ready', async () => { + const routes = happyRoutes(); + routes['GET /device/sessions/brave-teal-otter'] = [ + { + body: session('failed', { release_reason: 'device_failed' }), + status: 200, + }, + ]; + const { provider } = setup(routes); + const error = await rejection(provider.acquire(request())); + expect(error.message).to.include( + 'ended before it was ready (device_failed)', + ); + }); + + it('stops waiting when the run is interrupted, and stops the session', async () => { + const routes = happyRoutes(); + routes['GET /device/sessions/brave-teal-otter'] = [ + { body: session('queued'), status: 200 }, + ]; + const { api, provider } = setup(routes, {}, { pollMs: 50 }); + const interrupt = new AbortController(); + + const acquiring = provider.acquire(request({ signal: interrupt.signal })); + setTimeout(() => interrupt.abort(new Error('interrupted')), 120); + const error = await rejection(acquiring); + + expect(error.message).to.equal('interrupted'); + expect(api.calls.at(-1)).to.include({ + method: 'DELETE', + path: '/device/sessions/brave-teal-otter', + }); + }); + + it('stops the session on release, and takes a session already gone as stopped', async () => { + const context = { + env: { DEVICE_CLOUD_API_KEY: 'key' }, + log: () => {}, + signal: new AbortController().signal, + }; + for (const status of [200, 404, 409]) { + const { api, provider } = setup({ + 'DELETE /device/sessions/brave-teal-otter': [{ body: {}, status }], + }); + await provider.release({ id: 'brave-teal-otter' }, context); + expect(api.calls).to.have.length(1); + expect(api.calls[0]).to.include({ + method: 'DELETE', + path: '/device/sessions/brave-teal-otter', + }); + } + + const { provider } = setup({ + 'DELETE /device/sessions/brave-teal-otter': [ + { body: { message: 'Something broke.' }, status: 500 }, + ], + }); + const error = await rejection( + provider.release({ id: 'brave-teal-otter' }, context), + ); + expect(error.message).to.include('Something broke.'); + }); + + describe('a test that records video', () => { + const context = (attemptId = 'attempt-1') => ({ + attemptId, + env: { DEVICE_CLOUD_API_KEY: 'key-from-env' }, + runId: 'run-1', + signal: new AbortController().signal, + targetName: 'android', + }); + const stopContext = { + dir: '/tmp/video', + signal: new AbortController().signal, + }; + const at = (iso: string) => () => Date.parse(iso); + + it("gets a console link to its part of the session's recording", async () => { + let clock = Date.parse('2026-11-25T10:00:10.000Z'); + const { api, provider } = setup( + { + 'GET /device/sessions/brave-teal-otter': [ + { body: session('active'), status: 200 }, + ], + }, + {}, + { now: () => clock }, + ); + + const recording = await provider.record( + { id: 'brave-teal-otter' }, + context(), + ); + expect(recording.startedAt).to.equal('2026-11-25T10:00:10.000Z'); + clock = Date.parse('2026-11-25T10:00:45.500Z'); + const result = await recording.stop(stopContext); + + expect(result).to.deep.equal({ + mediaType: 'text/html', + url: 'https://console.example/device/brave-teal-otter?from=2026-11-25T10%3A00%3A10.000Z&to=2026-11-25T10%3A00%3A45.500Z', + }); + // The session was read with the run's key; stopping asked for nothing. + expect(api.calls).to.have.length(1); + expect(api.calls[0].headers['x-app-api-key']).to.equal('key-from-env'); + }); + + it('reads the session once per lease, however many tests record', async () => { + const { api, provider } = setup( + { + 'GET /device/sessions/brave-teal-otter': [ + { body: session('active'), status: 200 }, + ], + }, + {}, + { now: at('2026-11-25T10:00:00.000Z') }, + ); + for (const attempt of ['attempt-1', 'attempt-2', 'attempt-3']) { + const recording = await provider.record( + { id: 'brave-teal-otter' }, + context(attempt), + ); + await recording.stop(stopContext); + } + + expect(api.calls.map((c) => `${c.method} ${c.path}`)).to.deep.equal([ + 'GET /device/sessions/brave-teal-otter', + ]); + }); + + it('fails, named, when the session cannot be read, and reads it again next time', async () => { + const { api, provider } = setup( + { + 'GET /device/sessions/brave-teal-otter': [ + { body: { message: 'Device session not found.' }, status: 404 }, + { + body: session('active', { monitor_url: undefined }), + status: 200, + }, + { body: session('active'), status: 200 }, + ], + }, + {}, + { now: at('2026-11-25T10:00:00.000Z') }, + ); + + const gone = await rejection( + provider.record({ id: 'brave-teal-otter' }, context()), + ); + expect(gone.message).to.include( + 'reading device session brave-teal-otter', + ); + expect(gone.message).to.include('Device session not found.'); + const noPage = await rejection( + provider.record({ id: 'brave-teal-otter' }, context()), + ); + expect(noPage.message).to.include('has no console page'); + const recording = await provider.record( + { id: 'brave-teal-otter' }, + context(), + ); + expect((await recording.stop(stopContext)).url).to.match( + /^https:\/\/console\.example\/device\/brave-teal-otter\?from=/, + ); + expect(api.calls).to.have.length(3); + }); + }); +}); diff --git a/test/unit/encrypt-help.test.ts b/test/unit/encrypt-help.test.ts index 871ce2a..616f635 100644 --- a/test/unit/encrypt-help.test.ts +++ b/test/unit/encrypt-help.test.ts @@ -9,8 +9,9 @@ import { cloudCommand } from '../../src/commands/cloud.js'; import { uploadCommand } from '../../src/commands/upload.js'; /** - * Client-side encryption is on by default (dcd#1138), so --encrypt is listed - * in --help, and --no-encrypt, the per-run opt-out, must parse. + * Uploads are always encrypted (dcd#1138). --encrypt stays as a no-op so old + * scripts still run, and --no-encrypt must still parse so it can be ignored + * with a warning rather than fail. */ const commands: Array<[string, CommandDef]> = [ ['cloud', cloudCommand as CommandDef], @@ -24,10 +25,11 @@ async function argsOf(cmd: CommandDef): Promise { describe('--encrypt flag', () => { for (const [name, cmd] of commands) { describe(`dcd ${name}`, () => { - it('lists encrypt in the usage, with the opt-out', async () => { + it('lists encrypt in the usage, as no longer needed', async () => { const usage = await renderUsage(cmd); expect(usage).to.contain('--encrypt'); - expect(usage).to.contain('--no-encrypt or DCD_ENCRYPT=0 turns it off'); + expect(usage).to.contain('always encrypted'); + expect(usage).to.not.contain('turns it off'); }); it('parses --encrypt and --no-encrypt', async () => { diff --git a/test/unit/encryption-decision.test.ts b/test/unit/encryption-decision.test.ts index 2621498..75e26e1 100644 --- a/test/unit/encryption-decision.test.ts +++ b/test/unit/encryption-decision.test.ts @@ -1,167 +1,79 @@ import { expect } from 'chai'; -import { - type EncryptionDecision, - resolveEncryption, -} from '../../src/utils/envelope.js'; +import { resolveEncryption } from '../../src/utils/envelope.js'; /** - * The order that decides whether a run encrypts (dcd#1138): an explicit flag, - * then DCD_ENCRYPT (or its legacy alias), then the server default from the - * compatibility data, then off. Every case passes `env` explicitly so the - * developer's own shell can't leak in. + * Uploads are always encrypted (dcd#1138). The old opt-outs, --no-encrypt and + * DCD_ENCRYPT=0 (or its legacy alias), are ignored with a warning. Every case + * passes `env` explicitly so the developer's own shell can't leak in. */ describe('resolveEncryption', () => { - const on = (source: EncryptionDecision['source']) => ({ enabled: true, source }); - const off = (source: EncryptionDecision['source']) => ({ enabled: false, source }); + const ON = { enabled: true, source: 'always' }; - it('is off when nothing is set', () => { - expect(resolveEncryption({ env: {} })).to.deep.equal(off('off')); + it('is on when nothing is set', () => { + expect(resolveEncryption({ env: {} })).to.deep.equal(ON); }); - it('treats a missing server field (an older API) as off', () => { - expect(resolveEncryption({ env: {}, serverDefault: undefined })).to.deep.equal( - off('off'), - ); + it('is on with --encrypt, which is now a no-op', () => { + expect(resolveEncryption({ env: {}, flag: true })).to.deep.equal(ON); }); - it('is off when the server default is explicitly off', () => { - expect(resolveEncryption({ env: {}, serverDefault: false })).to.deep.equal( - off('off'), - ); + it('is on with DCD_ENCRYPT=1', () => { + expect(resolveEncryption({ env: { DCD_ENCRYPT: '1' } })).to.deep.equal(ON); }); - it('follows the server default when neither the flag nor the env decides', () => { - expect(resolveEncryption({ env: {}, serverDefault: true })).to.deep.equal( - on('server'), - ); - }); - - describe('an explicit flag', () => { - it('--encrypt turns it on with nothing else set', () => { - expect(resolveEncryption({ env: {}, flag: true })).to.deep.equal(on('flag')); - }); - - it('--no-encrypt beats DCD_ENCRYPT=1', () => { - expect( - resolveEncryption({ env: { DCD_ENCRYPT: '1' }, flag: false }), - ).to.deep.equal(off('flag')); - }); - - it('--no-encrypt beats the server default', () => { - expect( - resolveEncryption({ env: {}, flag: false, serverDefault: true }), - ).to.deep.equal(off('flag')); - }); - - it('--encrypt beats DCD_ENCRYPT=0', () => { - expect( - resolveEncryption({ env: { DCD_ENCRYPT: '0' }, flag: true }), - ).to.deep.equal(on('flag')); + it('ignores --no-encrypt, and says so', () => { + expect(resolveEncryption({ env: {}, flag: false })).to.deep.equal({ + ...ON, + notice: 'Ignoring --no-encrypt: uploads are always encrypted.', }); }); - describe('the env var', () => { - for (const value of ['1', 'true', 'TRUE', 'True', ' 1 ']) { - it(`reads DCD_ENCRYPT=${JSON.stringify(value)} as on`, () => { - expect(resolveEncryption({ env: { DCD_ENCRYPT: value } })).to.deep.equal( - on('env'), - ); - }); - } - - for (const value of ['0', 'false', 'FALSE', 'False']) { - it(`reads DCD_ENCRYPT=${JSON.stringify(value)} as off, beating the server default`, () => { - expect( - resolveEncryption({ env: { DCD_ENCRYPT: value }, serverDefault: true }), - ).to.deep.equal(off('env')); - }); - } - - for (const value of ['', 'yes', 'on', '2']) { - it(`ignores DCD_ENCRYPT=${JSON.stringify(value)}, leaving the server default to decide`, () => { - expect( - resolveEncryption({ env: { DCD_ENCRYPT: value }, serverDefault: true }), - ).to.deep.equal(on('server')); - expect(resolveEncryption({ env: { DCD_ENCRYPT: value } })).to.deep.equal( - off('off'), - ); + for (const value of ['0', 'false', 'FALSE', 'False', ' 0 ']) { + it(`ignores DCD_ENCRYPT=${JSON.stringify(value)}, and says so`, () => { + expect(resolveEncryption({ env: { DCD_ENCRYPT: value } })).to.deep.equal({ + ...ON, + notice: 'Ignoring DCD_ENCRYPT: uploads are always encrypted.', }); - } - - it('honours the legacy DCD_ENCRYPT_BINARIES alias both ways', () => { - expect( - resolveEncryption({ env: { DCD_ENCRYPT_BINARIES: '1' } }), - ).to.deep.equal(on('env')); - expect( - resolveEncryption({ - env: { DCD_ENCRYPT_BINARIES: 'false' }, - serverDefault: true, - }), - ).to.deep.equal(off('env')); }); + } - it('lets DCD_ENCRYPT win when both are set', () => { - expect( - resolveEncryption({ - env: { DCD_ENCRYPT: '0', DCD_ENCRYPT_BINARIES: '1' }, - }), - ).to.deep.equal(off('env')); - expect( - resolveEncryption({ - env: { DCD_ENCRYPT: 'true', DCD_ENCRYPT_BINARIES: '0' }, - }), - ).to.deep.equal(on('env')); + it('ignores the legacy DCD_ENCRYPT_BINARIES=0, and says so', () => { + expect(resolveEncryption({ env: { DCD_ENCRYPT_BINARIES: '0' } })).to.deep.equal({ + ...ON, + notice: 'Ignoring DCD_ENCRYPT_BINARIES: uploads are always encrypted.', }); + }); - it('falls back to the alias when DCD_ENCRYPT is set to something unreadable', () => { - expect( - resolveEncryption({ - env: { DCD_ENCRYPT: 'yes', DCD_ENCRYPT_BINARIES: '1' }, - }), - ).to.deep.equal(on('env')); + it('names every ignored opt-out in one line', () => { + expect( + resolveEncryption({ + env: { DCD_ENCRYPT: '0', DCD_ENCRYPT_BINARIES: 'false' }, + flag: false, + }), + ).to.deep.equal({ + ...ON, + notice: + 'Ignoring --no-encrypt and DCD_ENCRYPT and DCD_ENCRYPT_BINARIES: uploads are always encrypted.', }); }); + for (const value of ['', 'yes', 'on', '2', '1', 'true']) { + it(`gives no notice for DCD_ENCRYPT=${JSON.stringify(value)}`, () => { + expect(resolveEncryption({ env: { DCD_ENCRYPT: value } })).to.deep.equal(ON); + }); + } + it('reads process.env when no env is passed', () => { const original = process.env.DCD_ENCRYPT; try { - process.env.DCD_ENCRYPT = '1'; - expect(resolveEncryption({})).to.deep.equal(on('env')); + process.env.DCD_ENCRYPT = '0'; + expect(resolveEncryption().notice).to.equal( + 'Ignoring DCD_ENCRYPT: uploads are always encrypted.', + ); } finally { if (original === undefined) delete process.env.DCD_ENCRYPT; else process.env.DCD_ENCRYPT = original; } }); - - describe('full matrix', () => { - const flags = [undefined, true, false] as const; - const envs: Array<[string, Record, boolean | undefined]> = [ - ['unset', {}, undefined], - ['DCD_ENCRYPT=1', { DCD_ENCRYPT: '1' }, true], - ['DCD_ENCRYPT=0', { DCD_ENCRYPT: '0' }, false], - ]; - const serverDefaults = [undefined, true, false] as const; - - for (const flag of flags) { - for (const [envLabel, env, envValue] of envs) { - for (const serverDefault of serverDefaults) { - const expected: EncryptionDecision = - flag !== undefined - ? { enabled: flag, source: 'flag' } - : envValue !== undefined - ? { enabled: envValue, source: 'env' } - : serverDefault === true - ? on('server') - : off('off'); - - it(`flag=${String(flag)}, ${envLabel}, server=${String(serverDefault)} → ${expected.enabled ? 'on' : 'off'} (${expected.source})`, () => { - expect(resolveEncryption({ env, flag, serverDefault })).to.deep.equal( - expected, - ); - }); - } - } - } - }); }); diff --git a/test/unit/fetch-http-stack.test.ts b/test/unit/fetch-http-stack.test.ts new file mode 100644 index 0000000..bd36e90 --- /dev/null +++ b/test/unit/fetch-http-stack.test.ts @@ -0,0 +1,109 @@ +import { expect } from 'chai'; +import { createReadStream, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer, type IncomingMessage, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import * as tus from 'tus-js-client'; + +import { FetchHttpStack, tusHttpStackOptions } from '../../src/gateways/fetch-http-stack.js'; + +/** + * The standalone binary runs on Bun, whose node:http can't send tus's + * upload-creating POST, so it uploads through FetchHttpStack instead. + */ +describe('FetchHttpStack', () => { + let server: Server; + let endpoint: string; + let dir: string; + let received: Buffer; + let requests: string[]; + + const readAll = async (req: IncomingMessage): Promise => { + const parts: Buffer[] = []; + for await (const part of req) parts.push(part as Buffer); + return Buffer.concat(parts); + }; + + // A minimal tus server: POST creates (with data), PATCH appends. + beforeEach(async () => { + received = Buffer.alloc(0); + requests = []; + dir = mkdtempSync(join(tmpdir(), 'dcd-tus-')); + server = createServer(async (req, res) => { + const body = await readAll(req); + requests.push(`${req.method} ${body.length} ${req.headers['x-upsert'] ?? ''}`); + received = Buffer.concat([received, body]); + const headers = { 'Tus-Resumable': '1.0.0', 'Upload-Offset': String(received.length) }; + if (req.method === 'POST') { + res.writeHead(201, { ...headers, Location: `${endpoint}/upload-1` }); + } else { + res.writeHead(204, headers); + } + res.end(); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + endpoint = `http://127.0.0.1:${(server.address() as AddressInfo).port}/files`; + }); + + afterEach(async () => { + rmSync(dir, { recursive: true, force: true }); + // fetch keeps its connections alive, which would hold close() open. + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + }); + + it('uploads a file stream in chunks, data on create', async () => { + const file = join(dir, 'app.bin'); + const content = Buffer.from(Array.from({ length: 2500 }, (_, i) => i % 251)); + writeFileSync(file, content); + const progress: number[] = []; + + await new Promise((resolve, reject) => { + new tus.Upload(createReadStream(file), { + endpoint, + uploadSize: content.length, + chunkSize: 1000, + uploadDataDuringCreation: true, + retryDelays: [], + headers: { 'x-upsert': 'true' }, + httpStack: new FetchHttpStack(), + onProgress: (sent) => progress.push(sent), + onError: reject, + onSuccess: () => resolve(), + }).start(); + }); + + expect(received.equals(content)).to.equal(true); + expect(requests).to.deep.equal(['POST 1000 true', 'PATCH 1000 true', 'PATCH 500 true']); + expect(progress.at(-1)).to.equal(content.length); + }); + + it('turns a server error into a tus error', async () => { + server.removeAllListeners('request'); + server.on('request', (_req, res) => { + res.writeHead(403, { 'Tus-Resumable': '1.0.0' }); + res.end('denied'); + }); + + const error = await new Promise((resolve, reject) => { + new tus.Upload(Buffer.from('abc'), { + endpoint, + retryDelays: [], + httpStack: new FetchHttpStack(), + onError: resolve, + onSuccess: () => reject(new Error('expected the upload to fail')), + }).start(); + }); + + expect(error.message).to.contain('response code: 403'); + expect(error.message).to.contain('denied'); + }); + + it('is used under Bun only, and leaves no httpStack key under Node', () => { + expect(tusHttpStackOptions(true).httpStack).to.be.instanceOf(FetchHttpStack); + // An explicit `httpStack: undefined` would replace tus's default stack. + expect(tusHttpStackOptions(false)).to.deep.equal({}); + }); +}); diff --git a/test/unit/kek-from-api.test.ts b/test/unit/kek-from-api.test.ts index a57a5b1..720863f 100644 --- a/test/unit/kek-from-api.test.ts +++ b/test/unit/kek-from-api.test.ts @@ -128,11 +128,9 @@ describe('KEK public key from /cli-config', () => { it('passes a decision through when the API publishes a key', async () => { stubFetch(() => json({ binary_kek_public_key: { version: 1, key: rawPublicKey() } })); - for (const source of ['flag', 'env', 'server'] as const) { - expect( - await checkKekForEncryption({ enabled: true, source }, 'https://api.dev.devicecloud.dev'), - ).to.deep.equal({ enabled: true, source }); - } + expect( + await checkKekForEncryption({ enabled: true, source: 'always' }, 'https://api.dev.devicecloud.dev'), + ).to.deep.equal({ enabled: true, source: 'always' }); }); it('passes a decision to stay off through without asking the API', async () => { @@ -144,50 +142,36 @@ describe('KEK public key from /cli-config', () => { expect(requested).to.deep.equal([]); }); - for (const source of ['env', 'server'] as const) { - it(`skips ${source} encryption when the API publishes no key, with a notice`, async () => { - stubFetch(() => json({ supabase_publishable_key: 'sb_publishable_x' })); - const decision = await checkKekForEncryption({ enabled: true, source }, NO_KEK); - expect(decision).to.include({ enabled: false, source }); - expect(decision.notice).to.contain(NO_KEK); - expect(decision.notice).to.contain('DCD_BINARY_KEK_PUBLIC'); - expect(decision.notice).to.not.contain('\n'); - }); - } - - it('refuses an explicit --encrypt when the API publishes no key', async () => { + it('skips encryption when the API publishes no key, with a notice', async () => { stubFetch(() => json({ supabase_publishable_key: 'sb_publishable_x' })); - let message = ''; - try { - await checkKekForEncryption({ enabled: true, source: 'flag' }, NO_KEK); - } catch (error) { - message = (error as Error).message; - } - expect(message).to.match(/--encrypt needs the KEK public key.*DCD_BINARY_KEK_PUBLIC/); + const decision = await checkKekForEncryption( + { enabled: true, notice: 'Ignoring DCD_ENCRYPT: uploads are always encrypted.', source: 'always' }, + NO_KEK, + ); + expect(decision).to.include({ enabled: false, source: 'no_kek' }); + expect(decision.notice).to.contain(NO_KEK); + expect(decision.notice).to.contain('DCD_BINARY_KEK_PUBLIC'); + expect(decision.notice).to.not.contain('\n'); }); it('fails closed rather than uploading plaintext when the API cannot be asked', async () => { stubFetch(() => json({}, 503)); - for (const source of ['flag', 'env', 'server'] as const) { - let failed = false; - try { - await checkKekForEncryption({ enabled: true, source }, NO_KEK); - } catch { - failed = true; - } - expect(failed, source).to.equal(true); + let failed = false; + try { + await checkKekForEncryption({ enabled: true, source: 'always' }, NO_KEK); + } catch { + failed = true; } + expect(failed).to.equal(true); }); - it('lets DCD_BINARY_KEK_PUBLIC unlock any API, whatever the source', async () => { + it('lets DCD_BINARY_KEK_PUBLIC unlock any API', async () => { process.env.DCD_BINARY_KEK_PUBLIC = `7:${rawPublicKey()}`; stubFetch(() => json({}, 500)); - for (const source of ['flag', 'env', 'server'] as const) { - expect(await checkKekForEncryption({ enabled: true, source }, NO_KEK)).to.deep.equal({ - enabled: true, - source, - }); - } + expect(await checkKekForEncryption({ enabled: true, source: 'always' }, NO_KEK)).to.deep.equal({ + enabled: true, + source: 'always', + }); expect(requested).to.deep.equal([]); }); }); diff --git a/test/unit/mcp-bridge.test.ts b/test/unit/mcp-bridge.test.ts index 4de9808..e9e9be5 100644 --- a/test/unit/mcp-bridge.test.ts +++ b/test/unit/mcp-bridge.test.ts @@ -430,6 +430,8 @@ describe('dcd mcp bridge', () => { return new Response(JSON.stringify({ id: 'b-1', upload: { path: 'p', signedUrl: 'https://sb.example/put' }, mirror: null })); } + // No KEK published, so the bundle goes up in plaintext. + if (url.endsWith('/cli-config')) return new Response(JSON.stringify({ supabase_publishable_key: 'sb_publishable_test' })); if (url === 'https://sb.example/put') return new Response(null, { status: 200 }); if (url.endsWith('/device/bundles')) { return new Response(JSON.stringify({ bundle: { id: 'b-1', sha: 's', bytes: 1, encrypted: false, created_at: 'now' } })); diff --git a/test/unit/report-download.service.test.ts b/test/unit/report-download.service.test.ts index 06ae46c..b7674b4 100644 --- a/test/unit/report-download.service.test.ts +++ b/test/unit/report-download.service.test.ts @@ -48,7 +48,6 @@ before(async () => { /** `zip` cut off before its central directory, as a dropped stream leaves it. */ const truncated = (zip: Buffer) => zip.subarray(0, Math.floor(zip.length / 2)); -// eslint-disable-next-line @typescript-eslint/no-explicit-any const originalFetch = (global as any).fetch; /** @@ -63,7 +62,6 @@ function mockFetch(status: number, responseBody?: Buffer | string) { const encoder = new TextEncoder(); // Default: a complete ZIP, the body a successful artifacts download has. const body = responseBody ?? INLINE_ZIP; - // eslint-disable-next-line @typescript-eslint/no-explicit-any (global as any).fetch = async ( input: URL | string, init?: RequestInit, @@ -91,7 +89,6 @@ function mockFetch(status: number, responseBody?: Buffer | string) { } function restoreFetch() { - // eslint-disable-next-line @typescript-eslint/no-explicit-any (global as any).fetch = originalFetch; captured = null; } @@ -620,6 +617,155 @@ describe('ReportDownloadService', () => { expect(fs.readFileSync(outPath).equals(INLINE_ZIP)).to.be.true; }); + // The inline route gives these answers too, so asking it again only cost + // a second request for the same error. + describe('a manifest answer the inline route would repeat', () => { + const cases = [ + { + expected: 'Invalid request: resultId must be a positive whole number', + message: 'resultId must be a positive whole number', + status: 400, + }, + { + expected: 'Access denied. This upload belongs to another team', + message: 'This upload belongs to another team', + status: 403, + }, + { + expected: 'Resource not found. No results found for uploadId=run-42', + message: 'No results found for uploadId=run-42', + status: 404, + }, + ]; + + for (const { expected, message, status } of cases) { + it(`shows an artifacts ${status} without asking the inline route`, async () => { + mockBundleFetch({ + manifestBody: { message, statusCode: status }, + manifestStatus: status, + }); + const warnings: string[] = []; + + const result = await service.downloadArtifacts({ + ...BASE, + artifactsPath: path.join(tempDir, `final-${status}.zip`), + downloadType: 'ALL', + warnLogger: (msg) => warnings.push(msg), + }); + + expect(result.ok).to.be.false; + expect(warnings[0]).to.equal(`Failed to download artifacts: ${expected}`); + expect(calls).to.have.length(1); + expect(calls.some((c) => c.url.endsWith('/download'))).to.be.false; + expect(fallbacks).to.deep.equal([]); + }); + + it(`shows an html report ${status} without asking the inline route`, async () => { + mockBundleFetch({ + manifestBody: { message, statusCode: status }, + manifestStatus: status, + }); + const warnings: string[] = []; + + await service.downloadReports({ + ...BASE, + htmlPath: path.join(tempDir, `final-report-${status}.zip`), + reportType: 'html', + warnLogger: (msg) => warnings.push(msg), + }); + + // The same text the inline route's answer gave. + expect(warnings[0]).to.equal( + status === 404 + ? "Failed to download HTML report: Upload ID 'run-42' not found or no HTML report available for this upload" + : `Failed to download HTML report: Failed to download HTML report: ${status} ${JSON.stringify({ message, statusCode: status })}`, + ); + expect(calls).to.have.length(1); + expect(calls.some((c) => c.url.endsWith('/html-report'))).to.be.false; + expect(fallbacks).to.deep.equal([]); + }); + } + + for (const status of [413, 500]) { + it(`still falls back on a manifest ${status}`, async () => { + mockBundleFetch({ + manifestBody: { message: 'no' }, + manifestStatus: status, + }); + const outPath = path.join(tempDir, `fallback-${status}.zip`); + + const result = await service.downloadArtifacts({ + ...BASE, + artifactsPath: outPath, + downloadType: 'ALL', + }); + + expect(result.ok).to.be.true; + expect(fallbacks[0]).to.include({ + reason: 'manifest_http_error', + status, + }); + expect( + calls.some((c) => c.method === 'POST' && c.url.endsWith('/download')), + ).to.be.true; + expect(fs.readFileSync(outPath).equals(INLINE_ZIP)).to.be.true; + }); + } + }); + + // A folder as the artifacts path failed with EISDIR, which the + // CLI took for a broken stream, so it fell back to the inline download + // (the API building the whole ZIP) and then failed the same way. + describe('folder and local file paths', () => { + it('saves artifacts.zip inside an existing folder', async () => { + mockBundleFetch(); + const dir = fs.mkdtempSync(path.join(tempDir, 'shard-')); + + const result = await service.downloadArtifacts({ + ...BASE, + artifactsPath: dir, + downloadType: 'ALL', + }); + + const file = path.join(dir, 'artifacts.zip'); + expect(result).to.include({ ok: true, path: file }); + expect(fs.readFileSync(file).equals(BUNDLE_ZIP)).to.be.true; + expect(fallbacks).to.deep.equal([]); + }); + + it('creates a folder given with a trailing separator', async () => { + mockBundleFetch(); + const dir = path.join(tempDir, 'not-yet', 'here') + path.sep; + + const result = await service.downloadArtifacts({ + ...BASE, + artifactsPath: dir, + downloadType: 'ALL', + }); + + const file = path.join(dir, 'artifacts.zip'); + expect(result).to.include({ ok: true, path: file }); + expect(fs.readFileSync(file).equals(BUNDLE_ZIP)).to.be.true; + }); + + it('reports a destination it cannot write, without falling back', async () => { + mockBundleFetch(); + // A file where a parent folder should be: mkdir fails (ENOTDIR/EEXIST). + const blocker = path.join(tempDir, 'blocker.txt'); + fs.writeFileSync(blocker, 'x'); + + const result = await service.downloadArtifacts({ + ...BASE, + artifactsPath: path.join(blocker, 'artifacts.zip'), + downloadType: 'ALL', + }); + + expect(result.ok).to.be.false; + expect(fallbacks).to.deep.equal([]); + expect(calls.some((c) => c.url.endsWith('/download'))).to.be.false; + }); + }); + describe('records why it fell back', () => { const download = (name: string) => service.downloadArtifacts({ diff --git a/test/unit/signed-upload.test.ts b/test/unit/signed-upload.test.ts new file mode 100644 index 0000000..a69bf94 --- /dev/null +++ b/test/unit/signed-upload.test.ts @@ -0,0 +1,300 @@ +import { expect } from 'chai'; +import * as fs from 'node:fs'; +import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import * as os from 'node:os'; +import * as path from 'node:path'; + +import { resetCliConfigCache } from '../../src/config/cli-config.js'; +import { ApiGateway } from '../../src/gateways/api-gateway.js'; +import { + isSignatureError, + type SignedUpload, + SupabaseGateway, +} from '../../src/gateways/supabase-gateway.js'; +import { uploadSupabaseCopy } from '../../src/methods.js'; + +/** + * Uploads straight to the final storage path with a signed token. Storage + * checks the token on every TUS request, so the client has to send it as + * `x-signature` each time, and get a fresh one when it is refused or about + * to expire. + */ + +interface SeenRequest { + method: string; + objectName?: string; + signature?: string; + upsert?: string; + url: string; +} + +/** Decode tus's `Upload-Metadata` header (`key base64,key base64`). */ +function objectNameOf(header: string | undefined): string | undefined { + for (const pair of (header ?? '').split(',')) { + const [key, value] = pair.trim().split(' '); + if (key === 'objectName' && value) return Buffer.from(value, 'base64').toString(); + } + + return undefined; +} + +/** + * A minimal TUS server: creation with data in one request, which is all a + * file smaller than one chunk needs. `refuse` decides, per request, whether + * to answer like Storage does for a bad signature. + */ +function startTusServer(refuse: (signature: string | undefined, n: number) => boolean): Promise<{ + seen: SeenRequest[]; + server: Server; + url: string; +}> { + const seen: SeenRequest[] = []; + const server = createServer((req: IncomingMessage, res: ServerResponse) => { + const chunks: Buffer[] = []; + req.on('data', (c: Buffer) => chunks.push(c)); + req.on('end', () => { + const signature = req.headers['x-signature'] as string | undefined; + seen.push({ + method: req.method ?? '', + objectName: objectNameOf(req.headers['upload-metadata'] as string | undefined), + signature, + upsert: req.headers['x-upsert'] as string | undefined, + url: req.url ?? '', + }); + + res.setHeader('Tus-Resumable', '1.0.0'); + if (refuse(signature, seen.length)) { + res.writeHead(400, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ error: 'InvalidJWT', message: 'jwt expired', statusCode: '400' })); + return; + } + + const received = Buffer.concat(chunks).length; + res.writeHead(201, { + Location: `${req.url}/upload-1`, + 'Upload-Offset': String(received), + }); + res.end(); + }); + }); + + return new Promise((resolve) => { + server.listen(0, '127.0.0.1', () => { + const { port } = server.address() as AddressInfo; + resolve({ seen, server, url: `http://127.0.0.1:${port}` }); + }); + }); +} + +describe('isSignatureError', () => { + it('spots a refused token', () => { + expect(isSignatureError(400, '{"error":"InvalidJWT","message":"jwt expired"}')).to.equal(true); + expect(isSignatureError(403, 'invalid signature')).to.equal(true); + }); + + it('spots the messages Storage actually sends', () => { + expect(isSignatureError(400, '"exp" claim timestamp check failed')).to.equal(true); + expect(isSignatureError(400, 'The provided token has expired.')).to.equal(true); + expect(isSignatureError(400, 'Invalid Compact JWS')).to.equal(true); + expect(isSignatureError(400, 'Invalid signature')).to.equal(true); + }); + + it('leaves other failures alone', () => { + expect(isSignatureError(500, 'jwt expired')).to.equal(false); + expect(isSignatureError(400, 'The resource already exists')).to.equal(false); + }); +}); + +describe('SupabaseGateway.uploadResumableSigned', () => { + const realFetch = globalThis.fetch; + let tempDir: string; + let source: { contentType: string; diskPath: string; name: string; size: number }; + let server: Server | undefined; + + beforeEach(() => { + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'dcd-signed-upload-')); + const diskPath = path.join(tempDir, 'app.apk'); + fs.writeFileSync(diskPath, Buffer.alloc(1024, 7)); + source = { contentType: 'application/vnd.android.package-archive', diskPath, name: 'app.apk', size: 1024 }; + + // The publishable key comes from the API's /cli-config. + resetCliConfigCache(); + globalThis.fetch = (async () => + new Response(JSON.stringify({ supabase_publishable_key: 'sb_publishable_test' }), { + headers: { 'content-type': 'application/json' }, + })) as typeof fetch; + }); + + afterEach(() => { + globalThis.fetch = realFetch; + resetCliConfigCache(); + server?.close(); + server = undefined; + fs.rmSync(tempDir, { force: true, recursive: true }); + }); + + const signed: SignedUpload = { expiresInSeconds: 7200, path: '1/binaries/android/abc.apk', token: 't1' }; + + it('sends the token to the signed endpoint for the final path, without upsert', async () => { + const tus = await startTusServer(() => false); + server = tus.server; + + await SupabaseGateway.uploadResumableSigned('dev', signed, source, async () => { + throw new Error('no refresh expected'); + }, false, { storageUrl: tus.url }); + + expect(tus.seen).to.have.length(1); + expect(tus.seen[0]).to.include({ + method: 'POST', + objectName: '1/binaries/android/abc.apk', + signature: 't1', + url: '/storage/v1/upload/resumable/sign', + }); + expect(tus.seen[0].upsert).to.equal(undefined); + }); + + it('gets a fresh token and carries on when the token is refused', async () => { + const tus = await startTusServer((signature) => signature === 't1'); + server = tus.server; + const refreshed: string[] = []; + + await SupabaseGateway.uploadResumableSigned( + 'dev', + signed, + source, + async (p) => { + refreshed.push(p); + return { ...signed, token: 't2' }; + }, + false, + { retryDelays: [0, 0, 0], storageUrl: tus.url }, + ); + + expect(refreshed).to.deep.equal(['1/binaries/android/abc.apk']); + expect(tus.seen.map((r) => r.signature)).to.deep.equal(['t1', 't2']); + }); + + it('refreshes before the first request when the token is about to expire', async () => { + const tus = await startTusServer(() => false); + server = tus.server; + + await SupabaseGateway.uploadResumableSigned( + 'dev', + { ...signed, expiresInSeconds: 0 }, + source, + async () => ({ ...signed, token: 'fresh' }), + false, + { storageUrl: tus.url }, + ); + + expect(tus.seen.map((r) => r.signature)).to.deep.equal(['fresh']); + }); + + it('gives up after a bounded number of refreshes', async () => { + const tus = await startTusServer(() => true); + server = tus.server; + let refreshes = 0; + + let failure: unknown; + try { + await SupabaseGateway.uploadResumableSigned( + 'dev', + signed, + source, + async () => { + refreshes += 1; + return { ...signed, token: `t${refreshes + 1}` }; + }, + false, + { retryDelays: Array.from({ length: 20 }, () => 0), storageUrl: tus.url }, + ); + } catch (error) { + failure = error; + } + + expect(failure).to.be.instanceOf(Error); + expect(refreshes).to.equal(5); + }); +}); + +describe('uploadSupabaseCopy', () => { + const realSigned = SupabaseGateway.uploadResumableSigned; + const realTemp = SupabaseGateway.uploadResumable; + const realRefresh = ApiGateway.refreshUploadToken; + let calls: string[]; + + const base = { + apiUrl: 'http://localhost:9999', + auth: { headers: {} } as never, + debug: false, + env: 'dev' as const, + source: { contentType: 'application/zip', diskPath: '/nowhere', name: 'f.zip', size: 1 }, + tempPath: 'uploads/abc/abc.zip', + }; + const signedUpload: SignedUpload = { expiresInSeconds: 7200, path: '1/tests/abc.zip', token: 't' }; + + beforeEach(() => { + calls = []; + SupabaseGateway.uploadResumable = (async (_env: string, p: string) => { + calls.push(`temp:${p}`); + }) as typeof SupabaseGateway.uploadResumable; + }); + + afterEach(() => { + SupabaseGateway.uploadResumableSigned = realSigned; + SupabaseGateway.uploadResumable = realTemp; + ApiGateway.refreshUploadToken = realRefresh; + }); + + it('goes straight to the final path when a signed upload is offered', async () => { + SupabaseGateway.uploadResumableSigned = (async (_env: string, s: SignedUpload) => { + calls.push(`signed:${s.path}`); + }) as typeof SupabaseGateway.uploadResumableSigned; + + const outcome = await uploadSupabaseCopy({ ...base, signedUpload }); + + expect(outcome).to.deep.equal({ direct: true, path: '1/tests/abc.zip', result: { error: null, success: true } }); + expect(calls).to.deep.equal(['signed:1/tests/abc.zip']); + }); + + it('asks the API for a fresh token for the same path', async () => { + let refreshedFor: string | undefined; + ApiGateway.refreshUploadToken = (async (_url: string, _auth: unknown, p: string) => { + refreshedFor = p; + return signedUpload; + }) as typeof ApiGateway.refreshUploadToken; + SupabaseGateway.uploadResumableSigned = (async ( + _env: string, + s: SignedUpload, + _source: unknown, + refresh: (p: string) => Promise, + ) => { + await refresh(s.path); + }) as typeof SupabaseGateway.uploadResumableSigned; + + await uploadSupabaseCopy({ ...base, signedUpload }); + + expect(refreshedFor).to.equal('1/tests/abc.zip'); + }); + + it('falls back to the temp path when the signed upload fails', async () => { + SupabaseGateway.uploadResumableSigned = (async () => { + throw new Error('refused'); + }) as typeof SupabaseGateway.uploadResumableSigned; + + const outcome = await uploadSupabaseCopy({ ...base, signedUpload }); + + expect(outcome.direct).to.equal(false); + expect(outcome.path).to.equal('uploads/abc/abc.zip'); + expect(outcome.result.success).to.equal(true); + expect(calls).to.deep.equal(['temp:uploads/abc/abc.zip']); + }); + + it('uses the temp path when no signed upload is offered', async () => { + const outcome = await uploadSupabaseCopy(base); + + expect(outcome.direct).to.equal(false); + expect(calls).to.deep.equal(['temp:uploads/abc/abc.zip']); + }); +}); diff --git a/test/unit/styling.test.ts b/test/unit/styling.test.ts new file mode 100644 index 0000000..0944139 --- /dev/null +++ b/test/unit/styling.test.ts @@ -0,0 +1,98 @@ +import { expect } from 'chai'; +import { execFileSync } from 'node:child_process'; +import * as path from 'node:path'; +import { pathToFileURL } from 'node:url'; + +/** + * Colour support is decided once per process from its streams and env, so each + * case runs the styling module in a child process whose stdout and stderr are + * pipes, never the terminal mocha may be running in. + */ +const stylingUrl = pathToFileURL(path.resolve('src/utils/styling.ts')).href; + +const probe = ` +const { colors, forStderr, symbols } = await import(${JSON.stringify(stylingUrl)}); +process.stdout.write(JSON.stringify({ + bold: colors.bold('b'), + dimNull: colors.dim(null), + empty: colors.dim(''), + error: colors.error('e'), + forStderr: forStderr('\\u001B[31mx\\u001B[39m'), + lines: colors.dim('\\none\\r\\ntwo'), + nested: colors.dim('a' + colors.highlight('b') + 'c'), + success: symbols.success, + url: colors.url('u'), + urlLines: colors.url('u\\nv'), +})); +`; + +function runProbe(env: Record): Record { + const inherited = { ...process.env }; + delete inherited.FORCE_COLOR; + delete inherited.NO_COLOR; + delete inherited.NODE_DISABLE_COLORS; + const out = execFileSync( + process.execPath, + ['--import', 'tsx/esm', '--input-type=module', '-e', probe], + { encoding: 'utf8', env: { ...inherited, ...env }, stdio: ['ignore', 'pipe', 'pipe'] }, + ); + return JSON.parse(out) as Record; +} + +describe('styling', function () { + // Each case starts a node + tsx child process. + this.timeout(30_000); + + it('prints plain text when stdout is not a terminal', () => { + const r = runProbe({}); + expect(r.bold).to.equal('b'); + expect(r.error).to.equal('e'); + expect(r.url).to.equal('u'); + expect(r.success).to.equal('✓'); + }); + + it('strips colour bound for stderr when stderr is not a terminal', () => { + expect(runProbe({}).forStderr).to.equal('x'); + }); + + it('colours under FORCE_COLOR, nesting formats for url', () => { + const r = runProbe({ FORCE_COLOR: '1' }); + expect(r.bold).to.equal('\u001B[1mb\u001B[22m'); + expect(r.error).to.equal('\u001B[31me\u001B[39m'); + expect(r.url).to.equal('\u001B[36m\u001B[4mu\u001B[24m\u001B[39m'); + expect(r.success).to.equal('\u001B[32m✓\u001B[39m'); + }); + + // The bytes chalk produced, which the CLI's output must keep on every runtime. + it('re-opens the outer colour after a nested span', () => { + expect(runProbe({ FORCE_COLOR: '1' }).nested).to.equal( + '\u001B[90ma\u001B[36mb\u001B[39m\u001B[90mc\u001B[39m', + ); + }); + + it('closes and re-opens colour around each line break', () => { + const r = runProbe({ FORCE_COLOR: '1' }); + expect(r.lines).to.equal('\u001B[90m\u001B[39m\n\u001B[90mone\u001B[39m\r\n\u001B[90mtwo\u001B[39m'); + expect(r.urlLines).to.equal( + '\u001B[36m\u001B[4mu\u001B[24m\u001B[39m\n\u001B[36m\u001B[4mv\u001B[24m\u001B[39m', + ); + }); + + it('leaves an empty string empty', () => { + expect(runProbe({ FORCE_COLOR: '1' }).empty).to.equal(''); + }); + + it('prints plain text under FORCE_COLOR=0', () => { + const r = runProbe({ FORCE_COLOR: '0' }); + expect(r.url).to.equal('u'); + expect(r.forStderr).to.equal('x'); + }); + + it('keeps colour bound for stderr when stderr takes colour', () => { + expect(runProbe({ FORCE_COLOR: '1' }).forStderr).to.equal('\u001B[31mx\u001B[39m'); + }); + + it('prints a non-string value instead of throwing', () => { + expect(runProbe({}).dimNull).to.equal('null'); + }); +}); diff --git a/test/unit/telemetry-api-url.test.ts b/test/unit/telemetry-api-url.test.ts new file mode 100644 index 0000000..d3787de --- /dev/null +++ b/test/unit/telemetry-api-url.test.ts @@ -0,0 +1,76 @@ +import { expect } from 'chai'; + +import { telemetry, telemetryDisabled } from '../../src/services/telemetry.service.js'; + +/** + * Events go to the API the command itself talks to. A login's stored API used + * to win over `--api-url`, so a logged-in run aimed at a local or dev API sent + * its events to the login's API (prod) instead. + */ +describe('telemetry API URL', () => { + const realFetch = globalThis.fetch; + const realArgv = process.argv; + let urls: string[]; + + beforeEach(function () { + // The singleton reads this once, at import. + if (telemetryDisabled()) this.skip(); + + urls = []; + globalThis.fetch = (async (input: unknown) => { + urls.push(String(input)); + return new Response('{}', { status: 202 }); + }) as typeof fetch; + }); + + afterEach(() => { + globalThis.fetch = realFetch; + process.argv = realArgv; + }); + + async function sendWith(argv: string[], storedApiUrl?: string): Promise { + process.argv = ['node', 'dcd', ...argv]; + telemetry.configure({ + apiUrl: storedApiUrl, + auth: { headers: { authorization: 'Bearer t' }, mode: 'bearer' } as never, + }); + telemetry.recordSubmitAttempts(1); + telemetry.recordCommandSuccess(); + await telemetry.flush(); + return urls.pop()!; + } + + it('follows --api-url over the login’s stored API', async () => { + const url = await sendWith( + ['artifacts', '--api-url', 'http://localhost:4321'], + 'https://api.devicecloud.dev', + ); + expect(url).to.equal('http://localhost:4321/cli/logs'); + }); + + it('accepts the --api-url= form', async () => { + const url = await sendWith( + ['artifacts', '--api-url=https://dev-api.devicecloud.dev'], + 'https://api.devicecloud.dev', + ); + expect(url).to.equal('https://dev-api.devicecloud.dev/cli/logs'); + }); + + it('uses the stored API when there is no flag', async () => { + const url = await sendWith(['artifacts'], 'https://dev-api.devicecloud.dev'); + expect(url).to.equal('https://dev-api.devicecloud.dev/cli/logs'); + }); + + it('ignores a flag URL the command would refuse', async () => { + const url = await sendWith( + ['artifacts', '--api-url', 'http://not-local.example'], + 'https://dev-api.devicecloud.dev', + ); + expect(url).to.equal('https://dev-api.devicecloud.dev/cli/logs'); + }); + + it('falls back to the default API with neither', async () => { + const url = await sendWith(['artifacts']); + expect(url).to.equal('https://api.devicecloud.dev/cli/logs'); + }); +}); diff --git a/test/unit/telemetry-disabled.test.ts b/test/unit/telemetry-disabled.test.ts new file mode 100644 index 0000000..5e780a8 --- /dev/null +++ b/test/unit/telemetry-disabled.test.ts @@ -0,0 +1,29 @@ +import { expect } from 'chai'; + +import { telemetryDisabled } from '../../src/services/telemetry.service.js'; + +/** The two env vars that turn telemetry off, and the values that don't. */ +describe('telemetryDisabled', () => { + it('is off (telemetry on) with neither var set', () => { + expect(telemetryDisabled({})).to.equal(false); + }); + + for (const name of ['DCD_TELEMETRY_DISABLED', 'DO_NOT_TRACK']) { + for (const value of ['1', 'true', 'TRUE', 'yes', ' 1 ']) { + it(`turns telemetry off for ${name}=${JSON.stringify(value)}`, () => { + expect(telemetryDisabled({ [name]: value })).to.equal(true); + }); + } + + for (const value of ['', '0', 'false', 'False', ' 0 ']) { + it(`leaves telemetry on for ${name}=${JSON.stringify(value)}`, () => { + expect(telemetryDisabled({ [name]: value })).to.equal(false); + }); + } + } + + it('turns telemetry off when either var says so', () => { + expect(telemetryDisabled({ DCD_TELEMETRY_DISABLED: '0', DO_NOT_TRACK: '1' })).to.equal(true); + expect(telemetryDisabled({ DCD_TELEMETRY_DISABLED: '1', DO_NOT_TRACK: '0' })).to.equal(true); + }); +}); diff --git a/test/unit/telemetry-encryption.test.ts b/test/unit/telemetry-encryption.test.ts index 430cd73..4340673 100644 --- a/test/unit/telemetry-encryption.test.ts +++ b/test/unit/telemetry-encryption.test.ts @@ -4,6 +4,7 @@ import { jsonResult, runTool } from '../../src/mcp/helpers.js'; import { type EncryptionTelemetry, telemetry, + telemetryDisabled, } from '../../src/services/telemetry.service.js'; /** @@ -22,7 +23,7 @@ describe('encryption telemetry (#1138)', () => { beforeEach(function () { // The singleton reads this once, at import. - if (process.env.DCD_TELEMETRY_DISABLED) this.skip(); + if (telemetryDisabled()) this.skip(); events = []; globalThis.fetch = (async (_input: unknown, init?: RequestInit) => { @@ -43,7 +44,7 @@ describe('encryption telemetry (#1138)', () => { events.filter((e) => e.message === message).pop(); it('puts what the command encrypted on `command completed`, merged as it happens', async () => { - telemetry.recordEncryption({ binary: false, env: false, flow: false, source: 'server' }); + telemetry.recordEncryption({ binary: false, env: false, flow: false, source: 'always' }); telemetry.recordEncryption({ binary: true }); telemetry.recordEncryption({ env: true, flow: true }); telemetry.recordCommandSuccess(); @@ -53,12 +54,12 @@ describe('encryption telemetry (#1138)', () => { binary: true, env: true, flow: true, - source: 'server', + source: 'always', }); }); it('puts it on `command failed` too', async () => { - telemetry.recordEncryption({ binary: false, env: false, flow: false, source: 'flag' }); + telemetry.recordEncryption({ binary: false, env: false, flow: false, source: 'no_kek' }); telemetry.recordCommandFailure({ error: new Error('boom'), exitCode: 1 }); await telemetry.flush(); @@ -66,7 +67,7 @@ describe('encryption telemetry (#1138)', () => { binary: false, env: false, flow: false, - source: 'flag', + source: 'no_kek', }); }); @@ -75,7 +76,7 @@ describe('encryption telemetry (#1138)', () => { binary: true, env: false, flow: true, - source: 'env', + source: 'always', }; it('sends the fields a tool adds on its `mcp tool completed` event', async () => { diff --git a/test/unit/telemetry-submit-attempts.test.ts b/test/unit/telemetry-submit-attempts.test.ts index 414aca1..9f5fe19 100644 --- a/test/unit/telemetry-submit-attempts.test.ts +++ b/test/unit/telemetry-submit-attempts.test.ts @@ -1,6 +1,6 @@ import { expect } from 'chai'; -import { telemetry } from '../../src/services/telemetry.service.js'; +import { telemetry, telemetryDisabled } from '../../src/services/telemetry.service.js'; /** * How many attempts the flow submit took (dcd#1617 follow-up) rides on the @@ -19,7 +19,7 @@ describe('submit attempts telemetry', () => { beforeEach(function () { // The singleton reads this once, at import. - if (process.env.DCD_TELEMETRY_DISABLED) this.skip(); + if (telemetryDisabled()) this.skip(); events = []; globalThis.fetch = (async (_input: unknown, init?: RequestInit) => { diff --git a/test/unit/upload-encrypt.test.ts b/test/unit/upload-encrypt.test.ts index 4443d8a..21ceb81 100644 --- a/test/unit/upload-encrypt.test.ts +++ b/test/unit/upload-encrypt.test.ts @@ -10,9 +10,9 @@ import { resetCliConfigCache } from '../../src/config/cli-config.js'; import { clearCompatibilityCache } from '../../src/utils/compatibility.js'; /** - * `dcd upload` decides encryption in the same order as `dcd cloud`: the flag - * (--encrypt / --no-encrypt), then DCD_ENCRYPT, then the server default from - * the compatibility data (dcd#1138), then off. + * `dcd upload` always encrypts, like `dcd cloud` (dcd#1138). --no-encrypt and + * DCD_ENCRYPT=0 are ignored with a warning. The only way to get a plaintext + * upload is an API that publishes no KEK. * * Observed through the dedup lookup, which is the first upload request either * way: an encrypted upload deduplicates on the plaintext hash and says so @@ -22,8 +22,6 @@ const API = 'http://localhost:9999'; /** An API that publishes no KEK on /cli-config (see the fetch stub). */ const UNKNOWN_API = 'https://api.example.com'; const APK = path.join(process.cwd(), 'test/fixtures/wikipedia.apk'); -/** Printed when the server default, not a flag or env var, turned encryption on. */ -const DEFAULT_ON_NOTICE = 'Encrypting uploads; opt out with --no-encrypt'; describe('dcd upload encryption', () => { const ORIGINAL_ENV = { ...process.env }; @@ -31,9 +29,6 @@ describe('dcd upload encryption', () => { const realExit = process.exit; const realFlushSync = telemetry.flushSync; let lookups: Array>; - /** The `encryption` field the mocked compatibility endpoint returns, if any. */ - let compatEncryption: { defaultOn: boolean } | undefined; - let compatFails: boolean; let tempDir: string; beforeEach(() => { @@ -44,16 +39,15 @@ describe('dcd upload encryption', () => { delete process.env.DCD_ENCRYPT_BINARIES; clearCompatibilityCache(); resetCliConfigCache(); - compatEncryption = undefined; - compatFails = false; // A throwaway KEK so encryption can run against an API that publishes none. const { publicKey } = generateKeyPairSync('x25519'); const raw = publicKey.export({ format: 'der', type: 'spki' }).subarray(12); process.env.DCD_BINARY_KEK_PUBLIC = `1:${raw.toString('base64')}`; - // Serve the compatibility data, and answer the dedup lookup with a hit of - // the matching kind, so the command finishes without uploading anything. + // Answer the dedup lookup with a hit of the matching kind, so the command + // finishes without uploading anything. `dcd upload` no longer reads the + // compatibility data, so any request for it fails the test. lookups = []; globalThis.fetch = (async (input: unknown, init?: RequestInit) => { const json = (body: unknown, status = 200) => @@ -69,17 +63,7 @@ describe('dcd upload encryption', () => { } if (String(input).includes('/results/compatibility/data')) { - if (compatFails) return json({ message: 'boom' }, 500); - return json({ - data: { - android: {}, - androidPlay: {}, - ios: {}, - maestro: { defaultVersion: '2.0.0', latestVersion: '2.0.0', supportedVersions: ['2.0.0'] }, - ...(compatEncryption ? { encryption: compatEncryption } : {}), - }, - statusCode: 200, - }); + throw new Error('dcd upload should not fetch the compatibility data'); } const body = JSON.parse(String(init?.body)) as Record; @@ -134,65 +118,33 @@ describe('dcd upload encryption', () => { return (JSON.parse(out) as { appBinaryId: string }).appBinaryId; } - it('encrypts when DCD_ENCRYPT=1 is exported and --encrypt is not passed', async () => { - process.env.DCD_ENCRYPT = '1'; - + it('encrypts with nothing set', async () => { expect(await upload()).to.equal('encrypted-binary'); expect(lookups[0]).to.include({ encrypted: true }); expect(lookups[0]).to.have.property('shaPlain'); }); - it('still encrypts with --encrypt alone', async () => { + it('encrypts with --encrypt, which is now a no-op', async () => { expect(await upload({ encrypt: true })).to.equal('encrypted-binary'); }); - it('uploads in plaintext when neither is set and the API sends no default', async () => { - expect(await upload()).to.equal('plain-binary'); - expect(lookups[0]).to.have.property('sha'); - expect(lookups[0]).to.not.have.property('encrypted'); - }); - - it('uploads in plaintext when the server default is off', async () => { - compatEncryption = { defaultOn: false }; - expect(await upload()).to.equal('plain-binary'); - }); - - it('encrypts when the server default is on', async () => { - compatEncryption = { defaultOn: true }; - expect(await upload()).to.equal('encrypted-binary'); - }); - - it('lets --no-encrypt beat the server default', async () => { - compatEncryption = { defaultOn: true }; - expect(await upload({ encrypt: false })).to.equal('plain-binary'); + it('ignores --no-encrypt, with a warning, and still encrypts', async () => { + expect(await upload({ encrypt: false })).to.equal('encrypted-binary'); + expect(await run({ encrypt: false })).to.contain( + 'Ignoring --no-encrypt: uploads are always encrypted.', + ); }); - it('lets --no-encrypt beat DCD_ENCRYPT=1', async () => { - process.env.DCD_ENCRYPT = '1'; - expect(await upload({ encrypt: false })).to.equal('plain-binary'); - }); - - it('lets DCD_ENCRYPT=0 beat the server default', async () => { - process.env.DCD_ENCRYPT = '0'; - compatEncryption = { defaultOn: true }; - expect(await upload()).to.equal('plain-binary'); - }); - - it('treats a failed compatibility fetch as the default being off', async () => { - compatFails = true; - expect(await upload()).to.equal('plain-binary'); - }); - - it('says it is encrypting, and how to opt out, when the server default encrypts', async () => { - compatEncryption = { defaultOn: true }; - expect(await run({})).to.contain(DEFAULT_ON_NOTICE); - }); + for (const name of ['DCD_ENCRYPT', 'DCD_ENCRYPT_BINARIES']) { + it(`ignores ${name}=0, with a warning, and still encrypts`, async () => { + process.env[name] = '0'; + expect(await upload()).to.equal('encrypted-binary'); + expect(await run({})).to.contain(`Ignoring ${name}: uploads are always encrypted.`); + }); + } - it('prints no notice when the flag or env var turned encryption on', async () => { - compatEncryption = { defaultOn: true }; - expect(await run({ encrypt: true })).to.not.contain(DEFAULT_ON_NOTICE); - process.env.DCD_ENCRYPT = '1'; - expect(await run({})).to.not.contain(DEFAULT_ON_NOTICE); + it('prints no notice in the normal case', async () => { + expect(await run({})).to.not.contain('Ignoring'); }); describe('against an API that publishes no KEK', () => { @@ -200,46 +152,23 @@ describe('dcd upload encryption', () => { delete process.env.DCD_BINARY_KEK_PUBLIC; }); - it('skips the server default, with a notice, and uploads in plaintext', async () => { - compatEncryption = { defaultOn: true }; + it('uploads in plaintext, with a notice', async () => { expect(await upload({ 'api-url': UNKNOWN_API })).to.equal('plain-binary'); + expect(lookups[0]).to.have.property('sha'); + expect(lookups[0]).to.not.have.property('encrypted'); const out = await run({ 'api-url': UNKNOWN_API }); expect(out).to.contain(`Not encrypting uploads: ${UNKNOWN_API}`); - expect(out).to.not.contain(DEFAULT_ON_NOTICE); }); - it('skips DCD_ENCRYPT=1 the same way', async () => { - process.env.DCD_ENCRYPT = '1'; - expect(await upload({ 'api-url': UNKNOWN_API })).to.equal('plain-binary'); - }); - - it('refuses --encrypt before uploading anything', async () => { - let stderr = ''; - const original = process.stderr.write.bind(process.stderr); - process.stderr.write = ((chunk: string) => { - stderr += chunk; - return true; - }) as typeof process.stderr.write; - try { - await run({ 'api-url': UNKNOWN_API, encrypt: true }); - expect.fail('dcd upload --encrypt should have failed'); - } catch (error) { - expect((error as Error).message).to.equal('process.exit(1)'); - } finally { - process.stderr.write = original; - } - - expect(stderr).to.contain('--encrypt needs the KEK public key'); - expect(lookups).to.have.lengthOf(0); + it('treats --encrypt the same way, since it is a no-op', async () => { + expect(await upload({ 'api-url': UNKNOWN_API, encrypt: true })).to.equal('plain-binary'); }); - it('encrypts with --encrypt once DCD_BINARY_KEK_PUBLIC names a key', async () => { + it('encrypts once DCD_BINARY_KEK_PUBLIC names a key', async () => { const { publicKey } = generateKeyPairSync('x25519'); const raw = publicKey.export({ format: 'der', type: 'spki' }).subarray(12); process.env.DCD_BINARY_KEK_PUBLIC = `1:${raw.toString('base64')}`; - expect(await upload({ 'api-url': UNKNOWN_API, encrypt: true })).to.equal( - 'encrypted-binary', - ); + expect(await upload({ 'api-url': UNKNOWN_API })).to.equal('encrypted-binary'); }); }); });