From dc9022ac9f866ae6676b26da54df185c9ab39a04 Mon Sep 17 00:00:00 2001 From: chenliuyun Date: Thu, 5 Nov 2026 20:36:22 +0800 Subject: [PATCH 1/3] feat: align SwitchBot API and harden account switching --- CHANGELOG.md | 31 ++ README.md | 62 +++- docs/account-switch-safety-mvp.md | 105 +++++++ docs/agent-guide.md | 97 ++++++- docs/openapi-alignment-ambiguities.md | 26 ++ docs/policy-reference.md | 54 +++- docs/schema-versioning.md | 14 + src/api/client.ts | 35 ++- src/commands/auth.ts | 21 +- src/commands/cache.ts | 7 +- src/commands/devices.ts | 2 +- src/commands/expand.ts | 2 +- src/commands/mcp.ts | 125 +++++--- src/config.ts | 11 +- src/credentials/prime.ts | 98 ++++--- src/credentials/scope.ts | 63 +++++ src/devices/cache.ts | 172 +++++------ src/devices/catalog.ts | 104 +++++-- src/devices/param-validator.ts | 128 ++++++++- src/devices/resources.ts | 72 ++++- src/index.ts | 14 +- src/lib/command-preflight.ts | 1 + src/lib/devices.ts | 42 ++- src/lib/idempotency.ts | 36 ++- src/policy/schema/v0.2.json | 2 +- src/policy/validate.ts | 64 +++-- src/rules/action.ts | 124 ++++---- src/rules/destructive.ts | 11 +- src/rules/engine.ts | 8 +- tests/api/art-upload-limit-alignment.test.ts | 131 +++++++++ tests/api/client.test.ts | 88 ++---- tests/commands/auth.test.ts | 208 ++++++-------- tests/commands/config.test.ts | 79 +----- tests/commands/devices.test.ts | 23 +- tests/commands/mcp-camera-alignment.test.ts | 124 ++++++++ tests/commands/mcp-profile-http.test.ts | 109 ++++++- tests/commands/mcp-safety-lifecycle.test.ts | 221 +++++++++++++++ tests/commands/mcp.test.ts | 128 +++++++++ tests/commands/schema.test.ts | 2 +- tests/config.test.ts | 14 +- tests/credentials/prime.test.ts | 117 ++++++++ tests/devices/account-cache-lifecycle.test.ts | 267 ++++++++++++++++++ .../art-frame-object-alignment.test.ts | 139 +++++++++ tests/devices/cache-scoping.test.ts | 18 ++ tests/devices/camera-alignment.test.ts | 72 +++++ tests/devices/curtain-lock-alignment.test.ts | 80 ++++++ tests/devices/k11-pro-alignment.test.ts | 126 +++++++++ tests/devices/light-bars-boundary.test.ts | 66 +++++ tests/devices/webhook-alignment.test.ts | 104 +++++++ tests/lib/devices.test.ts | 3 + tests/lib/idempotency.test.ts | 18 ++ tests/policy/camera-safety-alignment.test.ts | 32 +++ tests/policy/validate.test.ts | 162 +++++++++++ tests/rules/action.test.ts | 262 +++++++++++++++-- tests/rules/engine.test.ts | 53 ++++ 55 files changed, 3539 insertions(+), 638 deletions(-) create mode 100644 docs/account-switch-safety-mvp.md create mode 100644 src/credentials/scope.ts create mode 100644 tests/api/art-upload-limit-alignment.test.ts create mode 100644 tests/commands/mcp-camera-alignment.test.ts create mode 100644 tests/commands/mcp-safety-lifecycle.test.ts create mode 100644 tests/devices/account-cache-lifecycle.test.ts create mode 100644 tests/devices/art-frame-object-alignment.test.ts create mode 100644 tests/devices/camera-alignment.test.ts create mode 100644 tests/devices/curtain-lock-alignment.test.ts create mode 100644 tests/devices/k11-pro-alignment.test.ts create mode 100644 tests/devices/light-bars-boundary.test.ts create mode 100644 tests/devices/webhook-alignment.test.ts create mode 100644 tests/policy/camera-safety-alignment.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index f9cd4cc3..405a0b1d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,37 @@ All notable changes to `@switchbot/openapi-cli` are documented in this file. The format is loosely based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). This project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added + +- Catalog coverage for RGBICWW Light Bars, Smart Lock Ultra Max, Curtain 4, Robot Vacuum Cleaner K11 Plus Pro, AI Art Frame Luma, Outdoor Pan/Tilt Cam 3K, and Solar Pan/Tilt Cam 2K. +- Light Bars object commands, including `setLightEffect` with `effectId` 0–25; six existing documented lights also expose their light effects. +- Camera `latestImage` metadata with its expiry contract, Solar motion-detection controls, and Art Frame Luma upload/status support. + +### Changed + +- MCP output schemas now declare the existing structured `isError` / `structuredContent.error` result alongside successful object results; successful and error payload shapes are unchanged. +- Direct destructive commands remain blocked by default even with `--yes` or `confirm: true`; an explicit dev/override permission and confirmation, or an approved plan, is required. Physical devices cannot use IR `customize` dispatch. +- Solar motion-detection disable is destructive and prohibited from automation/policy preapproval. +- Successful credential mutations invalidate device, status, credential, and idempotency caches across running processes; implicit and explicit default profiles now share the legacy cache paths. +- Account changes reject obsolete in-flight reads and retained-client retries instead of crossing account boundaries. Existing MQTT subscriptions must be restarted. + +### Fixed + +- MCP now applies destructive-command safety to cold-cache devices identified only by `controlType`. +- HTTP MCP returns a protocol error instead of terminating if credentials change during request priming; unavailable replacement keychains cannot fall back to older file credentials. +- Rule JSON parameters avoid a redundant parse while preserving request and audit formats. + +### Compatibility + +- Rule RGB parameters retain both `setColor 255 0 0` and `setColor 255:0:0`; JSON objects preserve whitespace and can use YAML literal blocks. +- Rule dry-runs now require the target in the active profile's cache; missing inventory fails without a network request instead of reporting success. + +### Notes + +- Light Bars webhook field shapes are documented, but the exact `context.deviceType` identifier remains unconfirmed and is deliberately not mapped. + ## [3.9.0] ### Added diff --git a/README.md b/README.md index f7ffe4e8..7570c75f 100644 --- a/README.md +++ b/README.md @@ -51,19 +51,28 @@ Run `switchbot catalog show` for the effective catalog, including aliases and pe | Category | Devices | | --- | --- | -| **Lighting** | Color Bulb · Strip Light · Strip Light 3 · RGBICWW Strip Light · Floor Lamp · RGBICWW Floor Lamp · Ceiling Light · Ceiling Light Pro · RGBICWW Ceiling Light · RGBIC Neon Rope Light · RGBIC Neon Wire Rope Light · Candle Warmer Lamp · Permanent Outdoor Lights | +| **Lighting** | Color Bulb · Strip Light · Strip Light 3 · RGBICWW Strip Light · RGBICWW Light Bars _(unreleased)_ · Floor Lamp · RGBICWW Floor Lamp · Ceiling Light · Ceiling Light Pro · RGBICWW Ceiling Light · RGBIC Neon Rope Light · RGBIC Neon Wire Rope Light · Candle Warmer Lamp · Permanent Outdoor Lights | | **Climate** | Humidifier · Humidifier2 · Air Purifier VOC · Air Purifier Table VOC · Air Purifier PM2.5 · Air Purifier Table PM2.5 · Smart Radiator Thermostat | -| **Security** | Smart Lock · Smart Lock Pro · Smart Lock Pro Wifi · Smart Lock Ultra · Lock Lite · Lock Vision · Lock Vision Pro · Keypad · Keypad Touch · Keypad Vision · Keypad Vision Pro · Garage Door Opener · Video Doorbell | -| **Curtains & blinds** | Curtain · Curtain3 · Blind Tilt · Roller Shade | +| **Security** | Smart Lock · Smart Lock Pro · Smart Lock Pro Wifi · Smart Lock Ultra · Smart Lock Ultra Max _(unreleased)_ · Lock Lite · Lock Vision · Lock Vision Pro · Keypad · Keypad Touch · Keypad Vision · Keypad Vision Pro · Garage Door Opener · Video Doorbell | +| **Curtains & blinds** | Curtain · Curtain3 · Curtain 4 _(unreleased)_ · Blind Tilt · Roller Shade | | **Power** | Plug · Plug Mini (US) · Plug Mini (JP) · Plug Mini (EU) · Relay Switch 1 · Relay Switch 1PM · Relay Switch 2PM | | **Fans** | Battery Circulator Fan · Battery Circulator Fan 2 Pro · Circulator Fan · Standing Circulator Fan | -| **Cleaning** | Robot Vacuum Cleaner S1 · Robot Vacuum Cleaner S1 Plus · K10+ · K10+ Pro · Robot Vacuum Cleaner K10+ Pro Combo · Robot Vacuum Cleaner S10 · Robot Vacuum Cleaner S20 · Robot Vacuum Cleaner K11+ · Robot Vacuum Cleaner K20 Plus Pro | +| **Cleaning** | Robot Vacuum Cleaner S1 · Robot Vacuum Cleaner S1 Plus · K10+ · K10+ Pro · Robot Vacuum Cleaner K10+ Pro Combo · Robot Vacuum Cleaner S10 · Robot Vacuum Cleaner S20 · Robot Vacuum Cleaner K11+ · Robot Vacuum Cleaner K11 Plus Pro _(unreleased)_ · Robot Vacuum Cleaner K20 Plus Pro | | **Sensors** _(read-only)_ | Meter · MeterPlus · WoIOSensor · MeterPro · MeterPro(CO2) · WeatherStation · Motion Sensor · Presence Sensor · Contact Sensor · Water Detector · Wallet Finder Card | | **Hubs** _(read-only)_ | Hub · Hub Plus · Hub Mini · Hub 2 · Hub 3 · AI Hub | -| **Cameras** _(status only)_ | Indoor Cam · Pan/Tilt Cam · Pan/Tilt Cam 2K · Pan/Tilt Cam Plus 2K · Pan/Tilt Cam Plus 3K · Outdoor Spotlight Cam | -| **Other** | Bot · AI Art Frame · AI MindClip · Kata Friends · Home Climate Panel · Remote | +| **Cameras** | Indoor Cam · Pan/Tilt Cam · Pan/Tilt Cam 2K · Pan/Tilt Cam Plus 2K · Pan/Tilt Cam Plus 3K · Outdoor Spotlight Cam · Outdoor Pan/Tilt Cam 3K _(unreleased; status only)_ · Solar Pan/Tilt Cam 2K _(unreleased)_ | +| **Other** | Bot · AI Art Frame · AI Art Frame Luma _(unreleased)_ · AI MindClip · Kata Friends · Home Climate Panel · Remote | | **IR virtual remotes** _(via Hub)_ | Air Conditioner · TV · Streamer · Set Top Box · DVD · Speaker · Fan · Light · Others | +### Device contract notes + +**Unreleased:** The notes below describe upcoming capabilities not included in CLI 3.9.0. + +- Light Bars accept object parameters. For example: `switchbot devices command setLightEffect '{"effectId":1}'`; `effectId` is an integer from 0 through 25. +- Outdoor Pan/Tilt Cam 3K is status-only. Camera status may include `latestImage` as `{ imageUrl, expireAt }`; `expireAt` is Unix seconds. Treat cached URLs as potentially expired, do not download or persist image bytes, and query again with `--no-cache` when a fresh status is needed. +- Solar Pan/Tilt Cam 2K supports motion-detection enable/disable only. Disabling detection is destructive and follows the reviewed approval path; it is not a substitute for camera streaming or PTZ control. +- Light Bars webhook field shapes are documented, but their exact `context.deviceType` identifier is not discoverable from the official material. The CLI does not guess a mapping. + --- ## Quick start @@ -222,9 +231,12 @@ path and is not the bundle route. See [host verification boundaries](./docs/host ## Credentials -> **Recommended:** use `switchbot auth login` for browser-based OAuth — credentials are stored securely in the OS keychain and never need to be copy-pasted anywhere. +> **Recommended:** use `switchbot auth login` for browser-based OAuth. Credentials are stored in the OS keychain when available, otherwise in the local config file. -Priority: env vars → OS keychain → `~/.switchbot/config.json` +Priority: complete env vars → OS keychain → `~/.switchbot/config.json`. +`--config ` bypasses the keychain but not complete environment credentials. +`config set-token` writes the file; an existing keychain entry still takes +precedence unless `--config` is used. ```bash switchbot auth login # browser OAuth — opens login page, saves to OS keychain @@ -233,6 +245,34 @@ export SWITCHBOT_TOKEN=... SWITCHBOT_SECRET=... # CI / env override switchbot auth keychain set/get/delete # OS keychain management ``` +### Switching accounts and caches + +Successful `auth login`, `auth keychain set/delete/migrate`, and +`config set-token` invalidate the affected credential scope's device list, +status, primed credentials, and idempotency results. Other running CLI/MCP +processes observe the change at their next cache or request boundary. A request +already in flight is not automatically retried under the new account; if it +was already sent, check its outcome before retrying. + +Implicit default and `--profile default` share `~/.switchbot/devices.json` +and `status.json`. Named profiles have separate cache directories. +`--config` stores caches beside the selected file; config files in the same +directory share that cache scope, so use separate directories for separate +accounts. Internal cache files contain a non-secret credential revision; CLI, +MCP, and audit output formats are unchanged. + +Direct edits to credential files, environment variables, or an external +keychain tool do not publish this invalidation. Stop affected long-running +processes, run `switchbot [--profile | --config ] cache clear`, +then restart them with the intended credentials. Restart an MQTT subscription +or rules daemon after changing accounts; its existing event stream is not +rebound automatically. Audit, policy, and event-history files are not cleared. +[Details and safety boundaries](./docs/agent-guide.md#profiles-and-credential-refresh). + +If a newly selected native keychain is locked or unavailable, requests fail +closed rather than using older file credentials. Offline commands and +credential-repair commands remain available. + For HTTP `401`, check the active token/secret, signature and system clock; use `auth login` or replace the credential source locally, never paste secrets into chat. For `429`, honor `Retry-After` and reduce request frequency. @@ -354,6 +394,10 @@ switchbot rules suggest --intent "turn off AC at 11pm" [--llm auto] switchbot daemon start/stop/reload/status ``` +Existing rules may use either `setColor 255 0 0` or `setColor 255:0:0`; +both send `255:0:0`. The same applies to `setColorLightRGB`. JSON object +parameters and audit records retain their existing formats. + ### `plan` Declarative batch operations. A plan file has `version`, `description`, and a `steps` array. @@ -446,7 +490,7 @@ Policy commands retain their documented specialized exit codes (including YAML p ## Development -Verified CLI regression suite: 3093 tests. Plugin workspace checks are separate. +Verified CLI regression suite: 3163 tests. Plugin workspace checks are separate. ```bash npm install && npm run build diff --git a/docs/account-switch-safety-mvp.md b/docs/account-switch-safety-mvp.md new file mode 100644 index 00000000..61e73cac --- /dev/null +++ b/docs/account-switch-safety-mvp.md @@ -0,0 +1,105 @@ +# Account switching and command safety MVP + +## Scope + +Follow-up to the API-alignment review on `feat/switchbot-api-alignment`. +Keep the existing CLI commands, JSON envelopes, MCP payloads, policy grammar, +and credential precedence. No release, hardware operation, or upstream API +expansion is part of this work. + +## Findings + +| Finding | Priority | Observable problem | MVP | +| --- | --- | --- | --- | +| MCP cold-cache type fallback | P1 | A device identified only by `controlType` can pass command validation but skip destructive-command authorization. | 1 | +| Cross-process account cache invalidation | P1 | Saving new credentials removes disk caches but a running process can retain the old account's inventory, status, credentials, or idempotent result. | 1 | +| Two default cache scopes | P2 | Implicit default and `--profile default` share credentials but currently use different device/status caches. | 1 | +| MCP output contract regression coverage | P3 | The current implementation rejects malformed outputs, but permanent protocol tests do not protect all exclusive success/error constraints. | 2 | +| Repeated rule JSON parsing | P3 | A valid JSON rule parameter is parsed before validation, by its validator, and again for dispatch. | 2 | +| Cache publication and replacement races | P1 | Torn disk writes, late responses, or retained clients can mix account data unless revision and request boundaries fail closed. | 1 | +| Keychain recovery and HTTP request errors | P1 | A locked replacement keychain must not expose stale file credentials or prevent offline credential repair; concurrent priming must not terminate MCP. | 1 | + +Solar's inventory-dependent automation restriction is intentional: do not +extend it to Video Doorbell by adding a global verb prohibition. Both +`setColor 255 0 0` and `setColor 255:0:0`, and the corresponding +`setColorLightRGB` forms, remain supported. JSON string contents and audit +parameter shapes must remain unchanged. + +## MVP 1: safety and account lifecycle + +- Use the same resolved device type for MCP validation, normalization, risk, + direct-execution permission, and confirmation. Cover `deviceType` and + `controlType`, cold and warm caches, Solar and Lock Ultra Max, and a real IR + custom command. Default-profile destructive calls must make zero POSTs. +- Publish account-cache invalidation only through the existing credential + mutation commands. Use a non-secret scope revision, not stored credentials, + a background polling service, or a new CLI flag. Running processes check the + revision at their next cache/credential use; an unchanged revision retains + the existing hot-cache and credential TTL behavior. +- Invalidate device/status and credential snapshots, and prevent reuse of an + old account's idempotent result. An old in-flight response must not repopulate + a new account's cache. Do not retry a mutation automatically during an + account change. +- Atomically replace cache documents with a private, additive + `_credentialRevision` field so a stale writer cannot attach old data to a + new account. Existing public cache-return fields and CLI/MCP output remain + unchanged; missing metadata is accepted only before a revision exists. +- Preserve keychain-first resolution. When a native keychain replacement was + published, fail closed if that store cannot supply the replacement; never + fall back to an older file. Publish keychain mutations to the profile they + actually modify even when an unrelated `--config` is present. + Keep offline commands and credential repair available if the store is + locked, while synchronous and asynchronous credential consumers fail closed. +- Unify implicit and explicit default cache storage on the existing + `~/.switchbot/devices.json` and `status.json` paths. Keep named profiles + isolated and retain explicit `--config` precedence. Ignore obsolete + explicit-default cache data rather than restoring it into the active scope. +- Do not delete policy, audit, or event-history data. Environment credentials + remain highest priority. Direct environment/file edits are not login events; + document their manual invalidation/restart requirements. + +## MVP 2: contracts and rule execution + +- Exercise real SDK `listTools` followed by `callTool`, with output validation + enabled. Protect rejection of missing required success fields, mixed + success/error objects, and incorrectly typed error fields. Preserve valid + success and structured-error responses; do not relax schemas. +- Remove the redundant pre-validation wire conversion in rules. Retain + consumer-visible request parameters and successful/failed audit records, + including RGB compatibility and JSON objects with spaces or newlines. +- Keep implementation-count/performance probes temporary. Permanent tests + assert behavior and invariants, not the number of `JSON.parse` calls. + +## MVP 3: documentation and verification + +- Update README, changelog, agent guidance, and relevant policy/schema notes + with account switching, scope boundaries, safety behavior, and compatibility. +- Use vertical TDD: one failing consumer regression, the minimal fix, then its + passing check. Characterization tests for already-correct MCP rejection paths + need no artificial production failure. Review independent lifecycle slices + in parallel and run checks centrally. +- Run the full CLI regression suite and Markdown lint after integration; + update documented test counts from that run, not a prediction. +- Smoke the actual CLI and MCP SDK with isolated HOME/configuration and local + HTTP adapters. Demonstrate external credential replacement while another + process is warm, default/profile isolation, no destructive POST on refusal, + and unchanged rule wire/audit data. Do not claim cloud or hardware validation. + +## Delivery evidence + +- Full CLI suite: **180 files, 3163 tests passed**; its setup ran the release + build and TypeScript typecheck. Plugin workspace tests were not rerun. +- `npm run lint:md` passed. +- Isolated real CLI + MCP SDK smoke: a separate `config set-token` process + changed a warm reader from account A's inventory, status, and keyed command + result to B's; a cold `controlType`-only lock was refused with zero POSTs. + Implicit and explicit default shared inventory. +- Rule smoke sent both RGB forms as `255:0:0`; a spaced JSON object and all + three corresponding audit parameters were unchanged. A 64 KiB JSON payload + was parsed twice instead of three times; this count probe was temporary. +- Dedicated regressions cover late cache responses and disk writes, keychain + failure and repair, retained-client/429 races, HTTP MCP recovery including an + unavailable startup profile, profile scoping, and invalid SDK output. All + network boundaries were local adapters. +- No real OAuth, cloud API, MQTT broker, camera/image URL, or physical device + was exercised. diff --git a/docs/agent-guide.md b/docs/agent-guide.md index b4b2a807..287a7140 100644 --- a/docs/agent-guide.md +++ b/docs/agent-guide.md @@ -107,6 +107,19 @@ The default profile exposes 18 tools; `--tools readonly` exposes 15. Policy, aud The MCP server refuses destructive commands (Smart Lock `unlock` or `deadbolt`, Garage Door `open`, etc.) unless the tool call includes `confirm: true`, and the default safety profile still blocks direct destructive execution in favor of the reviewed CLI flow (`plan save` → `plan review` → `plan approve` → `plan execute`). `deadbolt` releases the latch; it does not lock the door. Discover destructive classifications with `switchbot schema export | jq '[.data.types[].commands[] | select(.safetyTier=="destructive")]'`; classification is not permission to execute. +Device type resolution uses `deviceType` or, when absent, `controlType` for +both cold and warm inventory. A `controlType`-only lock or Solar camera must +pass the same safety and confirmation gates before any mutation is sent. + +MCP tool failures are structured results: `isError: true` with +`structuredContent.error`. Inspect that error rather than treating a returned +tool result as success. Published output schemas retain the existing success +object and also admit this error object; no tool or machine payload was added. + +Physical devices must use built-in `command` dispatch. `commandType: "customize"` +is only for a genuine user-defined button on an IR virtual remote; it cannot +reclassify or bypass safety checks for a lock, camera, or other physical device. + ### Deprecated aliases (scheduled for removal in 4.0.0) These names continue to work in 3.x but are thin wrappers over `device_history`. Migrate to the consolidated tool — it emits a single schema per session instead of three. @@ -167,9 +180,33 @@ HTTP profile selection uses `x-switchbot-profile` before `?profile=...`; names m Named HTTP profiles may store credentials only in the OS keychain; a profile JSON file is not required. Profile lookup happens after bearer authentication, and names without credentials or a configuration file are rejected. -MQTT subscriptions belong to the startup profile. A request for a different profile cannot read that subscription's `switchbot://events` ring or receive its MQTT account-overview fields. Start a separate subscription/server for a different account. - -MCP refreshes credentials at request/tool boundaries with a five-second cache and per-profile single-flight loading. Credential changes are picked up after that cache expires; asynchronous stale loads cannot overwrite a later invalidation. Environment credentials still take precedence over keychain and files. +MQTT subscriptions belong to the startup profile. A request for a different profile cannot read that subscription's `switchbot://events` ring or receive its MQTT account-overview fields. Restart the subscription/server after switching its account; existing streams and event history are not rebound or cleared. + +Successful CLI credential mutations publish a non-secret revision for the +affected profile or `--config` directory. Running processes invalidate device +inventory, status, credential snapshots, and idempotency results on their next +use; an obsolete in-flight inventory/status response is rejected. A retained +HTTP client from the old scope fails closed, including on a 429 retry. An +already dispatched mutation is not repeated automatically and may have taken +effect; check its outcome before retrying. + +Native-keychain replacements require the keychain to be available on the next +refresh; the client will not silently fall back to an older file credential. +Unchanged credentials still use the five-second keychain cache. Complete +environment credentials take precedence; `--config` bypasses the keychain. +`config set-token` updates the file, so an existing keychain entry still wins. +External environment/keychain/file edits do not publish a revision: stop +long-running processes, clear the affected scope's cache, and restart them. + +If the startup profile's replacement keychain is unavailable, optional MQTT +initialization is disabled instead of using an older file credential. HTTP MCP +can still serve other valid named profiles. Restore the keychain and restart +the server to establish the startup subscription. + +Implicit and explicit `default` use the same legacy cache paths. Named +profiles are isolated; `--config` places caches in the config file's +directory, so separate config files in one directory share a cache scope. +Account changes do not erase policy, audit, or event history. --- @@ -289,8 +326,9 @@ Lock Vision's less-specific object template is not assigned these restrictions. ### Idempotent command retries `send_command` / `devices command` accept an idempotency key. Within the same -running process and credential profile, reusing it for the same device, command -type and wire parameters replays the result instead of sending another request. +running process, credential storage scope, and account revision, reusing it for +the same device, command type and wire parameters replays the result instead of +sending another request. Changing any of those values returns an idempotency conflict; use a new key for a different operation. Omitted parameters and `"default"` represent the same wire request. The cache is process-local and expires after 60 seconds: separate @@ -353,14 +391,34 @@ Each command entry carries: - `parameter` / `exampleParams` — what the agent should fill in - `commandType` (`command` vs `customize`) — built-in vs user-defined IR button +### Model-specific boundaries + +**Unreleased:** The following model names and capabilities are not included in CLI 3.9.0. + +The catalog recognizes the model names RGBICWW Light Bars, Smart Lock Ultra +Max, Curtain 4, Robot Vacuum Cleaner K11 Plus Pro, AI Art Frame Luma, Outdoor +Pan/Tilt Cam 3K, and Solar Pan/Tilt Cam 2K. Use `search_catalog` and +`describe_device` to determine the model's command and parameter contract; +similarly named models can differ or share an alias. + +- Light Bars use object parameters; `setLightEffect` takes `{ "effectId": 0 }` + through `{ "effectId": 25 }`. +- K11+ Pro requires at least one valid `changeParam` property. Curtain 4 uses + the normal curtain position tuple. Art Frame Luma accepts the established + one-source upload object (`imageUrl` or `imageBase64`, never both). +- Outdoor Pan/Tilt Cam 3K is status-only. For both new cameras, `latestImage` + is an optional object whose `expireAt` is Unix seconds; do not download its + URL or assume a cached URL remains valid. Solar supports only motion-detection + enable/disable; disabling detection is destructive. + Use `switchbot doctor` to confirm the CLI is healthy before orchestrating anything non-trivial — it validates credentials, catalog size, cache state, clock drift, and quota file access. --- ## Safety rails -1. **Destructive-command guard**: Smart Lock `unlock`, Garage Door `open`, and anything else tagged `destructive: true` in the catalog **refuses to run** directly in the default profile. Use the reviewed plan workflow by default; only explicit dev profiles may pair direct execution with `--yes` / `confirm: true`. -2. **Dry-run**: Global `--dry-run` short-circuits mutating requests; GETs still execute. Unknown physical device types and unsupported commands fail closed. Explicit custom IR buttons remain available through `commandType: "customize"`. +1. **Destructive-command guard**: Smart Lock `unlock`/`deadbolt`, Solar motion-detection disable, Garage Door `open`, and anything else tagged `destructive: true` **refuse direct execution** in the default profile. `--yes` or `confirm: true` confirms intent; neither grants direct-execution permission. Use the reviewed plan workflow, or an explicit dev/override permission plus confirmation. +2. **Dry-run and dispatch type**: Global `--dry-run` short-circuits mutating requests; GETs still execute. Unknown physical device types and unsupported commands fail closed. A physical device cannot use `customize`; explicit custom IR buttons remain available only for IR virtual remotes. 3. **Quota**: The API applies account limits and throttling. `--retry-on-429 ` and `--backoff ` handle throttling; `~/.switchbot/quota.json` is a local counter, not the authoritative server quota. 4. **Audit log**: `--audit-log` enables JSONL mutation records; `--audit-log-path ` selects a custom file. 5. **Exit codes**: Most commands use `0` success, `1` runtime error, `2` usage error. Policy commands have documented additional codes; see [Policy reference](./policy-reference.md#validation-flow). @@ -427,6 +485,31 @@ switchbot rules lint && switchbot daemon reload MCP agents use `rules_suggest` + `policy_add_rule` tools for the same pipeline without shell access. +### Rule command parameters + +Rules preserve JSON whitespace and YAML literal-block newlines. They are not +shell commands: YAML consumes its own outer quotes; do not add shell quotes +around JSON. + +Both `setColor 255 0 0` and `setColor 255:0:0` send `255:0:0`. RGBICWW Ceiling +Light's `setColorLightRGB` also accepts both forms. Object arguments can be +written directly in a YAML literal block: + +```yaml +then: + - command: 'devices command setColor 255:0:0' + device: hallway lamp + - command: |- + devices command uploadImage { + "imageUrl": "https://example.com/art.jpg" + } + device: art frame +``` + +Rule dry-runs require a known target/type in the active profile's cache; a cold +or unknown cache fails preflight without a network call. `rules simulate` +evaluates triggers and conditions only—it does not validate or execute actions. + ### Hard limits - **Never** set `automation.enabled: true` without explicitly informing the user. diff --git a/docs/openapi-alignment-ambiguities.md b/docs/openapi-alignment-ambiguities.md index 9091ccf0..9910aa33 100644 --- a/docs/openapi-alignment-ambiguities.md +++ b/docs/openapi-alignment-ambiguities.md @@ -19,3 +19,29 @@ dates and pagination; requiring documented fields does not require a real accoun - [Presence Sensor](https://github.com/OpenWonderLabs/SwitchBotAPI/blob/dc9a6b0e4ad77882c72d186ecd5d134113acdad0/devices/sensors/presence-sensor.md) uses the Contact Sensor's `WoContact` context identifier in its example. [RGBIC Neon Wire Rope Light](https://github.com/OpenWonderLabs/SwitchBotAPI/blob/dc9a6b0e4ad77882c72d186ecd5d134113acdad0/devices/lighting/rgbic-neon-wire-rope-light.md) uses `RGBICWW Strip Light`. Neither ambiguous example is used to invent a distinct webhook mapping. - [Battery Circulator Fan](https://github.com/OpenWonderLabs/SwitchBotAPI/blob/dc9a6b0e4ad77882c72d186ecd5d134113acdad0/devices/climate-control/battery-circulator-fan.md) lists `nightStatus` as Integer but samples `"off"`; [Smart Radiator Thermostat](https://github.com/OpenWonderLabs/SwitchBotAPI/blob/dc9a6b0e4ad77882c72d186ecd5d134113acdad0/devices/climate-control/smart-radiator-thermostat.md) lists `mode` as String but samples `1`. Discovery follows the tables and flags these contradictions; it is advisory, not payload validation or coercion. - Documented webhook identifiers such as `Robot Vacuum Cleaner s20`, `Robot Vacuum Cleaner K20+ Pro`, and `climate Panel` are preserved separately from REST inventory names. No runtime payload is renamed to match the device catalog. + +## 2026-11-05 upstream snapshot + +The following evidence is pinned to upstream commit +[`fa8f90c`](https://github.com/OpenWonderLabs/SwitchBotAPI/commit/fa8f90c661cfa183d633d87f18c04e0e5059fa74) +([delta from the earlier snapshot](https://github.com/OpenWonderLabs/SwitchBotAPI/compare/dc9a6b0e4ad77882c72d186ecd5d134113acdad0...fa8f90c661cfa183d633d87f18c04e0e5059fa74)). +It supplements, rather than replaces, the historical evidence above. + +- [RGBICWW Light Bars](https://github.com/OpenWonderLabs/SwitchBotAPI/blob/fa8f90c661cfa183d633d87f18c04e0e5059fa74/devices/lighting/rgbicww-light-bars.md#L5-L66) + documents the REST type, commands, and webhook field shape, but not an exact + webhook `context.deviceType` or attributable event example. No Light Bars + webhook identifier is registered until upstream supplies that evidence. +- The Light Bars document gives brightness `1–100` for + `setBrightnessAndTemperature` while showing `0` in its example. Local + validation accepts `0–100` for compatibility; server acceptance of `0` + remains unconfirmed. Likewise, local validation accepts any integer `style` + and an empty `colorList`; neither a style enum nor a minimum list length is + confirmed server behavior. +- [Outdoor Pan/Tilt Cam + 3K](https://github.com/OpenWonderLabs/SwitchBotAPI/blob/fa8f90c661cfa183d633d87f18c04e0e5059fa74/devices/cameras/outdoor-pantilt-cam-3k.md#L5-L38) + and [Solar Pan/Tilt Cam + 2K](https://github.com/OpenWonderLabs/SwitchBotAPI/blob/fa8f90c661cfa183d633d87f18c04e0e5059fa74/devices/cameras/solar-pantilt-cam-2k.md#L5-L86) + expose status `latestImage` URLs with `expireAt` in Unix seconds. A cached + status can retain a URL after it expires; consumers must use `expireAt`. + Solar webhook `timeOfSample` is milliseconds, not the status URL expiry + unit. diff --git a/docs/policy-reference.md b/docs/policy-reference.md index 418686bf..020fb045 100644 --- a/docs/policy-reference.md +++ b/docs/policy-reference.md @@ -130,6 +130,7 @@ The destructive blocklist the schema enforces on `never_confirm`: - `nightLatchUnlock` - `createKey` - `deleteKey` +- `disableMotionDetection` - `deleteWebhook` - `deleteScene` - `factoryReset` @@ -222,6 +223,47 @@ automation: dry_run: true # default true in v0.2; writes audit but skips the API call ``` +#### Rule command parameters + +`then[].command` is rule text, not a shell command line. Its grammar is +`devices command [parameter]`. JSON objects and arrays retain +their whitespace and line breaks. YAML quotes delimit the outer YAML string; +do not add shell quotes around JSON or expect flags to be parsed. + +```yaml +then: + - command: 'devices command setColor 255:0:0' + device: hallway lamp + - command: |- + devices command uploadImage { + "imageUrl": "https://example.com/art.jpg" + } + device: art frame +``` + +Both `setColor 255 0 0` and `setColor 255:0:0` are supported; each sends +`255:0:0` after RGB validation. The same compatibility applies to +`setColorLightRGB` on RGBICWW Ceiling Light. Invalid RGB components are rejected. + +#### Rule action inventory and simulation + +Rule action preflight validates the command, parameter, and catalog safety +against the selected profile's cached inventory. Dry-run and test-only +API-skipping execution are cache-only: they make no GET or POST request. +Missing inventory, an unknown or ambiguous type, and invalid parameters fail +closed; prewarm the same profile's inventory before running them. Skipping the +API call skips only dispatch, not validation or safety checks. + +After a successful account change, old inventory and status snapshots are +invalidated at the next use, including in already running processes. Refresh +the new account's inventory before a cache-only rule dry-run. MQTT-triggered +rules need their daemon/subscription restarted for the new account; existing +event history is not cleared. + +`rules simulate` evaluates historical triggers and conditions only. A reported +would-fire result neither executes nor preflights its actions, so it is not +proof that an action can execute. + `suppressIfAlreadyDesired` checks the target's REST status `power` value, case-insensitively, before `turnOn` or `turnOff`. An unknown power state or failed status request keeps the existing best-effort behavior: the action proceeds. @@ -319,11 +361,13 @@ automation: **Destructive commands are refused.** The v0.2 validator rejects `lock`, `unlock`, `deadbolt`, `nightLatchUnlock`, `createKey`, `deleteKey`, `deleteWebhook`, `deleteScene`, and `factoryReset` in any `then[].command`. -Inventory-aware validation also rejects device-specific destructive actions, -including Garage Door Opener `turnOn`/`turnOff`; ordinary light power actions remain allowed. -Before a live rule mutation, the executor resolves missing device metadata and -checks the catalog safety tier. Unknown devices/commands fail closed. Dry-run -does not fetch inventory or mutate devices. +The bare `disableMotionDetection` name is globally prohibited in +`never_confirm`. Separately, the catalog classifies disabling motion detection +on Solar Pan/Tilt Cam 2K as locally destructive; this local safety policy does +not classify every device with that command name or claim a server-side safety +tier. Inventory-aware validation also rejects +device-specific destructive actions, including Garage Door Opener +`turnOn`/`turnOff`; ordinary light power actions remain allowed. **Hot-path behaviour.** Every fire is serialised through a dispatch queue so two MQTT events arriving in the same tick respect throttle diff --git a/docs/schema-versioning.md b/docs/schema-versioning.md index 649ba3ce..3e35c836 100644 --- a/docs/schema-versioning.md +++ b/docs/schema-versioning.md @@ -29,6 +29,20 @@ every command payload has the same version or shape. - Device descriptors in `types` retain their 1.0 shape. Resource changes do not imply a device-entry change. +The unreleased API-alignment changes keep these payload versions: new device +entries add catalog data, and MCP output schemas now describe existing +structured errors as well as successful results. This does **not** make every +behavior change compatible: cold-cache rule dry-runs, the default destructive +command gate, and the policy `never_confirm` restriction have safety or +compatibility implications. Both existing RGB rule forms remain supported. +Assess the CLI release version separately; it is not yet set. + +Credential-scope revisions add private metadata to local device/status cache +files; they do not add fields to the CLI JSON envelope, MCP tool results, or +audit records. Account switching can reject an obsolete in-flight operation or +require an MQTT subscription restart; payload-version stability does not +remove those behavioral boundaries. + ## JSON envelope Every non-streaming JSON success is shaped as follows: diff --git a/src/api/client.ts b/src/api/client.ts index bae12a78..9cf30e86 100644 --- a/src/api/client.ts +++ b/src/api/client.ts @@ -20,6 +20,8 @@ import { recordRequest, checkDailyCap } from '../utils/quota.js'; import { readProfileMeta } from '../config.js'; import { getActiveProfile } from '../lib/request-context.js'; import { redactHeaders, warnOnceIfUnsafe } from '../utils/redact.js'; +import { primeCredentials } from '../credentials/prime.js'; +import { assertCredentialScope, readCredentialScope } from '../credentials/scope.js'; class DailyCapExceededError extends Error { constructor(public readonly cap: number, public readonly total: number, public readonly profile?: string) { @@ -62,9 +64,24 @@ export const apiCircuitBreaker = new CircuitBreaker('switchbot-api', { export { CircuitOpenError }; type RetryableConfig = InternalAxiosRequestConfig & { __retryCount?: number }; +function isUploadImageCommandRequest(response: AxiosResponse): boolean { + const url = response.config.url; + if (!url || !/\/v1\.1\/devices\/[^/]+\/commands(?:\?.*)?$/.test(url)) return false; + + let data: unknown = response.config.data; + if (typeof data === 'string') { + try { + data = JSON.parse(data) as unknown; + } catch { + return false; + } + } + return !!data && typeof data === 'object' && 'command' in data && data.command === 'uploadImage'; +} + export function createClient(): AxiosInstance { - const { token, secret } = loadConfig(); + const scope = readCredentialScope(); const verbose = isVerbose(); const dryRun = isDryRun(); const maxRetries = getRetryOn429(); @@ -81,7 +98,11 @@ export function createClient(): AxiosInstance { }); // Inject auth headers; optionally log the request; short-circuit on --dry-run. - client.interceptors.request.use((config: InternalAxiosRequestConfig) => { + client.interceptors.request.use(async (config: InternalAxiosRequestConfig) => { + assertCredentialScope(scope); + await primeCredentials(profile ?? 'default'); + assertCredentialScope(scope); + const { token, secret } = loadConfig(); // Circuit breaker check — fail fast when the API is consistently down. apiCircuitBreaker.checkAndAllow(); @@ -92,6 +113,7 @@ export function createClient(): AxiosInstance { throw new DailyCapExceededError(dailyCap, check.total, profile); } } + assertCredentialScope(scope); const authHeaders = buildAuthHeaders(token, secret); Object.assign(config.headers, authHeaders); @@ -140,10 +162,11 @@ export function createClient(): AxiosInstance { } const data = response.data as { statusCode?: number; message?: string }; if (data.statusCode !== undefined && data.statusCode !== 100) { - const msg = - API_ERROR_MESSAGES[data.statusCode] ?? - data.message ?? - `API error code: ${data.statusCode}`; + const msg = data.statusCode === 402 && isUploadImageCommandRequest(response) + ? `Image upload quota reached${data.message ? `: ${data.message}` : ''}` + : API_ERROR_MESSAGES[data.statusCode] ?? + data.message ?? + `API error code: ${data.statusCode}`; throw new ApiError(msg, data.statusCode); } // Successful HTTP response — record for circuit breaker. diff --git a/src/commands/auth.ts b/src/commands/auth.ts index 6b9db1b8..7591fd3d 100644 --- a/src/commands/auth.ts +++ b/src/commands/auth.ts @@ -34,7 +34,7 @@ import { browserLogin } from '../auth/browser-login.js'; import type { ExchangeResult } from '../auth/token-exchange.js'; import { verifyCredentials } from '../auth/verify.js'; import { clearPrimedCredentials } from '../credentials/prime.js'; -import { idempotencyCache } from '../lib/idempotency.js'; +import { publishCredentialRevision, readCredentialScope } from '../credentials/scope.js'; function activeProfile(): string { return getActiveProfile() ?? 'default'; @@ -82,11 +82,12 @@ async function promptSecret(question: string): Promise { }); } -export function onCredentialChange(): void { - clearCache(); - clearStatusCache(); - clearPrimedCredentials(activeProfile()); - idempotencyCache.clearForProfile(activeProfile()); +export function onCredentialChange(scope = readCredentialScope(), requireKeychain = false): void { + clearCache(scope); + clearStatusCache(scope); + publishCredentialRevision(scope, requireKeychain); + clearPrimedCredentials(activeProfile(), scope); + // Idempotency keys include this revision, including in other running processes. } function readStdinFile(filePath: string): CredentialBundle { @@ -251,7 +252,7 @@ export function registerAuthCommand(program: Command): void { }); } - onCredentialChange(); + onCredentialChange(readCredentialScope(profile, true), store.name !== 'file'); if (isJsonMode()) { printJson({ profile, backend: store.name, written: true }); return; @@ -289,7 +290,7 @@ export function registerAuthCommand(program: Command): void { }); } - onCredentialChange(); + onCredentialChange(readCredentialScope(profile, true)); if (isJsonMode()) { printJson({ profile, backend: store.name, deleted: true }); return; @@ -370,7 +371,7 @@ export function registerAuthCommand(program: Command): void { } } - onCredentialChange(); + onCredentialChange(readCredentialScope(profile, true), store.name !== 'file'); if (isJsonMode()) { printJson({ profile, @@ -464,7 +465,7 @@ export function registerAuthCommand(program: Command): void { // Credentials changed — clear device/status cache so the next list // fetches fresh data for the new account instead of returning stale // results from the previous account's cache. - onCredentialChange(); + onCredentialChange(readCredentialScope(), backendName !== 'file'); if (isJsonMode()) { printJson({ diff --git a/src/commands/cache.ts b/src/commands/cache.ts index 3b45151f..532fa437 100644 --- a/src/commands/cache.ts +++ b/src/commands/cache.ts @@ -25,13 +25,18 @@ export function registerCacheCommand(program: Command): void { .command('cache') .description('Inspect and manage the local SwitchBot CLI caches') .addHelpText('after', ` -Two caches live at ~/.switchbot/: +Default-profile caches live at ~/.switchbot/: devices.json List of known deviceIds + metadata. Refreshed by every 'devices list' call. Drives command validation and helpful hints — keep around even if you don't use TTL. status.json Per-device status bodies keyed by deviceId. Only written when a status TTL is enabled (via --cache ). +Implicit and explicit --profile default share these files. Named profiles use +separate cache directories; --config stores them beside its config file. +Successful credential changes invalidate the affected scope across processes. +Cache files contain a private, non-secret credential revision. + Cache modes (global flag, apply to any read): --cache off | --no-cache disable cache reads --cache auto (default) list cache on (1h TTL), status cache off diff --git a/src/commands/devices.ts b/src/commands/devices.ts index 2c39ef8e..c9d2ea00 100644 --- a/src/commands/devices.ts +++ b/src/commands/devices.ts @@ -713,7 +713,7 @@ Examples: } const destructive = isDestructiveCommand(cachedForGuard?.type, cmd, options.type); - if (!isDryRun() && destructive && !options.yes && !allowsDirectDestructiveExecution()) { + if (!isDryRun() && destructive && !allowsDirectDestructiveExecution()) { const typeLabel = cachedForGuard?.type ?? 'unknown'; const reason = getDestructiveReason(cachedForGuard?.type, cmd, options.type); exitWithError({ diff --git a/src/commands/expand.ts b/src/commands/expand.ts index 70a96638..df3b0268 100644 --- a/src/commands/expand.ts +++ b/src/commands/expand.ts @@ -53,7 +53,7 @@ Supported expansions: --mode values: auto | cool | dry | fan | heat --fan values: auto | low | mid | high - Curtain / Curtain 3 — setPosition + Curtain / Curtain 3 / Curtain 4 — setPosition --position 50 [--mode silent] → "0,1,50" --mode values: default (ff) | performance (0) | silent (1) diff --git a/src/commands/mcp.ts b/src/commands/mcp.ts index 3a37c9bf..b70e33f8 100644 --- a/src/commands/mcp.ts +++ b/src/commands/mcp.ts @@ -107,6 +107,42 @@ import { readPolicyExampleYaml } from '../embedded-assets.js'; type McpErrorKind = 'api' | 'runtime' | 'usage' | 'guard'; +const structuredToolError = z.object({ + error: z.object({ + code: z.number(), + kind: z.enum(['api', 'runtime', 'usage', 'guard']), + message: z.string(), + hint: z.string().optional(), + retryable: z.boolean().optional(), + context: z.record(z.string(), z.unknown()).optional(), + subKind: z.string().optional(), + errorClass: z.string().optional(), + transient: z.boolean().optional(), + retryAfterMs: z.number().optional(), + }).strict(), +}).strict(); + +/** + * The SDK requires a root object schema and clients validate structured errors + * too. Keep the original success schema and error schema as exclusive branches. + */ +function toolOutputSchema(shape: Record): z.ZodObject { + const success = z.object(shape).strict(); + const optionalShape: Record = {}; + for (const [key, value] of Object.entries(shape)) optionalShape[key] = value.optional(); + optionalShape.error = structuredToolError.shape.error.optional(); + return z.object(optionalShape).strict().superRefine((value, ctx) => { + if (!success.safeParse(value).success && !structuredToolError.safeParse(value).success) { + ctx.addIssue({ code: 'custom', message: 'Expected a complete success or structured error result.' }); + } + }).meta({ + oneOf: [ + z.toJSONSchema(success, { target: 'draft-7', io: 'output' }), + z.toJSONSchema(structuredToolError, { target: 'draft-7', io: 'output' }), + ], + }); +} + function mcpError( kind: McpErrorKind, code: number, @@ -418,7 +454,10 @@ Tool profile: ${profileName} (${allowedTools.size} tools loaded).${profileName ! return callback(args, extra); }; // Every local tool has an input schema; the SDK also supports a separate no-input callback form. - return server.registerTool(name, config, primedCallback as ToolCallback); + const outputSchema = config.outputSchema + ? toolOutputSchema(config.outputSchema as Record) + : undefined; + return server.registerTool(name, { ...config, outputSchema } as typeof config, primedCallback as ToolCallback); }; // ---- list_devices --------------------------------------------------------- @@ -907,9 +946,26 @@ Tool profile: ${profileName} (${allowedTools.size} tools loaded).${profileName ! hint: "Check the deviceId with 'switchbot devices list' (IDs are case-sensitive).", }); } - typeName = physical ? physical.deviceType : ir!.remoteType; + typeName = physical ? physical.deviceType || physical.controlType : ir!.remoteType; } + // validateCommand covers command existence + required/unexpected-parameter. + // stringifiedParam was computed once at the top of the handler so dry-run + // and live paths share the same shape. + const validation = validateCommand(deviceId, effectiveCommand, stringifiedParam, effectiveType); + if (!validation.ok) { + return mcpError( + 'usage', 2, + validation.error.message, + { + hint: validation.error.hint, + context: { validationKind: validation.error.kind, deviceType: typeName, command: effectiveCommand }, + }, + ); + } + if (validation.normalized) { + effectiveCommand = validation.normalized; + } const destructive = isDestructiveCommand(typeName, effectiveCommand, effectiveType); if (destructive && !allowsDirectDestructiveExecution()) { const reason = getDestructiveReason(typeName, effectiveCommand, effectiveType); @@ -954,23 +1010,6 @@ Tool profile: ${profileName} (${allowedTools.size} tools loaded).${profileName ! ); } - // validateCommand covers command existence + required/unexpected-parameter. - // stringifiedParam was computed once at the top of the handler so dry-run - // and live paths share the same shape. - const validation = validateCommand(deviceId, effectiveCommand, stringifiedParam, effectiveType); - if (!validation.ok) { - return mcpError( - 'usage', 2, - validation.error.message, - { - hint: validation.error.hint, - context: { validationKind: validation.error.kind, deviceType: typeName, command: effectiveCommand }, - }, - ); - } - if (validation.normalized) { - effectiveCommand = validation.normalized; - } // R-2: run B-1 client-side parameter validator (range/format checks). // Customize commands (user-defined IR buttons) opt out — the catalog @@ -2872,15 +2911,23 @@ process_uptime_seconds ${Math.floor(process.uptime())} // Resolve keychain-only profiles after authentication, before rejecting // names that have neither credentials nor a profile configuration. if (profile) { - await primeCredentials(profile); - const envCredsPresent = !!(process.env.SWITCHBOT_TOKEN && process.env.SWITCHBOT_SECRET); - if (!envCredsPresent && !getPrimedCredentials(profile) && !fs.existsSync(profileFilePath(profile))) { - res.writeHead(401, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ - jsonrpc: '2.0', - error: { code: -32001, message: `Unknown profile: ${profile}` }, - id: null, - })); + try { + await primeCredentials(profile); + const envCredsPresent = !!(process.env.SWITCHBOT_TOKEN && process.env.SWITCHBOT_SECRET); + if (!envCredsPresent && !getPrimedCredentials(profile) && !fs.existsSync(profileFilePath(profile))) { + res.writeHead(401, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ + jsonrpc: '2.0', + error: { code: -32001, message: `Unknown profile: ${profile}` }, + id: null, + })); + return; + } + } catch { + if (!res.destroyed) { + res.writeHead(500, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32603, message: 'Internal server error' }, id: null })); + } return; } } @@ -2896,20 +2943,20 @@ process_uptime_seconds ${Math.floor(process.uptime())} }); // Route per-request credentials via AsyncLocalStorage so loadConfig() // picks up this request's profile instead of the process-global flag. - await withRequestContext({ profile: profile ?? undefined }, async () => { - await primeCredentials(getActiveProfile() ?? 'default'); - if (res.destroyed) return; - reqServer = createSwitchBotMcpServer({ eventManager, eventManagerProfile: startupProfile, toolProfile }); - try { + try { + await withRequestContext({ profile: profile ?? undefined }, async () => { + await primeCredentials(getActiveProfile() ?? 'default'); + if (res.destroyed) return; + reqServer = createSwitchBotMcpServer({ eventManager, eventManagerProfile: startupProfile, toolProfile }); await reqServer.connect(reqTransport); await reqTransport.handleRequest(req, res); - } catch (err) { - if (!res.headersSent) { - res.writeHead(500, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32603, message: 'Internal server error' }, id: null })); - } + }); + } catch { + if (!res.headersSent && !res.destroyed) { + res.writeHead(500, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32603, message: 'Internal server error' }, id: null })); } - }); + } }); // Graceful shutdown diff --git a/src/config.ts b/src/config.ts index f33253ed..5dad4ed3 100644 --- a/src/config.ts +++ b/src/config.ts @@ -5,7 +5,7 @@ import { createHash } from 'node:crypto'; import { getConfigPath } from './utils/flags.js'; import { assertValidProfileName, getActiveProfile } from './lib/request-context.js'; import { emitJsonError, isJsonMode } from './utils/output.js'; -import { getPrimedCredentials, clearPrimedCredentials } from './credentials/prime.js'; +import { getPrimedCredentials, clearPrimedCredentials, KeychainCredentialsUnavailableError } from './credentials/prime.js'; export interface SwitchBotConfig { token: string; @@ -145,8 +145,13 @@ export function tryLoadConfig(): SwitchBotConfig | null { if (envToken && envSecret) return { token: envToken, secret: envSecret }; if (!getConfigPath()) { - const primed = getPrimedCredentials(getActiveProfile() ?? 'default'); - if (primed) return primed; + try { + const primed = getPrimedCredentials(getActiveProfile() ?? 'default'); + if (primed) return primed; + } catch (error) { + if (error instanceof KeychainCredentialsUnavailableError) return null; + throw error; + } } const file = configFilePath(); diff --git a/src/credentials/prime.ts b/src/credentials/prime.ts index 926cb7df..1b9de75d 100644 --- a/src/credentials/prime.ts +++ b/src/credentials/prime.ts @@ -4,93 +4,112 @@ * `loadConfig()` runs synchronously, but every OS keychain backend is * async (subprocess-based). We bridge the two by priming credentials * once per command, early in the `preAction` hook, and keeping the - * result in a tiny in-process cache keyed by profile name. + * result in a tiny in-process cache keyed by credential storage scope. * - * For long-running processes (MCP server, daemon, status-sync), the - * cache expires after CACHE_TTL_MS so that keychain changes (e.g. from - * a concurrent `switchbot auth login`) are picked up without restart. + * Auth/config commands publish a revision that invalidates other processes + * immediately. The TTL also picks up external keychain edits without restart. * * After priming, sync callers can consult `getPrimedCredentials()` to * pick up keychain-stored token/secret without any await. * - * This module intentionally swallows errors — a flaky keychain - * probe must never block the CLI from running. When the probe fails - * we behave as "nothing primed" and the existing file path is used. + * A flaky keychain probe falls back to the existing config-file path. + * Account changes during an asynchronous lookup instead fail closed. */ import { CredentialBundle, selectCredentialStore } from './keychain.js'; +import { getConfigPath } from '../utils/flags.js'; +import { assertCredentialScope, readCredentialScope, type CredentialScope } from './scope.js'; const CACHE_TTL_MS = 5_000; +export class KeychainCredentialsUnavailableError extends Error { + constructor() { + super('Changed credentials are unavailable from the keychain; unlock the credential store and retry.'); + this.name = 'KeychainCredentialsUnavailableError'; + } +} + interface CacheEntry { - profile: string; + revision: string; creds: CredentialBundle | null; timestamp: number; } const caches = new Map(); const generations = new Map(); -const inFlight = new Map>(); +const inFlight = new Map }>(); -function isCacheValid(profile: string): boolean { - const entry = caches.get(profile); - if (!entry) return false; - return (Date.now() - entry.timestamp) < CACHE_TTL_MS; +function isCacheValid(scope: CredentialScope): boolean { + const entry = caches.get(scope.key); + return entry?.revision === scope.revision && (Date.now() - entry.timestamp) < CACHE_TTL_MS; } -function genFor(profile: string): number { - return generations.get(profile) ?? 0; +function genFor(key: string): number { + return generations.get(key) ?? 0; } /** * Look up the given profile in the active credential store and cache * the result. Subsequent calls within CACHE_TTL_MS short-circuit. * After TTL expires, credentials are re-read from the keychain. - * Swallows all errors. + * Swallows store errors, but rejects a concurrent credential replacement. * - * A per-profile generation counter guards against the race where + * A per-scope generation counter guards against the race where * clearPrimedCredentials(profile) fires while store.get() is still in * flight — if the generation changed, we discard the stale result instead * of overwriting the now-empty cache. */ -async function refreshCredentials(profile: string): Promise { - if (!generations.has(profile)) generations.set(profile, 0); - const gen = genFor(profile); +async function refreshCredentials(profile: string, scope: CredentialScope): Promise { + if (!generations.has(scope.key)) generations.set(scope.key, 0); + const gen = genFor(scope.key); + let creds: CredentialBundle | null = null; + let nativeStore = false; try { const store = await selectCredentialStore(); - const creds = await store.get(profile); - if (genFor(profile) !== gen) return; - caches.set(profile, { profile, creds, timestamp: Date.now() }); + nativeStore = store.name !== 'file'; + creds = await store.get(profile); } catch { - if (genFor(profile) !== gen) return; - caches.set(profile, { profile, creds: null, timestamp: Date.now() }); + // Preserve file fallback for unavailable credential stores. } + assertCredentialScope(scope, profile); + if (genFor(scope.key) !== gen) return; + if (scope.requireKeychain && (!nativeStore || !creds)) { + throw new KeychainCredentialsUnavailableError(); + } + caches.set(scope.key, { revision: scope.revision, creds, timestamp: Date.now() }); } export async function primeCredentials(profile: string): Promise { - // Complete env credentials take precedence; native-store latency must not gate them. - if (process.env.SWITCHBOT_TOKEN && process.env.SWITCHBOT_SECRET) return; - if (isCacheValid(profile)) return; - const existing = inFlight.get(profile); - if (existing) return existing; + // Complete env credentials and explicit config files never wait for keychain. + if ((process.env.SWITCHBOT_TOKEN && process.env.SWITCHBOT_SECRET) || getConfigPath()) return; + const scope = readCredentialScope(profile); + if (isCacheValid(scope)) return; + const existing = inFlight.get(scope.key); + if (existing?.revision === scope.revision) return existing.promise; - const refresh = refreshCredentials(profile); - inFlight.set(profile, refresh); + const refresh = refreshCredentials(profile, scope); + inFlight.set(scope.key, { revision: scope.revision, promise: refresh }); try { await refresh; } finally { - if (inFlight.get(profile) === refresh) inFlight.delete(profile); + if (inFlight.get(scope.key)?.promise === refresh) inFlight.delete(scope.key); } } /** * Sync accessor for code paths that cannot be made async. Returns - * null when the cache is empty or keyed against a different profile, + * null when the cache is empty or belongs to an obsolete credential scope, * so existing file-based fallback stays the authoritative source. * Values are a snapshot; expiry is enforced only by the asynchronous priming path. */ export function getPrimedCredentials(profile: string): CredentialBundle | null { - return caches.get(profile)?.creds ?? null; + if (getConfigPath()) return null; + const scope = readCredentialScope(profile); + const entry = caches.get(scope.key); + if (scope.requireKeychain && (entry?.revision !== scope.revision || !entry.creds)) { + throw new KeychainCredentialsUnavailableError(); + } + return entry?.revision === scope.revision ? entry.creds : null; } /** @@ -112,11 +131,12 @@ export function __resetPrimedCredentials(): void { * Pass a specific `profile` to evict only that profile's entry (preferred * for auth operations on a single profile). Omit to clear all profiles. */ -export function clearPrimedCredentials(profile?: string): void { +export function clearPrimedCredentials(profile?: string, scope?: CredentialScope): void { if (profile !== undefined) { - generations.set(profile, (generations.get(profile) ?? 0) + 1); - caches.delete(profile); - inFlight.delete(profile); + const key = (scope ?? readCredentialScope(profile)).key; + generations.set(key, genFor(key) + 1); + caches.delete(key); + inFlight.delete(key); } else { // Iterate generations.keys() rather than caches.keys() so profiles that // are currently in-flight (primeCredentials awaiting store.get()) also diff --git a/src/credentials/scope.ts b/src/credentials/scope.ts new file mode 100644 index 00000000..c64cb51a --- /dev/null +++ b/src/credentials/scope.ts @@ -0,0 +1,63 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { createHash, randomUUID } from 'node:crypto'; +import { getConfigPath } from '../utils/flags.js'; +import { getActiveProfile } from '../lib/request-context.js'; + +export interface CredentialScope { + key: string; + cacheDir: string; + revision: string; + requireKeychain: boolean; +} + +const REVISION_FILE = '.credential-revision'; + +/** Resolve the existing cache storage scope without creating files on reads. */ +export function readCredentialScope(profile = getActiveProfile(), ignoreConfigOverride = false): CredentialScope { + const override = ignoreConfigOverride ? undefined : getConfigPath(); + let cacheDir = override + ? path.dirname(path.resolve(override)) + : path.join(os.homedir(), '.switchbot'); + if (!override && profile !== undefined && profile !== 'default') { + const hash = createHash('sha256').update(profile).digest('hex').slice(0, 8); + cacheDir = path.join(cacheDir, 'cache', hash); + } + let revision: string; + try { + revision = fs.readFileSync(path.join(cacheDir, REVISION_FILE), 'utf8'); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + revision = ''; + } + return { key: cacheDir, cacheDir, revision, requireKeychain: revision.startsWith('keychain:') }; +} + +export class CredentialScopeChangedError extends Error { + constructor() { + super('Credentials changed during this operation; retry explicitly with the current account.'); + this.name = 'CredentialScopeChangedError'; + } +} + +/** Never complete an old-account operation under a replacement account. */ +export function assertCredentialScope(expected: CredentialScope, profile = getActiveProfile()): void { + const current = readCredentialScope(profile); + if (current.key !== expected.key || current.revision !== expected.revision) { + throw new CredentialScopeChangedError(); + } +} + +/** Publish only after old account caches have been removed. Contains no secrets. */ +export function publishCredentialRevision(scope: CredentialScope, requireKeychain = false): void { + fs.mkdirSync(scope.cacheDir, { recursive: true, mode: 0o700 }); + const revision = randomUUID(); + const temporary = path.join(scope.cacheDir, `${REVISION_FILE}.${revision}.tmp`); + try { + fs.writeFileSync(temporary, requireKeychain ? `keychain:${revision}` : revision, { mode: 0o600, flag: 'wx' }); + fs.renameSync(temporary, path.join(scope.cacheDir, REVISION_FILE)); + } finally { + fs.rmSync(temporary, { force: true }); + } +} diff --git a/src/devices/cache.ts b/src/devices/cache.ts index 09f5fc5d..d183a78d 100644 --- a/src/devices/cache.ts +++ b/src/devices/cache.ts @@ -1,30 +1,7 @@ import fs from 'node:fs'; import path from 'node:path'; -import os from 'node:os'; -import { createHash } from 'node:crypto'; -import { getConfigPath } from '../utils/flags.js'; -import { getActiveProfile } from '../lib/request-context.js'; - -/** - * Returns the directory where cache files should be stored. - * - * - If a profile is active, scopes into a per-profile sub-directory so that - * rotating credentials or switching profiles never serves stale inventory - * from a prior session (Bug #37). - * - If no profile is active (unnamed / default), returns `baseDir` unchanged - * so the existing legacy path (~/.switchbot/devices.json) is preserved. - * - * Only called when `getConfigPath()` returns undefined — the --config-path - * override takes full precedence and bypasses this helper entirely. - */ -function scopedCacheDir(baseDir: string): string { - const profile = getActiveProfile(); - if (profile === undefined) return baseDir; - const hash = createHash('sha256').update(profile).digest('hex').slice(0, 8); - const dir = path.join(baseDir, 'cache', hash); - if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); - return dir; -} +import { randomUUID } from 'node:crypto'; +import { assertCredentialScope, readCredentialScope, type CredentialScope } from '../credentials/scope.js'; /** GC cutoff for status entries: evict anything older than this. */ const DEFAULT_STATUS_GC_TTL_MS = 24 * 60 * 60 * 1000; // 24 h @@ -68,56 +45,60 @@ export interface DeviceListBodyShape { }>; } -function cacheFilePath(): string { - const override = getConfigPath(); - const dir = override - ? path.dirname(path.resolve(override)) - : scopedCacheDir(path.join(os.homedir(), '.switchbot')); - return path.join(dir, 'devices.json'); +function cacheFilePath(scope = readCredentialScope()): string { + return path.join(scope.cacheDir, 'devices.json'); } -// In-memory hot-cache keyed by active profile (or '__default__' for no profile). -// Using Maps instead of module-level singletons ensures that mcp serve, which -// rotates profiles per request via withRequestContext, never leaks inventory -// across profiles within the same process (Bug #37). -const _listCacheByProfile = new Map(); -const _statusCacheByProfile = new Map(); +interface CacheSnapshot { + revision: string; + value: T; +} -function cacheKey(): string { - return getActiveProfile() ?? '__default__'; +/** Commit the data and its credential revision as one indivisible document. */ +function writeCacheFile(file: string, cache: DeviceCache | StatusCache, scope: CredentialScope): void { + fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); + const temporary = `${file}.${randomUUID()}.tmp`; + try { + fs.writeFileSync(temporary, JSON.stringify({ ...cache, _credentialRevision: scope.revision }, null, 2), { + mode: 0o600, flag: 'wx', + }); + fs.renameSync(temporary, file); + } finally { + fs.rmSync(temporary, { force: true }); + } } +// Storage scope includes --config precedence; revisions invalidate warm readers +// when credentials are changed by a different process. +const _listCacheByScope = new Map>(); +const _statusCacheByScope = new Map>(); + /** Force the next loadCache() call to re-read from disk. Used in tests. */ export function resetListCache(): void { - _listCacheByProfile.clear(); + _listCacheByScope.clear(); } /** Force the next loadStatusCache() call to re-read from disk. Used in tests. */ export function resetStatusCache(): void { - _statusCacheByProfile.clear(); + _statusCacheByScope.clear(); } export function loadCache(): DeviceCache | null { - const key = cacheKey(); - if (_listCacheByProfile.has(key)) return _listCacheByProfile.get(key)!; - const file = cacheFilePath(); - if (!fs.existsSync(file)) { - _listCacheByProfile.set(key, null); - return null; - } + const scope = readCredentialScope(); + const snapshot = _listCacheByScope.get(scope.key); + if (snapshot?.revision === scope.revision) return snapshot.value; + let value: DeviceCache | null = null; try { - const raw = fs.readFileSync(file, 'utf-8'); - const cache = JSON.parse(raw) as DeviceCache; - if (!cache || typeof cache.devices !== 'object' || cache.devices === null) { - _listCacheByProfile.set(key, null); - return null; + const parsed = JSON.parse(fs.readFileSync(cacheFilePath(scope), 'utf8')) as DeviceCache & { _credentialRevision?: string }; + if (parsed && typeof parsed.devices === 'object' && parsed.devices !== null && + (parsed._credentialRevision ?? '') === scope.revision) { + value = { lastUpdated: parsed.lastUpdated, devices: parsed.devices }; } - _listCacheByProfile.set(key, cache); - return cache; } catch { - _listCacheByProfile.set(key, null); - return null; + // Missing, unreadable or malformed cache data is a cache miss. } + _listCacheByScope.set(scope.key, { revision: scope.revision, value }); + return value; } export function getCachedDevice(deviceId: string): CachedDevice | null { @@ -146,7 +127,8 @@ export function getCachedTypeMap(deviceIds?: Iterable): Map = {}; for (const d of body.deviceList) { @@ -186,19 +168,17 @@ export function updateCacheFromDeviceList(body: DeviceListBodyShape): void { }; try { - const file = cacheFilePath(); - const dir = path.dirname(file); - if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); - fs.writeFileSync(file, JSON.stringify(cache, null, 2), { mode: 0o600 }); - _listCacheByProfile.set(cacheKey(), cache); + writeCacheFile(cacheFilePath(scope), cache, scope); + _listCacheByScope.set(scope.key, { revision: scope.revision, value: cache }); } catch { // Cache write failures must not break the command that triggered them. } + assertCredentialScope(scope); } -export function clearCache(): void { - _listCacheByProfile.set(cacheKey(), null); - const file = cacheFilePath(); +export function clearCache(scope = readCredentialScope()): void { + _listCacheByScope.set(scope.key, { revision: scope.revision, value: null }); + const file = cacheFilePath(scope); if (fs.existsSync(file)) { try { fs.unlinkSync(file); } catch (e) { if ((e as NodeJS.ErrnoException).code !== 'EBUSY') throw e; } } @@ -241,47 +221,32 @@ export interface StatusCache { entries: Record; } -function statusCacheFilePath(): string { - const override = getConfigPath(); - const dir = override - ? path.dirname(path.resolve(override)) - : scopedCacheDir(path.join(os.homedir(), '.switchbot')); - return path.join(dir, 'status.json'); +function statusCacheFilePath(scope = readCredentialScope()): string { + return path.join(scope.cacheDir, 'status.json'); } export function loadStatusCache(): StatusCache { - const key = cacheKey(); - if (_statusCacheByProfile.has(key)) return _statusCacheByProfile.get(key)!; - const file = statusCacheFilePath(); - if (!fs.existsSync(file)) { - const empty = { entries: {} }; - _statusCacheByProfile.set(key, empty); - return empty; - } + const scope = readCredentialScope(); + const snapshot = _statusCacheByScope.get(scope.key); + if (snapshot?.revision === scope.revision) return snapshot.value; + let value: StatusCache = { entries: {} }; try { - const raw = fs.readFileSync(file, 'utf-8'); - const parsed = JSON.parse(raw) as StatusCache; - if (!parsed || typeof parsed.entries !== 'object' || parsed.entries === null) { - const empty = { entries: {} }; - _statusCacheByProfile.set(key, empty); - return empty; + const parsed = JSON.parse(fs.readFileSync(statusCacheFilePath(scope), 'utf8')) as StatusCache & { _credentialRevision?: string }; + if (parsed && typeof parsed.entries === 'object' && parsed.entries !== null && + (parsed._credentialRevision ?? '') === scope.revision) { + value = { entries: parsed.entries }; } - _statusCacheByProfile.set(key, parsed); - return parsed; } catch { - const empty = { entries: {} }; - _statusCacheByProfile.set(key, empty); - return empty; + // Missing, unreadable or malformed cache data is a cache miss. } + _statusCacheByScope.set(scope.key, { revision: scope.revision, value }); + return value; } -function saveStatusCache(cache: StatusCache): void { - _statusCacheByProfile.set(cacheKey(), cache); +function saveStatusCache(cache: StatusCache, scope: CredentialScope): void { + _statusCacheByScope.set(scope.key, { revision: scope.revision, value: cache }); try { - const file = statusCacheFilePath(); - const dir = path.dirname(file); - if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); - fs.writeFileSync(file, JSON.stringify(cache, null, 2), { mode: 0o600 }); + writeCacheFile(statusCacheFilePath(scope), cache, scope); } catch { /* best-effort */ } @@ -333,20 +298,23 @@ export function setCachedStatus( deviceId: string, body: Record, now = new Date(), - ttlMsForGc = DEFAULT_STATUS_GC_TTL_MS + ttlMsForGc = DEFAULT_STATUS_GC_TTL_MS, + scope = readCredentialScope(), ): void { + assertCredentialScope(scope); const cache = loadStatusCache(); cache.entries[deviceId] = { fetchedAt: now.toISOString(), body, }; evictExpiredStatusEntries(cache, ttlMsForGc, now.getTime()); - saveStatusCache(cache); + saveStatusCache(cache, scope); + assertCredentialScope(scope); } -export function clearStatusCache(): void { - _statusCacheByProfile.set(cacheKey(), { entries: {} }); - const file = statusCacheFilePath(); +export function clearStatusCache(scope = readCredentialScope()): void { + _statusCacheByScope.set(scope.key, { revision: scope.revision, value: { entries: {} } }); + const file = statusCacheFilePath(scope); if (fs.existsSync(file)) { try { fs.unlinkSync(file); } catch (e) { if ((e as NodeJS.ErrnoException).code !== 'EBUSY') throw e; } } diff --git a/src/devices/catalog.ts b/src/devices/catalog.ts index 9110cb6c..fe3d989a 100644 --- a/src/devices/catalog.ts +++ b/src/devices/catalog.ts @@ -154,6 +154,7 @@ const STATUS_FIELD_DESCRIPTIONS: Record = { doorStatus: "Garage door position state", displayMode: "Art Frame display mode", imageUrl: "Current Art Frame image URL", + latestImage: 'Latest image object; empty when unavailable, otherwise imageUrl and expireAt (Unix seconds)', waterBaseBattery: "Vacuum water-base battery percentage", drying: "Humidifier drying state", position: "Device position percentage", @@ -224,6 +225,25 @@ const rgbOnlyLightControls0To100: CommandSpec[] = [ { command: 'setBrightness', parameter: '0-100', description: 'Set brightness percentage', idempotent: true, exampleParams: ['0', '50', '100'] }, { command: 'setColor', parameter: 'R:G:B (0-255 each)', description: 'Set RGB color, e.g. "255:0:0"', idempotent: true, exampleParams: ['255:0:0', '255:255:255'] }, ]; +const lightEffect: CommandSpec = { + command: 'setLightEffect', + parameter: '{"effectId":0-25}', + description: 'Set the preset lighting effect', + idempotent: false, + exampleParams: ['{"effectId":1}'], +}; +const k11Commands: CommandSpec[] = [ + { command: 'startClean', parameter: '\'{"action":"sweep"|"mop","param":{"fanLevel":1-4,"times":1-2639999}}\'', description: 'Begin a cleaning session', idempotent: false, exampleParams: ['{"action":"sweep","param":{"fanLevel":2,"times":1}}'] }, + { command: 'pause', parameter: '—', description: 'Pause cleaning', idempotent: true }, + { command: 'dock', parameter: '—', description: 'Return to dock', idempotent: true }, + { command: 'setVolume', parameter: '0-100', description: 'Set voice volume', idempotent: true, exampleParams: ['0', '50', '100'] }, + { command: 'changeParam', parameter: '\'{"fanLevel":1-4,"waterLevel":1-2,"times":1-2639999}\'', description: 'Change parameters mid-run', idempotent: true, exampleParams: ['{"fanLevel":3,"waterLevel":1,"times":1}'] }, +]; +const artFrameCommands: CommandSpec[] = [ + { command: 'next', parameter: '—', description: 'Switch to the next image', idempotent: false }, + { command: 'previous', parameter: '—', description: 'Switch to the previous image', idempotent: false }, + { command: 'uploadImage', parameter: '{"imageUrl":"..."} or {"imageBase64":"..."}', description: 'Upload a new image from exactly one URL or base64 image source.', idempotent: true, exampleParams: ['{"imageUrl":"https://example.com/art.jpg"}', '{"imageBase64":"data:image/jpeg;base64,..."}'] }, +]; export const DEVICE_CATALOG: DeviceCatalogEntry[] = [ // ---------- Physical devices ---------- @@ -253,7 +273,7 @@ export const DEVICE_CATALOG: DeviceCatalogEntry[] = [ category: 'physical', description: 'Motorized curtain track runner that opens/closes curtains by slide position (0=open, 100=closed).', role: 'curtain', - aliases: ['Curtain3', 'Curtain 3'], + aliases: ['Curtain3', 'Curtain 3', 'Curtain4', 'Curtain 4'], commands: [ ...onOff, { command: 'pause', parameter: '—', description: 'Stop movement', idempotent: true }, @@ -293,7 +313,7 @@ export const DEVICE_CATALOG: DeviceCatalogEntry[] = [ category: 'physical', description: 'Premium electronic deadbolt with full lock, unlock, and deadbolt control.', role: 'security', - aliases: ['Lock Ultra'], + aliases: ['Lock Ultra', 'Smart Lock Ultra Max', 'Lock Ultra Max'], commands: [ { command: 'lock', parameter: '—', description: 'Lock the door', idempotent: true }, { command: 'unlock', parameter: '—', description: 'Unlock the door', idempotent: true, safetyTier: 'destructive', safetyReason: 'Physically unlocks the door — anyone nearby can open it.' }, @@ -475,12 +495,30 @@ export const DEVICE_CATALOG: DeviceCatalogEntry[] = [ commands: [...onOffToggle, ...rgbLightControls0To100], statusFields: ['power', 'brightness', 'color', 'colorTemperature', 'version'], }, + { + type: 'RGBICWW Light Bars', + category: 'physical', + description: 'RGBICWW light bars with brightness, color, music and lighting effects.', + role: 'lighting', + commands: [ + ...onOffToggle, + ...rgbLightControls0To100, + { command: 'setBrightnessAndTemperature', parameter: '{"brightness":0-100,"temperature":2700-6500}', description: 'Set brightness and color temperature together', idempotent: true, exampleParams: ['{"brightness":50,"temperature":4000}'] }, + { command: 'setMusicColorMode', parameter: '{"colorList":["R:G:B"]}', description: 'Set music-mode colors', idempotent: false, exampleParams: ['{"colorList":["255:0:0"]}'] }, + { command: 'setMusicParamMode', parameter: '{"musicMode":0-5,"musicLevel":1-100,"sensitivity":1-100,"controllerMode":0-2}', description: 'Set music-mode parameters', idempotent: false, exampleParams: ['{"musicMode":0,"musicLevel":50,"sensitivity":50,"controllerMode":0}'] }, + { command: 'setEffectColorMode', parameter: '{"style":integer,"colorList":["R:G:B"]}', description: 'Set effect colors', idempotent: false, exampleParams: ['{"style":1,"colorList":["255:0:0"]}'] }, + { command: 'setEffectSpeedMode', parameter: '{"speed":1-255}', description: 'Set effect speed', idempotent: false, exampleParams: ['{"speed":100}'] }, + { command: 'setSegmentColorMode', parameter: '{"color":"R:G:B","lightIndex":0-11}', description: 'Set a segment color', idempotent: false, exampleParams: ['{"color":"255:0:0","lightIndex":0}'] }, + lightEffect, + ], + statusFields: ['version', 'power', 'onlineStatus', 'brightness', 'color', 'colorTemperature'], + }, { type: 'RGBICWW Strip Light', category: 'physical', description: 'RGBICWW strip light with 0-100 brightness, RGB color, and color temperature control.', role: 'lighting', - commands: [...onOffToggle, ...rgbLightControls0To100], + commands: [...onOffToggle, ...rgbLightControls0To100, lightEffect], statusFields: ['power', 'brightness', 'color', 'colorTemperature', 'version', 'onlineStatus'], }, { @@ -488,7 +526,7 @@ export const DEVICE_CATALOG: DeviceCatalogEntry[] = [ category: 'physical', description: 'RGBICWW floor lamp with 0-100 brightness, RGB color, and color temperature control.', role: 'lighting', - commands: [...onOffToggle, ...rgbLightControls0To100], + commands: [...onOffToggle, ...rgbLightControls0To100, lightEffect], statusFields: ['power', 'brightness', 'color', 'colorTemperature', 'version', 'onlineStatus'], }, { @@ -496,7 +534,7 @@ export const DEVICE_CATALOG: DeviceCatalogEntry[] = [ category: 'physical', description: 'RGBIC neon wire rope light with 0-100 brightness and RGB color control.', role: 'lighting', - commands: [...onOffToggle, ...rgbOnlyLightControls0To100], + commands: [...onOffToggle, ...rgbOnlyLightControls0To100, lightEffect], statusFields: ['power', 'brightness', 'color', 'version', 'onlineStatus'], }, { @@ -504,7 +542,7 @@ export const DEVICE_CATALOG: DeviceCatalogEntry[] = [ category: 'physical', description: 'RGBIC neon rope light with 0-100 brightness and RGB color control.', role: 'lighting', - commands: [...onOffToggle, ...rgbOnlyLightControls0To100], + commands: [...onOffToggle, ...rgbOnlyLightControls0To100, lightEffect], statusFields: ['power', 'brightness', 'color', 'version', 'onlineStatus'], }, { @@ -517,6 +555,7 @@ export const DEVICE_CATALOG: DeviceCatalogEntry[] = [ { command: 'setBrightness', parameter: '{0-100}', description: 'Set brightness (0-100)', idempotent: true, exampleParams: ['50'] }, { command: 'setColor', parameter: '\'{0-255}:{0-255}:{0-255}\'', description: 'Set RGB color', idempotent: true, exampleParams: ['255:0:0'] }, { command: 'setColorTemperature', parameter: '{2700-6500}', description: 'Set color temperature in Kelvin', idempotent: true, exampleParams: ['4000'] }, + lightEffect, ], statusFields: ['power', 'onlineStatus', 'brightness', 'color', 'colorTemperature', 'version'], }, @@ -548,6 +587,7 @@ export const DEVICE_CATALOG: DeviceCatalogEntry[] = [ { command: 'setMainLightColorTemp', parameter: '{2700-6500}', description: 'Set main light color temperature (K)', idempotent: true, exampleParams: ['4000'] }, { command: 'setColorLightBrightness', parameter: '{1-100}', description: 'Set color light brightness', idempotent: true, exampleParams: ['50'] }, { command: 'setColorLightRGB', parameter: '\'{0-255}:{0-255}:{0-255}\'', description: 'Set color light RGB color', idempotent: true, exampleParams: ['255:0:0'] }, + { ...lightEffect, description: 'Set the ambient color light effect' }, ], statusFields: ['power', 'onlineStatus', 'mainLightPower', 'mainLightBrightness', 'mainLightColorTemp', 'colorLightPower', 'colorLightBrightness', 'colorLightRGB', 'version'], }, @@ -613,13 +653,16 @@ export const DEVICE_CATALOG: DeviceCatalogEntry[] = [ description: 'Robot vacuum and mop with sweep/mop sessions, fan-level control, and adjustable mop moisture.', role: 'cleaning', aliases: ['K11+', 'Robot Vacuum Cleaner K11 Plus'], - commands: [ - { command: 'startClean', parameter: '\'{"action":"sweep"|"mop","param":{"fanLevel":1-4,"times":1-2639999}}\'', description: 'Begin a cleaning session', idempotent: false, exampleParams: ['{"action":"sweep","param":{"fanLevel":2,"times":1}}'] }, - { command: 'pause', parameter: '—', description: 'Pause cleaning', idempotent: true }, - { command: 'dock', parameter: '—', description: 'Return to dock', idempotent: true }, - { command: 'setVolume', parameter: '0-100', description: 'Set voice volume', idempotent: true, exampleParams: ['0', '50', '100'] }, - { command: 'changeParam', parameter: '\'{"fanLevel":1-4,"waterLevel":1-2,"times":1-2639999}\'', description: 'Change parameters mid-run', idempotent: true, exampleParams: ['{"fanLevel":3,"waterLevel":1,"times":1}'] }, - ], + commands: k11Commands, + statusFields: ['workingStatus', 'onlineStatus', 'battery', 'taskType'], + }, + { + type: 'Robot Vacuum Cleaner K11 Plus Pro', + category: 'physical', + description: 'Robot vacuum and mop with sweep/mop sessions and adjustable cleaning parameters.', + role: 'cleaning', + aliases: ['K11+ Pro', 'Robot Vacuum K11+ Pro'], + commands: k11Commands, statusFields: ['workingStatus', 'onlineStatus', 'battery', 'taskType'], }, { @@ -754,13 +797,18 @@ export const DEVICE_CATALOG: DeviceCatalogEntry[] = [ category: 'physical', description: 'Digital art frame that can switch images and accept new artwork uploads.', role: 'other', - commands: [ - { command: 'next', parameter: '—', description: 'Switch to the next image', idempotent: false }, - { command: 'previous', parameter: '—', description: 'Switch to the previous image', idempotent: false }, - { command: 'uploadImage', parameter: '{\"imageUrl\":\"...\"} or {\"imageBase64\":\"...\"}', description: 'Upload a new image from exactly one URL or base64 image source.', idempotent: true, exampleParams: ['{\"imageUrl\":\"https://example.com/art.jpg\"}', '{\"imageBase64\":\"data:image/jpeg;base64,...\"}'] }, - ], + commands: artFrameCommands, statusFields: ['battery', 'displayMode', 'imageUrl', 'version'], }, + { + type: 'AI Art Frame Luma', + category: 'physical', + description: 'Digital art frame with image uploads and online status.', + role: 'other', + aliases: ['AI Art Frame 2'], + commands: artFrameCommands, + statusFields: ['battery', 'displayMode', 'imageUrl', 'onlineStatus', 'version'], + }, // Status-only devices (no commands) { type: 'Meter', @@ -907,6 +955,26 @@ export const DEVICE_CATALOG: DeviceCatalogEntry[] = [ commands: [], statusFields: ['battery', 'version'], }, + { + type: 'Outdoor Pan/Tilt Cam 3K', + category: 'physical', + description: 'Outdoor camera exposing the latest image URL and expiry through status; no cloud controls.', + role: 'security', + readOnly: true, + commands: [], + statusFields: ['latestImage'], + }, + { + type: 'Solar Pan/Tilt Cam 2K', + category: 'physical', + description: 'Outdoor solar camera with status and motion detection control; only the outdoor unit is listed.', + role: 'security', + commands: [ + { command: 'enableMotionDetection', parameter: '—', description: 'Enable motion detection', idempotent: true }, + { command: 'disableMotionDetection', parameter: '—', description: 'Disable motion detection', idempotent: true, safetyTier: 'destructive', safetyReason: 'Disables camera motion detection and its security alerts.' }, + ], + statusFields: ['version', 'battery', 'online', 'latestImage'], + }, { type: 'Indoor Cam', category: 'physical', diff --git a/src/devices/param-validator.ts b/src/devices/param-validator.ts index c2c50fc6..c5d021ad 100644 --- a/src/devices/param-validator.ts +++ b/src/devices/param-validator.ts @@ -7,6 +7,15 @@ export const AC_FAN_MAP: Record = { auto: 1, low: 2, mid: 3, hig export const CURTAIN_MODE_MAP: Record = { default: 'ff', performance: '0', silent: '1' }; export const RELAY_MODE_MAP: Record = { toggle: 0, edge: 1, detached: 2, momentary: 3 }; const BLIND_DIRECTION = new Set(['up', 'down']); +const LIGHT_EFFECT_DEVICES: Record = { + 'Permanent Outdoor Lights': true, + 'RGBIC Neon Rope Light': true, + 'RGBIC Neon Wire Rope Light': true, + 'RGBICWW Ceiling Light': true, + 'RGBICWW Floor Lamp': true, + 'RGBICWW Strip Light': true, + 'RGBICWW Light Bars': true, +}; // ---- Semantic-flag builders (used by `devices expand`) -------------------- @@ -180,6 +189,20 @@ export function validateParameter( return validateIntRange(raw, 'setPosition', 0, 100, 'Relay Switch 2PM roller-shade percentage'); } + if (command === 'setLightEffect' && LIGHT_EFFECT_DEVICES[dt] === true) { + return validateLightEffect(raw); + } + if (dt === 'RGBICWW Light Bars') { + switch (command) { + case 'setBrightnessAndTemperature': + case 'setMusicColorMode': + case 'setMusicParamMode': + case 'setEffectColorMode': + case 'setEffectSpeedMode': + case 'setSegmentColorMode': + return validateLightBarsObject(command, raw); + } + } // --- Lighting --- if (command === 'setBrightness' && isBrightnessDevice(dt)) { return validateSetBrightness(raw, dt); @@ -192,7 +215,7 @@ export function validateParameter( } // --- AI Art Frame --- - if (dt === "AI Art Frame" && command === "uploadImage") { + if ((dt === "AI Art Frame" || dt === "AI Art Frame Luma") && command === "uploadImage") { return validateArtFrameUploadImage(raw); } @@ -307,6 +330,87 @@ export function validateParameter( return { ok: true }; } +function validateLightEffect(raw: string | undefined): ValidateResult { + let value: unknown; + try { + value = JSON.parse(raw ?? ''); + } catch { + return { ok: false, error: 'setLightEffect requires a JSON object with integer effectId 0-25.' }; + } + if (typeof value !== 'object' || value === null || Array.isArray(value)) { + return { ok: false, error: 'setLightEffect requires a JSON object with integer effectId 0-25.' }; + } + const effectId = (value as Record).effectId; + if (typeof effectId !== 'number' || !Number.isInteger(effectId) || effectId < 0 || effectId > 25) { + return { ok: false, error: 'setLightEffect requires an integer effectId between 0 and 25.' }; + } + return { ok: true, normalized: JSON.stringify(value) }; +} + +function validateLightBarsObject(command: string, raw: string | undefined): ValidateResult { + let value: unknown; + try { + value = JSON.parse(raw ?? ''); + } catch { + return { ok: false, error: `${command} requires a JSON object.` }; + } + if (typeof value !== 'object' || value === null || Array.isArray(value)) { + return { ok: false, error: `${command} requires a JSON object.` }; + } + const object = value as Record; + const integer = (key: string, min: number, max: number): boolean => + typeof object[key] === 'number' && Number.isInteger(object[key]) && object[key] >= min && object[key] <= max; + const color = (input: unknown): string | null => { + if (typeof input !== 'string') return null; + const result = validateRgbTriplet(input, command); + return result.ok ? result.normalized ?? input : null; + }; + const colors = (): boolean => { + if (!Array.isArray(object.colorList)) return false; + for (let i = 0; i < object.colorList.length; i++) { + const normalized = color(object.colorList[i]); + if (normalized === null) return false; + object.colorList[i] = normalized; + } + return true; + }; + let valid = false; + let expected = ''; + switch (command) { + case 'setBrightnessAndTemperature': + valid = integer('brightness', 0, 100) && integer('temperature', 2700, 6500); + expected = 'integer brightness 0-100 and temperature 2700-6500'; + break; + case 'setMusicColorMode': + valid = colors(); + expected = 'colorList array of R:G:B strings'; + break; + case 'setMusicParamMode': + valid = integer('musicMode', 0, 5) && integer('musicLevel', 1, 100) && + integer('sensitivity', 1, 100) && integer('controllerMode', 0, 2); + expected = 'integer musicMode 0-5, musicLevel/sensitivity 1-100, controllerMode 0-2'; + break; + case 'setEffectColorMode': + valid = typeof object.style === 'number' && Number.isInteger(object.style) && colors(); + expected = 'integer style and colorList array of R:G:B strings'; + break; + case 'setEffectSpeedMode': + valid = integer('speed', 1, 255); + expected = 'integer speed 1-255'; + break; + case 'setSegmentColorMode': { + const normalized = color(object.color); + valid = normalized !== null && integer('lightIndex', 0, 11); + if (normalized !== null) object.color = normalized; + expected = 'color R:G:B and integer lightIndex 0-11'; + break; + } + } + return valid + ? { ok: true, normalized: JSON.stringify(object) } + : { ok: false, error: `${command} requires ${expected}.` }; +} + function isBrightnessDevice(deviceType: string): boolean { return brightnessRange(deviceType) !== null; } @@ -324,6 +428,7 @@ export function brightnessRange(deviceType: string): [number, number] | null { deviceType === 'Floor Lamp' || deviceType === 'Strip Light 3' || deviceType === 'RGBICWW Strip Light' || + deviceType === 'RGBICWW Light Bars' || deviceType === 'RGBICWW Floor Lamp' || deviceType === 'RGBIC Neon Wire Rope Light' || deviceType === 'RGBIC Neon Rope Light' || @@ -349,6 +454,7 @@ function isColorDevice(deviceType: string): boolean { deviceType === 'Strip Light 3' || deviceType === 'Floor Lamp' || deviceType === 'RGBICWW Strip Light' || + deviceType === 'RGBICWW Light Bars' || deviceType === 'RGBICWW Floor Lamp' || deviceType === 'RGBIC Neon Wire Rope Light' || deviceType === 'RGBIC Neon Rope Light' || @@ -366,6 +472,7 @@ function isColorTemperatureDevice(deviceType: string): boolean { deviceType === 'Ceiling Light' || deviceType === 'Ceiling Light Pro' || deviceType === 'RGBICWW Strip Light' || + deviceType === 'RGBICWW Light Bars' || deviceType === 'RGBICWW Floor Lamp' || deviceType === 'Light Strip' || deviceType === 'Dimmer' || @@ -403,7 +510,8 @@ function isWaterLevelVacuum(deviceType: string): boolean { deviceType === 'Robot Vacuum Cleaner K20 Plus Pro' || deviceType === 'K11+' || deviceType === 'Robot Vacuum Cleaner K11+' || - deviceType === 'Robot Vacuum Cleaner K11 Plus' + deviceType === 'Robot Vacuum Cleaner K11 Plus' || + deviceType === 'Robot Vacuum Cleaner K11 Plus Pro' ); } @@ -904,16 +1012,13 @@ function validateArtFrameUploadImage(raw: string | undefined): ValidateResult { return { ok: false, error: "uploadImage expects a JSON object with exactly one non-empty imageUrl or imageBase64 field." }; } - const hasImageUrl = "imageUrl" in parsed - && typeof parsed.imageUrl === "string" - && parsed.imageUrl.trim().length > 0; - const hasImageBase64 = "imageBase64" in parsed - && typeof parsed.imageBase64 === "string" - && parsed.imageBase64.trim().length > 0; - if (hasImageUrl === hasImageBase64) { + const hasImageUrl = Object.hasOwn(parsed, "imageUrl"); + const hasImageBase64 = Object.hasOwn(parsed, "imageBase64"); + const source = hasImageUrl ? (parsed as Record).imageUrl : (parsed as Record).imageBase64; + if (hasImageUrl === hasImageBase64 || typeof source !== "string" || source.trim().length === 0) { return { ok: false, error: "uploadImage requires exactly one non-empty imageUrl or imageBase64 field." }; } - return { ok: true }; + return { ok: true, normalized: JSON.stringify(parsed) }; } // ---- Humidifier ------------------------------------------------------------- @@ -1141,6 +1246,9 @@ function validateVacuumChangeParam(raw: string | undefined, deviceType: string): } normalized.times = t; } + if (deviceType === 'Robot Vacuum Cleaner K11 Plus Pro' && Object.keys(normalized).length === 0) { + return { ok: false, error: 'K11+ Pro changeParam requires at least one supported parameter.' }; + } return { ok: true, normalized: JSON.stringify(normalized) }; } diff --git a/src/devices/resources.ts b/src/devices/resources.ts index 91111f95..391e5050 100644 --- a/src/devices/resources.ts +++ b/src/devices/resources.ts @@ -226,6 +226,19 @@ export const RESOURCE_CATALOG: ResourceCatalog = { ], }, }, + { + eventType: 'changeReport', + eventVersion: '1', + devicePattern: 'Lock Ultra Max', + context: { + deviceType: 'Smart Lock Ultra Max', + fields: [ + ...COMMON_WEBHOOK_CONTEXT_FIELDS, + { name: 'lockState', type: 'string', description: 'The state of the device: LOCKED, UNLOCKED, or JAMMED.' }, + { name: 'battery', type: 'number', description: 'The current battery level (0–100).' }, + ], + }, + }, { eventType: 'changeReport', eventVersion: '1', @@ -255,7 +268,7 @@ export const RESOURCE_CATALOG: ResourceCatalog = { eventVersion: '1', devicePattern: 'Plug Mini (EU)', context: { - deviceType: 'WoPlugEU', + deviceType: 'Plug Mini (EU)', fields: [ { name: 'deviceMac', type: 'string', description: 'Device MAC address.' }, { name: 'online', type: 'boolean', description: 'Whether the plug is connected.' }, @@ -343,6 +356,21 @@ export const RESOURCE_CATALOG: ResourceCatalog = { ], }, }, + { + eventType: 'changeReport', + eventVersion: '1', + devicePattern: 'Curtain 4', + context: { + deviceType: 'WoCurtain4', + fields: [ + ...COMMON_WEBHOOK_CONTEXT_FIELDS, + { name: 'calibrate', type: 'boolean', description: 'Whether the open and close positions have been calibrated.' }, + { name: 'group', type: 'boolean', description: 'Whether the curtain is paired with or grouped with another curtain.' }, + { name: 'slidePosition', type: 'number', description: 'Current slide position percentage (0–100).' }, + { name: 'battery', type: 'number', description: 'Current battery level (0–100).' }, + ], + }, + }, { eventType: 'changeReport', eventVersion: '1', @@ -539,6 +567,19 @@ export const RESOURCE_CATALOG: ResourceCatalog = { ], }, }, + { + eventType: 'changeReport', + eventVersion: '1', + devicePattern: 'AI Art Frame 2', + context: { + deviceType: 'AI Art Frame Luma', + fields: [ + ...COMMON_WEBHOOK_CONTEXT_FIELDS, + { name: 'displayMode', type: 'number', description: 'Display mode: 0 = Static image; 1 = Slideshow.' }, + { name: 'battery', type: 'number', description: 'Current battery level (0–100).' }, + ], + }, + }, { eventType: 'changeReport', eventVersion: '1', @@ -832,6 +873,22 @@ export const RESOURCE_CATALOG: ResourceCatalog = { ], }, }, + { + eventType: 'changeReport', + eventVersion: '1', + devicePattern: 'Robot Vacuum K11+ Pro', + context: { + deviceType: 'Robot Vacuum Cleaner K11 Plus Pro', + fields: [ + ...COMMON_WEBHOOK_CONTEXT_FIELDS, + { name: 'workingStatus', type: 'string', description: 'Current working status.' }, + { name: 'onlineStatus', type: 'string', description: 'Connection status: online or offline.' }, + { name: 'battery', type: 'number', description: 'Current battery level (0–100).' }, + { name: 'waterBaseBattery', type: 'number', description: 'Current water base battery level (0–100).' }, + { name: 'taskType', type: 'string', description: 'Current task in progress.' }, + ], + }, + }, { eventType: 'changeReport', eventVersion: '1', @@ -1118,6 +1175,19 @@ export const RESOURCE_CATALOG: ResourceCatalog = { ], }, }, + { + eventType: 'changeReport', + eventVersion: '1', + devicePattern: 'Solar Pan/Tilt Cam 2K', + context: { + deviceType: 'Solar Pan/Tilt Cam 2K', + fields: [ + ...COMMON_WEBHOOK_CONTEXT_FIELDS, + { name: 'battery', type: 'number', description: 'Current battery level (0–100).' }, + { name: 'detectionState', type: 'string', description: 'Motion state; DETECTED is sent when motion is detected and is absent from battery-only events.' }, + ], + }, + }, { eventType: 'changeReport', eventVersion: '1', diff --git a/src/index.ts b/src/index.ts index dea2e64c..420f8a00 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,7 +3,7 @@ import chalk from 'chalk'; import { emitJsonError, isJsonMode, printJson } from './utils/output.js'; import { commandToJson, resolveTargetCommand } from './utils/help-json.js'; import { buildProgram } from './program-builder.js'; -import { primeCredentials } from './credentials/prime.js'; +import { KeychainCredentialsUnavailableError, primeCredentials } from './credentials/prime.js'; import { getActiveProfile } from './lib/request-context.js'; // Early initialization: check for --no-color flag or NO_COLOR env var and disable chalk. @@ -14,12 +14,14 @@ if (process.argv.includes('--no-color') || Boolean(process.env.NO_COLOR)) { const program = buildProgram(); -// Prime keychain-stored credentials before any command runs. This is a -// best-effort probe: failures are silently swallowed inside primeCredentials, -// so the existing file-based path remains the safety net. We probe once per -// invocation (even for --help and --version, which is harmless). +// Offline and credential-repair commands must remain usable if a replacement +// keychain is locked; actual credential consumers still fail closed. program.hook('preAction', async () => { - await primeCredentials(getActiveProfile() ?? 'default'); + try { + await primeCredentials(getActiveProfile() ?? 'default'); + } catch (error) { + if (!(error instanceof KeychainCredentialsUnavailableError)) throw error; + } }); program.addHelpText('after', ` diff --git a/src/lib/command-preflight.ts b/src/lib/command-preflight.ts index 8a796d3f..83054119 100644 --- a/src/lib/command-preflight.ts +++ b/src/lib/command-preflight.ts @@ -5,6 +5,7 @@ import { validateParameter } from "../devices/param-validator.js"; export type CommandPreflightKind = | "unknown-device" | "unknown-device-type" + | "invalid-command-type" | "read-only-device" | "unknown-command" | "unexpected-parameter" diff --git a/src/lib/devices.ts b/src/lib/devices.ts index 82be29b0..70730293 100644 --- a/src/lib/devices.ts +++ b/src/lib/devices.ts @@ -17,11 +17,13 @@ import { isListCacheFresh, getCachedStatus, setCachedStatus, + type CachedDevice, } from '../devices/cache.js'; import { getCacheMode } from '../utils/flags.js'; import { writeAudit } from '../utils/audit.js'; import { isDryRun } from '../utils/flags.js'; import { getActiveProfile } from '../lib/request-context.js'; +import { assertCredentialScope, readCredentialScope } from '../credentials/scope.js'; export interface Device { deviceId: string; @@ -82,7 +84,7 @@ export class DeviceNotFoundError extends Error { export class CommandValidationError extends Error { constructor( message: string, - public readonly kind: 'read-only-device' | 'unknown-command' | 'unknown-device-type' | 'unexpected-parameter' | 'missing-parameter', + public readonly kind: 'read-only-device' | 'unknown-command' | 'unknown-device-type' | 'invalid-command-type' | 'unexpected-parameter' | 'missing-parameter', public readonly hint?: string ) { super(message); @@ -119,6 +121,7 @@ export async function fetchDeviceList( client?: AxiosInstance, options: { bypassCache?: boolean } = {}, ): Promise { + const scope = readCredentialScope(); // TTL-gated read: when the on-disk cache is younger than the configured // list TTL, skip the API call and synthesize a DeviceListBody from the // metadata cache. @@ -157,12 +160,14 @@ export async function fetchDeviceList( }); } } + assertCredentialScope(scope); return { deviceList, infraredRemoteList }; } } const c = client ?? createClient(); const res = await c.get<{ body: DeviceListBody }>('/v1.1/devices'); - updateCacheFromDeviceList(res.data.body); + assertCredentialScope(scope); + updateCacheFromDeviceList(res.data.body, scope); return res.data.body; } @@ -171,17 +176,22 @@ export async function fetchDeviceStatus( deviceId: string, client?: AxiosInstance ): Promise> { + const scope = readCredentialScope(); const mode = getCacheMode(); if (mode.statusTtlMs > 0) { const cached = getCachedStatus(deviceId, mode.statusTtlMs); - if (cached) return cached; + if (cached) { + assertCredentialScope(scope); + return cached; + } } const c = client ?? createClient(); const res = await c.get<{ body: Record }>( `/v1.1/devices/${deviceId}/status` ); + assertCredentialScope(scope); if (mode.statusTtlMs > 0) { - setCachedStatus(deviceId, res.data.body, new Date(), mode.statusTtlMs); + setCachedStatus(deviceId, res.data.body, new Date(), mode.statusTtlMs, scope); } return res.data.body; } @@ -316,10 +326,30 @@ export function validateCommand( parameter: string | undefined, commandType: string ): { ok: true; normalized?: string; caseNormalizedFrom?: string } | { ok: false; error: CommandValidationError } { - if (commandType === 'customize') return { ok: true }; - const cached = getCachedDevice(deviceId); if (!cached) return { ok: true }; + return validateCommandForDevice(deviceId, cached, cmd, parameter, commandType); +} + +/** Validate a command against an explicit inventory entry without touching the cache. */ +export function validateCommandForDevice( + deviceId: string, + cached: CachedDevice, + cmd: string, + parameter: string | undefined, + commandType: string, +): { ok: true; normalized?: string; caseNormalizedFrom?: string } | { ok: false; error: CommandValidationError } { + if (commandType === 'customize') { + if (cached.category === 'ir') return { ok: true }; + return { + ok: false, + error: new CommandValidationError( + `Custom commands are only supported for infrared remotes; ${cached.name} is a physical device.`, + 'invalid-command-type', + 'Use the built-in command type for this device.', + ), + }; + } const match = findCatalogEntry(cached.type); if (!match || Array.isArray(match)) { diff --git a/src/lib/idempotency.ts b/src/lib/idempotency.ts index 8096c028..d830a209 100644 --- a/src/lib/idempotency.ts +++ b/src/lib/idempotency.ts @@ -16,6 +16,7 @@ */ import crypto from 'node:crypto'; +import { readCredentialScope } from '../credentials/scope.js'; const DEFAULT_TTL_MS = 60000; // 60 seconds const DEFAULT_MAX_ENTRIES = 1024; @@ -81,6 +82,8 @@ export class IdempotencyCache { private cache = new Map(); private readonly ttlMs: number; private readonly maxEntries: number; + private generation = 0; + private profileGenerations = new Map(); constructor(ttlMs?: number, maxEntries?: number) { this.ttlMs = ttlMs ?? DEFAULT_TTL_MS; @@ -95,11 +98,10 @@ export class IdempotencyCache { * request fingerprint; mismatched shape raises * {@link IdempotencyConflictError}. * - * `profile` tags the entry so {@link clearForProfile} can evict only the - * entries belonging to a specific credential profile. Callers that omit - * `profile` store in an unscoped bucket — those entries survive - * {@link clearForProfile} by design; always pass the active profile for - * any call that should be evicted on credential rotation. + * `profile` resolves the credential storage scope and revision, isolating + * results across account replacements and explicit config directories. + * Callers that omit `profile` retain an unscoped bucket, which survives + * {@link clearForProfile} by design. * * Returns a tuple-esque object with `replayed: true` when the cached * result is served. The `result` field is the original cached value. @@ -115,10 +117,11 @@ export class IdempotencyCache { return { result, replayed: false }; } - // Use NUL-separated encoding to prevent collisions when a profile name - // contains ':' (e.g. profile="abc:123", key="def" must not hash the same - // as profile="abc", key="123:def"). - const hashed = hashKey(profile ? `${profile}\x00${key}` : key); + const scope = profile === undefined ? undefined : readCredentialScope(profile); + // NUL separators prevent ambiguous scope/revision/key concatenations. + const hashed = hashKey(scope ? `${scope.key}\x00${scope.revision}\x00${key}` : key); + const generation = this.generation; + const profileGeneration = profile === undefined ? 0 : this.profileGenerations.get(profile) ?? 0; const now = Date.now(); const cached = this.cache.get(hashed); const currentShape = shape ? shapeSignature(shape) : '*'; @@ -139,6 +142,18 @@ export class IdempotencyCache { } const result = await fn(); + // The operation already ran: return its outcome, but never retry it or let + // its late completion evict/overwrite entries from a replacement account. + if (generation !== this.generation || + (profile !== undefined && profileGeneration !== (this.profileGenerations.get(profile) ?? 0))) { + return { result, replayed: false }; + } + if (scope) { + const current = readCredentialScope(profile); + if (current.key !== scope.key || current.revision !== scope.revision) { + return { result, replayed: false }; + } + } if (this.cache.size >= this.maxEntries) { const toRemove = Math.ceil(this.maxEntries * 0.1); @@ -162,12 +177,15 @@ export class IdempotencyCache { /** Remove all cached entries that were stored under the given profile. */ clearForProfile(profile: string): void { + this.profileGenerations.set(profile, (this.profileGenerations.get(profile) ?? 0) + 1); for (const [k, v] of this.cache.entries()) { if (v.profile === profile) this.cache.delete(k); } } clear(): void { + this.generation++; + this.profileGenerations.clear(); this.cache.clear(); } diff --git a/src/policy/schema/v0.2.json b/src/policy/schema/v0.2.json index 62651318..12a86d9d 100644 --- a/src/policy/schema/v0.2.json +++ b/src/policy/schema/v0.2.json @@ -39,7 +39,7 @@ "type": "string", "minLength": 1, "not": { - "enum": ["lock", "unlock", "nightLatchUnlock", "createKey", "deleteKey", "deadbolt", "deleteWebhook", "deleteScene", "factoryReset"] + "enum": ["lock", "unlock", "nightLatchUnlock", "createKey", "deleteKey", "deadbolt", "disableMotionDetection", "deleteWebhook", "deleteScene", "factoryReset"] } } } diff --git a/src/policy/validate.ts b/src/policy/validate.ts index ecee3c3a..11f48798 100644 --- a/src/policy/validate.ts +++ b/src/policy/validate.ts @@ -14,9 +14,10 @@ import { type PolicySchemaVersion, } from './schema.js'; import { deriveSafetyTier, findCatalogEntry, getEffectiveCatalog } from '../devices/catalog.js'; +import { validateParameter } from '../devices/param-validator.js'; import { parseRuleCommand } from '../rules/action.js'; import { destructiveVerbOf, DESTRUCTIVE_COMMANDS } from '../rules/destructive.js'; -import type { DeviceListBody } from '../lib/devices.js'; +import { validateCommandForDevice, type DeviceListBody } from '../lib/devices.js'; type Ajv2020Type = InstanceType; type ValidateFn = ReturnType; @@ -415,7 +416,7 @@ function collectOfflineSemanticErrors( getEffectiveCatalog() .flatMap((entry) => entry.commands) .filter((spec) => spec.commandType !== 'customize') - .map((spec) => spec.command), + .map((spec) => spec.command.toLowerCase()), ); const rules = data?.automation?.rules; @@ -483,7 +484,7 @@ function collectOfflineSemanticErrors( continue; } - if (!knownDeviceCommands.has(parsed.verb)) { + if (!knownDeviceCommands.has(parsed.verb.toLowerCase())) { const { line, col } = locateInstancePath(loaded.doc, loaded.lineCounter, commandPath); out.push({ path: commandPath, @@ -554,12 +555,12 @@ export function validateLoadedPolicyAgainstInventory( const base = validateLoadedPolicy(loaded); const errors = [...base.errors]; const aliases = collectAliasMap(loaded.data); - const inventoryById = new Map(); + const inventoryById = new Map(); for (const device of inventory.deviceList) { - inventoryById.set(device.deviceId, { typeName: device.deviceType ?? '' }); + inventoryById.set(device.deviceId, { typeName: device.deviceType || device.controlType || '', name: device.deviceName, category: 'physical' }); } for (const remote of inventory.infraredRemoteList) { - inventoryById.set(remote.deviceId, { typeName: remote.remoteType }); + inventoryById.set(remote.deviceId, { typeName: remote.remoteType, name: remote.deviceName, category: 'ir' }); } for (const [aliasName, deviceId] of Object.entries(aliases)) { @@ -664,21 +665,48 @@ export function validateLoadedPolicyAgainstInventory( continue; } - // Only reached once the target device is resolved in the live - // inventory, so `target.typeName` came straight from the live API - // and is a canonical catalog key — `findCatalogEntry` almost always - // returns the exact entry. The `Array.isArray` branch would only - // fire if the live API ever returns a type that substring-matches - // multiple catalog rows (catalog drift / new upstream type). When - // that happens we'd rather stay silent than emit a false - // `rule-live-unsupported-command` against an ambiguous match — - // verb-support for the unknown type is simply not checkable here. const match = target.typeName ? findCatalogEntry(target.typeName) : null; const entry = !match || Array.isArray(match) ? null : match; - if (!entry) continue; - const spec = entry.commands.find((command) => command.commandType !== 'customize' && command.command === parsed.verb); + if (!entry) { + const { line, col } = locateInstancePath(loaded.doc, loaded.lineCounter, commandPath); + errors.push({ + path: commandPath, + line, + col, + keyword: 'rule-live-unknown-device-type', + message: `rule "${ruleName}" action #${ai} cannot validate device type "${target.typeName}"`, + hint: 'refresh the inventory and verify that this CLI supports the target device type', + schemaPath: '#/properties/automation/properties/rules/items/properties/then/items/properties/command', + }); + continue; + } + const spec = entry.commands.find((command) => command.commandType !== 'customize' && command.command.toLowerCase() === parsed.verb.toLowerCase()); const destructive = spec !== undefined && deriveSafetyTier(spec, entry) === 'destructive'; - if (spec && !destructive) continue; + if (spec && !destructive) { + const command = validateCommandForDevice( + effectiveDeviceId, + { type: target.typeName, name: target.name, category: target.category }, + parsed.verb, + parsed.rawParameter, + 'command', + ); + const parameter = command.ok + ? validateParameter(target.typeName, spec.command, parsed.rawParameter) + : { ok: false as const, error: command.error.message }; + if (!parameter.ok) { + const { line, col } = locateInstancePath(loaded.doc, loaded.lineCounter, commandPath); + errors.push({ + path: commandPath, + line, + col, + keyword: 'rule-live-invalid-parameter', + message: `rule "${ruleName}" action #${ai}: ${parameter.error}`, + hint: 'correct the command parameter for the resolved device type', + schemaPath: '#/properties/automation/properties/rules/items/properties/then/items/properties/command', + }); + } + continue; + } const { line, col } = locateInstancePath(loaded.doc, loaded.lineCounter, commandPath); errors.push({ diff --git a/src/rules/action.ts b/src/rules/action.ts index 9f52ac90..68eb4171 100644 --- a/src/rules/action.ts +++ b/src/rules/action.ts @@ -19,7 +19,9 @@ import type { AxiosInstance } from 'axios'; import { executeCommand, fetchDeviceList } from '../lib/devices.js'; +import { preflightCommandTargets } from '../lib/command-preflight.js'; import { getCachedDevice } from '../devices/cache.js'; +import { parseParameterForWire } from '../devices/param-validator.js'; import { deriveSafetyTier, findCatalogEntry } from '../devices/catalog.js'; import { writeAudit } from '../utils/audit.js'; import { isDestructiveCommand } from './destructive.js'; @@ -57,10 +59,10 @@ export interface RuleActionResult { interface ParsedCommand { deviceIdSlot: string | null; // literal deviceId or "" placeholder verb: string; - parameterTokens: string[]; + rawParameter: string | undefined; } -const DEVICES_COMMAND_RE = /^devices\s+command\s+(\S+)\s+(\S+)(?:\s+(.*))?$/; +const DEVICES_COMMAND_RE = /^devices\s+command\s+(\S+)\s+(\S+)(?:\s+(.*))?$/s; export function parseRuleCommand(cmd: string): ParsedCommand | null { const m = DEVICES_COMMAND_RE.exec(cmd.trim()); @@ -68,10 +70,15 @@ export function parseRuleCommand(cmd: string): ParsedCommand | null { const deviceIdSlot = m[1]; const verb = m[2]; const rest = (m[3] ?? '').trim(); + // Preserve the original whitespace-separated RGB rule form without + // rewriting JSON or unrelated text parameters. + const parameter = /^(?:setColor|setColorLightRGB)$/i.test(verb) && /^-?\d+\s+-?\d+\s+-?\d+$/.test(rest) + ? rest.replace(/\s+/g, ':') + : rest; return { deviceIdSlot, verb, - parameterTokens: rest.length === 0 ? [] : rest.split(/\s+/), + rawParameter: parameter || undefined, }; } @@ -88,18 +95,6 @@ export function resolveActionDevice( return candidate; } -/** - * Render a parameter for SwitchBot's command API. For the PoC we pass - * the raw token string for single-token args, join with `:` for - * multi-token args (matches the CLI's `devices command` convention), - * and `undefined` when no tokens were supplied (the SDK substitutes - * `'default'`). - */ -function renderParameter(tokens: string[]): unknown { - if (tokens.length === 0) return undefined; - if (tokens.length === 1) return tokens[0]; - return tokens.join(':'); -} export async function executeRuleAction( action: Action, @@ -174,68 +169,77 @@ export async function executeRuleAction( } const dryRun = ctx.globalDryRun === true || ctx.rule.dry_run === true; - const parameter = renderParameter(parsed.parameterTokens); - - if (dryRun) { - writeAudit({ - t: new Date().toISOString(), - kind: 'rule-fire-dry', - deviceId, - command: parsed.verb, - parameter: parameter ?? 'default', - commandType: 'command', - dryRun: true, - result: 'ok', - rule: { - name: ctx.rule.name, - triggerSource: ctx.rule.when.source, - matchedDevice: deviceId, - fireId: ctx.fireId, - }, - }); - return { ok: true, dryRun: true, deviceId, verb: parsed.verb }; - } - - if (ctx.skipApiCall) { - writeAudit({ - t: new Date().toISOString(), - kind: 'rule-fire', - deviceId, - command: parsed.verb, - parameter: parameter ?? 'default', - commandType: 'command', - dryRun: false, - result: 'ok', - rule: { - name: ctx.rule.name, - triggerSource: ctx.rule.when.source, - matchedDevice: deviceId, - fireId: ctx.fireId, - reason: 'api-skipped', - }, - }); - return { ok: true, deviceId, verb: parsed.verb }; - } - + let parameter: unknown; let safetyBlocked = false; try { // A generic verb such as turnOn can be destructive for a particular model. // Resolve inventory before any live mutation; an unknown target is not approval. let device = getCachedDevice(deviceId); - if (!device) { + if (!device && !dryRun && !ctx.skipApiCall) { await fetchDeviceList(ctx.httpClient, { bypassCache: true }); device = getCachedDevice(deviceId); } + if (!device) { + safetyBlocked = true; + throw new Error(`Device ${deviceId} is not in the current profile cache; refresh the inventory first.`); + } const entry = device ? findCatalogEntry(device.type) : null; if (!entry || Array.isArray(entry)) { safetyBlocked = true; throw new Error(`Cannot verify automation safety for device ${deviceId}; no unambiguous catalog entry.`); } + const preflight = preflightCommandTargets([deviceId], parsed.verb, parsed.rawParameter, 'command'); + if (!preflight.ok) { + safetyBlocked = true; + throw new Error(preflight.message); + } + parsed.verb = preflight.command; + parameter = parseParameterForWire(preflight.targets[0].parameter); const spec = entry.commands.find((command) => command.command === parsed.verb); if (!spec || deriveSafetyTier(spec, entry) === 'destructive') { safetyBlocked = true; throw new Error(`Automation refuses ${parsed.verb} for ${entry.type}: ${spec ? 'destructive command' : 'unknown command'}.`); } + if (dryRun) { + writeAudit({ + t: new Date().toISOString(), + kind: 'rule-fire-dry', + deviceId, + command: parsed.verb, + parameter: parameter ?? 'default', + commandType: 'command', + dryRun: true, + result: 'ok', + rule: { + name: ctx.rule.name, + triggerSource: ctx.rule.when.source, + matchedDevice: deviceId, + fireId: ctx.fireId, + }, + }); + return { ok: true, dryRun: true, deviceId, verb: parsed.verb }; + } + + if (ctx.skipApiCall) { + writeAudit({ + t: new Date().toISOString(), + kind: 'rule-fire', + deviceId, + command: parsed.verb, + parameter: parameter ?? 'default', + commandType: 'command', + dryRun: false, + result: 'ok', + rule: { + name: ctx.rule.name, + triggerSource: ctx.rule.when.source, + matchedDevice: deviceId, + fireId: ctx.fireId, + reason: 'api-skipped', + }, + }); + return { ok: true, deviceId, verb: parsed.verb }; + } await executeCommand(deviceId, parsed.verb, parameter, 'command', ctx.httpClient); writeAudit({ t: new Date().toISOString(), @@ -261,7 +265,7 @@ export async function executeRuleAction( kind: 'rule-fire', deviceId, command: parsed.verb, - parameter: parameter ?? 'default', + parameter: parameter ?? parseParameterForWire(parsed.rawParameter), commandType: 'command', dryRun: safetyBlocked, result: 'error', diff --git a/src/rules/destructive.ts b/src/rules/destructive.ts index 5a5131dc..be67278f 100644 --- a/src/rules/destructive.ts +++ b/src/rules/destructive.ts @@ -45,15 +45,12 @@ export function extractVerb(cmd: string): string | null { } export function isDestructiveCommand(cmd: string): boolean { - const verb = extractVerb(cmd); - if (!verb) return false; - return (DESTRUCTIVE_COMMANDS as readonly string[]).includes(verb); + return destructiveVerbOf(cmd) !== null; } export function destructiveVerbOf(cmd: string): DestructiveCommand | null { const verb = extractVerb(cmd); - if (verb && (DESTRUCTIVE_COMMANDS as readonly string[]).includes(verb)) { - return verb as DestructiveCommand; - } - return null; + return verb + ? DESTRUCTIVE_COMMANDS.find((candidate) => candidate.toLowerCase() === verb.toLowerCase()) ?? null + : null; } diff --git a/src/rules/engine.ts b/src/rules/engine.ts index effab91d..7b14feb0 100644 --- a/src/rules/engine.ts +++ b/src/rules/engine.ts @@ -1004,7 +1004,13 @@ export class RulesEngine { const firstAction = rule.then[0]; const firstCmd = firstAction && isCommandAction(firstAction) ? firstAction : null; const parsed = firstCmd ? parseRuleCommand(firstCmd.command) : null; - const verb = parsed?.verb ?? firstCmd?.command; + const rawVerb = parsed?.verb ?? firstCmd?.command; + const normalizedVerb = rawVerb?.toLowerCase(); + const verb = normalizedVerb === 'turnon' + ? 'turnOn' + : normalizedVerb === 'turnoff' + ? 'turnOff' + : rawVerb; if ((verb === 'turnOn' || verb === 'turnOff') && (firstCmd?.device || event.deviceId)) { const targetId = firstCmd?.device ? (this.aliases[firstCmd.device] ?? firstCmd.device) : event.deviceId!; try { diff --git a/tests/api/art-upload-limit-alignment.test.ts b/tests/api/art-upload-limit-alignment.test.ts new file mode 100644 index 00000000..3277b5aa --- /dev/null +++ b/tests/api/art-upload-limit-alignment.test.ts @@ -0,0 +1,131 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import axios, { type AxiosAdapter } from 'axios'; +import { ApiError, createClient } from '../../src/api/client.js'; +import { executeCommand } from '../../src/lib/devices.js'; + +const originalArgv = process.argv; +const originalAdapter = axios.defaults.adapter; + +afterEach(() => { + process.argv = originalArgv; + axios.defaults.adapter = originalAdapter; + vi.unstubAllEnvs(); +}); + +function createTestClient(adapter: AxiosAdapter) { + vi.stubEnv('SWITCHBOT_TOKEN', 'test-only-token'); + vi.stubEnv('SWITCHBOT_SECRET', 'test-only-secret'); + process.argv = ['node', 'switchbot', '--no-quota', '--no-retry']; + axios.defaults.adapter = adapter; + return createClient(); +} + +async function captureApiError(action: () => Promise): Promise { + try { + await action(); + } catch (error) { + expect(error).toBeInstanceOf(ApiError); + return error as ApiError; + } + throw new Error('Expected the request to reject with an ApiError'); +} + +describe('AI Art Frame upload limit alignment', () => { + it('preserves the provider message for an uploadImage quota error', async () => { + const providerMessage = 'Artwork allowance exhausted for this billing period'; + let requestBody: unknown; + const client = createTestClient(async (config) => { + requestBody = JSON.parse(String(config.data)); + return { + status: 200, statusText: 'OK', headers: {}, config, + data: { statusCode: 402, message: providerMessage }, + }; + }); + + const error = await captureApiError(() => executeCommand( + 'ART-LUMA-1', 'uploadImage', { imageUrl: 'https://example.test/art.jpg' }, 'command', client, + )); + + expect(requestBody).toEqual({ + command: 'uploadImage', + parameter: { imageUrl: 'https://example.test/art.jpg' }, + commandType: 'command', + }); + expect(error.code).toBe(402); + expect(error.message).toContain(providerMessage); + expect(error.message).toMatch(/image upload.*(?:quota|limit)/i); + expect(error.retryable).toBe(false); + }); + + it('preserves the 402 code and non-retryable quota semantics for an uploadImage HTTP 200 envelope without a provider message', async () => { + const client = createTestClient(async (config) => ({ + status: 200, + statusText: 'OK', + headers: {}, + config, + data: { statusCode: 402 }, + })); + + const error = await captureApiError(() => client.post( + '/v1.1/devices/ART-LUMA-1/commands', + { + command: 'uploadImage', + parameter: { imageUrl: 'https://example.test/art.jpg' }, + commandType: 'command', + }, + )); + + expect(error.code).toBe(402); + expect(error.message).toBe('Image upload quota reached'); + expect(error.retryable).toBe(false); + expect(error.transient).toBe(false); + }); + + it('does not relabel another endpoint HTTP 200 envelope 402 as an image-upload quota error', async () => { + const providerMessage = 'Subscription payment required'; + const client = createTestClient(async (config) => ({ + status: 200, + statusText: 'OK', + headers: {}, + config, + data: { statusCode: 402, message: providerMessage }, + })); + + const error = await captureApiError(() => client.get('/v1.1/devices')); + + expect(error.code).toBe(402); + expect(error.message).toBe(providerMessage); + expect(error.message).not.toMatch(/image upload quota/i); + }); + + it('does not relabel a genuine HTTP 402 from the uploadImage endpoint as image-upload quota', async () => { + const client = createTestClient(async (config) => { + throw new axios.AxiosError( + 'Payment Required', + 'ERR_BAD_REQUEST', + config, + undefined, + { + status: 402, + statusText: 'Payment Required', + headers: {}, + config, + data: {}, + }, + ); + }); + + const error = await captureApiError(() => client.post( + '/v1.1/devices/ART-LUMA-1/commands', + { + command: 'uploadImage', + parameter: { imageUrl: 'https://example.test/art.jpg' }, + commandType: 'command', + }, + )); + + expect(error.code).toBe(402); + expect(error.message).toBe('HTTP 402: Payment Required'); + expect(error.message).not.toMatch(/image upload quota/i); + }); +}); diff --git a/tests/api/client.test.ts b/tests/api/client.test.ts index 9019eb22..adf051f9 100644 --- a/tests/api/client.test.ts +++ b/tests/api/client.test.ts @@ -1,4 +1,20 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +let isolatedHome: string; +beforeEach(() => { + isolatedHome = fs.mkdtempSync(path.join(os.tmpdir(), 'switchbot-client-')); + vi.spyOn(os, 'homedir').mockReturnValue(isolatedHome); + vi.stubEnv('SWITCHBOT_TOKEN', 'fake-token'); + vi.stubEnv('SWITCHBOT_SECRET', 'fake-secret'); +}); +afterEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + fs.rmSync(isolatedHome, { recursive: true, force: true }); +}); type RequestFn = (config: { headers: Record }) => unknown; type ResponseOkFn = (response: unknown) => unknown; @@ -91,28 +107,12 @@ describe('createClient', () => { createClient(); }); - it('creates an axios instance with the SwitchBot baseURL and a timeout', () => { - expect(axiosMock.default.create).toHaveBeenCalledWith( - expect.objectContaining({ - baseURL: 'https://api.switch-bot.com', - timeout: expect.any(Number), - }) - ); - }); describe('request interceptor', () => { - it('injects auth headers into every outgoing request', () => { - const config = { headers: {} as Record }; - const result = captured.request!(config) as { headers: Record }; - expect(result.headers.Authorization).toBe('fake-token'); - expect(result.headers.sign).toBe('FAKE_SIGN'); - expect(result.headers.nonce).toBe('fake-nonce'); - expect(result.headers.t).toBe('1700000000000'); - }); - it('preserves pre-existing headers (merge, not replace)', () => { + it('preserves pre-existing headers (merge, not replace)', async () => { const config = { headers: { 'X-Custom': 'keep' } as Record }; - const result = captured.request!(config) as { headers: Record }; + const result = await captured.request!(config) as { headers: Record }; expect(result.headers['X-Custom']).toBe('keep'); expect(result.headers.Authorization).toBe('fake-token'); }); @@ -277,26 +277,11 @@ describe('createClient — configurable globals', () => { logSpy.mockRestore(); }); - it('honors --timeout when constructing the instance', () => { - process.argv = ['node', 'cli', 'devices', 'list', '--timeout', '7500']; - createClient(); - expect(axiosMock.default.create).toHaveBeenCalledWith( - expect.objectContaining({ timeout: 7500 }) - ); - }); - it('falls back to 30000ms when --timeout is omitted', () => { - process.argv = ['node', 'cli', 'devices', 'list']; - createClient(); - expect(axiosMock.default.create).toHaveBeenCalledWith( - expect.objectContaining({ timeout: 30_000 }) - ); - }); - - it('with --verbose, logs outgoing requests to stderr', () => { + it('with --verbose, logs outgoing requests to stderr', async () => { process.argv = ['node', 'cli', 'devices', 'list', '--verbose']; createClient(); - captured.request!({ + await captured.request!({ headers: {} as Record, method: 'get', baseURL: 'https://api.switch-bot.com', @@ -308,10 +293,10 @@ describe('createClient — configurable globals', () => { expect(combined).toContain('/v1.1/devices'); }); - it('with --dry-run, short-circuits non-GET requests with a DryRunSignal and logs', () => { + it('with --dry-run, short-circuits non-GET requests with a DryRunSignal and logs', async () => { process.argv = ['node', 'cli', 'devices', 'command', 'ABC', 'turnOn', '--dry-run']; createClient(); - expect(() => + await expect( captured.request!({ headers: {} as Record, method: 'post', @@ -319,7 +304,7 @@ describe('createClient — configurable globals', () => { url: '/v1.1/devices/ABC/commands', data: { command: 'turnOn' }, } as never) - ).toThrow(DryRunSignal); + ).rejects.toThrow(DryRunSignal); const out = writeSpy.mock.calls.map((c) => String(c[0])).join('\n'); expect(out).toContain('[dry-run]'); @@ -327,17 +312,6 @@ describe('createClient — configurable globals', () => { expect(out).toContain('/v1.1/devices/ABC/commands'); }); - it('with --dry-run, GET requests still pass through', () => { - process.argv = ['node', 'cli', 'devices', 'list', '--dry-run']; - createClient(); - const config = { - headers: {} as Record, - method: 'get', - baseURL: 'https://api.switch-bot.com', - url: '/v1.1/devices', - }; - expect(() => captured.request!(config as never)).not.toThrow(); - }); it('re-throws DryRunSignal from the response-error handler without wrapping', () => { process.argv = ['node', 'cli', 'devices', 'list']; @@ -508,7 +482,7 @@ describe('createClient — 429 retry', () => { expect(axiosMock.__instance.request).not.toHaveBeenCalled(); }); - it('records a quota entry on every dispatched request (P8)', () => { + it('records a quota entry on every dispatched request (P8)', async () => { process.argv = ['node', 'cli', 'devices', 'list']; createClient(); const config = { @@ -520,14 +494,14 @@ describe('createClient — 429 retry', () => { // P8: quota is recorded in the request interceptor BEFORE dispatch so // that timeouts, DNS errors, 5xx responses, and aborted calls also // count against the daily cap. - captured.request!(config); + await captured.request!(config); expect(quotaMock.recordRequest).toHaveBeenCalledWith( 'GET', 'https://api.switch-bot.com/v1.1/devices' ); }); - it('records quota even when the request ultimately 5xxs (P8)', () => { + it('records quota even when the request ultimately 5xxs (P8)', async () => { process.argv = ['node', 'cli', 'devices', 'list']; createClient(); const config = { @@ -536,7 +510,7 @@ describe('createClient — 429 retry', () => { url: '/v1.1/devices', headers: {}, }; - captured.request!(config); + await captured.request!(config); expect(quotaMock.recordRequest).toHaveBeenCalledTimes(1); // The response interceptor no longer records — all bookkeeping is in // the request interceptor, so subsequent failure handling must not @@ -553,7 +527,7 @@ describe('createClient — 429 retry', () => { expect(quotaMock.recordRequest).toHaveBeenCalledTimes(1); }); - it('records quota even when the request times out (P8)', () => { + it('records quota even when the request times out (P8)', async () => { process.argv = ['node', 'cli', 'devices', 'list', '--retry-on-5xx', '0']; createClient(); const config = { @@ -562,7 +536,7 @@ describe('createClient — 429 retry', () => { url: '/v1.1/devices', headers: {}, }; - captured.request!(config); + await captured.request!(config); expect(quotaMock.recordRequest).toHaveBeenCalledTimes(1); try { captured.failure!({ @@ -576,7 +550,7 @@ describe('createClient — 429 retry', () => { expect(quotaMock.recordRequest).toHaveBeenCalledTimes(1); }); - it('--no-quota skips quota recording (P8)', () => { + it('--no-quota skips quota recording (P8)', async () => { process.argv = ['node', 'cli', 'devices', 'list', '--no-quota']; createClient(); const config = { @@ -585,7 +559,7 @@ describe('createClient — 429 retry', () => { url: '/v1.1/devices', headers: {}, }; - captured.request!(config); + await captured.request!(config); expect(quotaMock.recordRequest).not.toHaveBeenCalled(); }); }); diff --git a/tests/commands/auth.test.ts b/tests/commands/auth.test.ts index 93d47499..12feedc8 100644 --- a/tests/commands/auth.test.ts +++ b/tests/commands/auth.test.ts @@ -11,6 +11,10 @@ import path from 'node:path'; import { Command } from 'commander'; import { registerAuthCommand } from '../../src/commands/auth.js'; import { expectJsonEnvelopeShape } from '../helpers/contracts.js'; +import { saveConfig } from '../../src/config.js'; +import { getCachedStatus, loadCache, resetListCache, resetStatusCache, setCachedStatus, updateCacheFromDeviceList } from '../../src/devices/cache.js'; +import { __resetPrimedCredentials, getPrimedCredentials, primeCredentials } from '../../src/credentials/prime.js'; +import { idempotencyCache } from '../../src/lib/idempotency.js'; const selectMock = vi.fn(); @@ -90,10 +94,33 @@ function makeStore(overrides: { }; } +const originalArgv = process.argv; +let isolatedHome: string; beforeEach(() => { + isolatedHome = fs.mkdtempSync(path.join(os.tmpdir(), 'switchbot-auth-command-')); + vi.stubEnv('HOME', isolatedHome); + vi.stubEnv('USERPROFILE', isolatedHome); + vi.stubEnv('XDG_CONFIG_HOME', isolatedHome); + vi.stubEnv('SWITCHBOT_TOKEN', ''); + vi.stubEnv('SWITCHBOT_SECRET', ''); + process.argv = ['node', 'switchbot']; + resetListCache(); + resetStatusCache(); + __resetPrimedCredentials(); + idempotencyCache.clear(); selectMock.mockReset(); }); +afterEach(() => { + process.argv = originalArgv; + resetListCache(); + resetStatusCache(); + __resetPrimedCredentials(); + idempotencyCache.clear(); + vi.unstubAllEnvs(); + fs.rmSync(isolatedHome, { recursive: true, force: true }); +}); + describe('auth keychain describe', () => { it('prints backend/tag/writable in human mode', async () => { selectMock.mockResolvedValue(makeStore({ name: 'keychain', writable: true })); @@ -212,24 +239,6 @@ describe('auth keychain set', () => { expect(data.written).toBe(true); }); - it('clears all four caches after writing credentials', async () => { - clearCacheMock.mockReset(); - clearStatusCacheMock.mockReset(); - clearPrimedCredsMock.mockReset(); - idempotencyClearForProfileMock.mockReset(); - - const store = makeStore({ writable: true }); - selectMock.mockResolvedValue(store); - const file = path.join(tmpDir, 'creds.json'); - fs.writeFileSync(file, JSON.stringify({ token: 'tk', secret: 'sk' })); - - const res = await runCli(['auth', 'keychain', 'set', '--stdin-file', file]); - expect(res.exitCode).toBe(0); - expect(clearCacheMock).toHaveBeenCalledOnce(); - expect(clearStatusCacheMock).toHaveBeenCalledOnce(); - expect(clearPrimedCredsMock).toHaveBeenCalledOnce(); - expect(idempotencyClearForProfileMock).toHaveBeenCalledOnce(); - }); }); describe('auth keychain delete', () => { @@ -253,22 +262,6 @@ describe('auth keychain delete', () => { expect(data.deleted).toBe(true); }); - it('clears all four caches after deleting credentials', async () => { - clearCacheMock.mockReset(); - clearStatusCacheMock.mockReset(); - clearPrimedCredsMock.mockReset(); - idempotencyClearForProfileMock.mockReset(); - - const store = makeStore({ writable: true }); - selectMock.mockResolvedValue(store); - - const res = await runCli(['auth', 'keychain', 'delete', '--yes']); - expect(res.exitCode).toBe(0); - expect(clearCacheMock).toHaveBeenCalledOnce(); - expect(clearStatusCacheMock).toHaveBeenCalledOnce(); - expect(clearPrimedCredsMock).toHaveBeenCalledOnce(); - expect(idempotencyClearForProfileMock).toHaveBeenCalledOnce(); - }); }); describe('auth keychain migrate', () => { @@ -437,25 +430,6 @@ describe('auth keychain migrate', () => { } }); - it('clears all four caches after a successful migrate', async () => { - clearCacheMock.mockReset(); - clearStatusCacheMock.mockReset(); - clearPrimedCredsMock.mockReset(); - idempotencyClearForProfileMock.mockReset(); - - const store = makeStore({ writable: true }); - selectMock.mockResolvedValue(store); - const file = path.join(tmpHome, '.switchbot', 'config.json'); - fs.mkdirSync(path.dirname(file), { recursive: true }); - fs.writeFileSync(file, JSON.stringify({ token: 't-mig', secret: 's-mig' })); - - const res = await runCli(['auth', 'keychain', 'migrate']); - expect(res.exitCode).toBe(0); - expect(clearCacheMock).toHaveBeenCalledOnce(); - expect(clearStatusCacheMock).toHaveBeenCalledOnce(); - expect(clearPrimedCredsMock).toHaveBeenCalledOnce(); - expect(idempotencyClearForProfileMock).toHaveBeenCalledOnce(); - }); }); // ── auth login ──────────────────────────────────────────────────────────────── @@ -471,57 +445,11 @@ vi.mock('../../src/auth/verify.js', () => ({ verifyCredentials: (...args: unknown[]) => verifyCredsMock(...args), })); -const clearCacheMock = vi.fn(); -const clearStatusCacheMock = vi.fn(); - -vi.mock('../../src/devices/cache.js', async () => { - const actual = await vi.importActual( - '../../src/devices/cache.js', - ); - return { - ...actual, - clearCache: (...args: unknown[]) => clearCacheMock(...args), - clearStatusCache: (...args: unknown[]) => clearStatusCacheMock(...args), - }; -}); - -const clearPrimedCredsMock = vi.fn(); - -vi.mock('../../src/credentials/prime.js', async () => { - const actual = await vi.importActual( - '../../src/credentials/prime.js', - ); - return { - ...actual, - clearPrimedCredentials: (...args: unknown[]) => clearPrimedCredsMock(...args), - }; -}); - -const idempotencyClearForProfileMock = vi.fn(); - -vi.mock('../../src/lib/idempotency.js', async () => { - const actual = await vi.importActual( - '../../src/lib/idempotency.js', - ); - return { - ...actual, - idempotencyCache: { - clearForProfile: (...args: unknown[]) => idempotencyClearForProfileMock(...args), - clear: vi.fn(), - run: vi.fn(), - size: vi.fn(() => 0), - }, - }; -}); describe('auth login', () => { beforeEach(() => { browserLoginMock.mockReset(); verifyCredsMock.mockReset(); - clearCacheMock.mockReset(); - clearStatusCacheMock.mockReset(); - clearPrimedCredsMock.mockReset(); - idempotencyClearForProfileMock.mockReset(); }); it('saves credentials and exits 0 on success', async () => { @@ -588,28 +516,74 @@ describe('auth login', () => { } }); - it('clears all four caches after successful login', async () => { - browserLoginMock.mockResolvedValue({ token: 'tok-new', secret: 'sec-new' }); +}); + +describe('authentication cache lifecycle', () => { + beforeEach(async () => { + saveConfig('old-token', 'old-secret'); + selectMock.mockResolvedValue(makeStore({ + writable: true, getResult: { token: 'old-token', secret: 'old-secret' }, + })); + updateCacheFromDeviceList({ + deviceList: [{ deviceId: 'OLD', deviceName: 'Old device', deviceType: 'Bot' }], + infraredRemoteList: [], + }); + setCachedStatus('OLD', { power: 'on' }); + await primeCredentials('default'); + await idempotencyCache.run('key', async () => 'old result', undefined, 'default'); + }); + + it.each(['login', 'set', 'delete', 'migrate'])('invalidates old account data after successful %s', async command => { + browserLoginMock.mockResolvedValue({ token: 'new-token', secret: 'new-secret' }); verifyCredsMock.mockResolvedValue({ ok: true }); - const store = makeStore({ writable: true }); - selectMock.mockResolvedValue(store); + const input = path.join(isolatedHome, 'credentials.json'); + fs.writeFileSync(input, JSON.stringify({ token: 'new-token', secret: 'new-secret' })); + const args = command === 'login' ? ['auth', 'login', '--no-open'] + : command === 'set' ? ['auth', 'keychain', 'set', '--stdin-file', input] + : ['auth', 'keychain', command, ...(command === 'delete' ? ['--yes'] : [])]; - const res = await runCli(['auth', 'login', '--no-open']); - expect(res.exitCode).toBe(0); - expect(clearCacheMock).toHaveBeenCalledOnce(); - expect(clearStatusCacheMock).toHaveBeenCalledOnce(); - expect(clearPrimedCredsMock).toHaveBeenCalledOnce(); - expect(idempotencyClearForProfileMock).toHaveBeenCalledOnce(); + expect((await runCli(args)).exitCode).toBe(0); + expect(loadCache()).toBeNull(); + expect(getCachedStatus('OLD', 60_000)).toBeNull(); + expect(getPrimedCredentials('default')).toBeNull(); + expect(await idempotencyCache.run('key', async () => 'new result', undefined, 'default')) + .toEqual({ result: 'new result', replayed: false }); }); - it('does not clear any cache when login fails', async () => { + it('preserves the current account caches when login fails', async () => { browserLoginMock.mockRejectedValue(new Error('user cancelled')); - - const res = await runCli(['auth', 'login', '--no-open']); - expect(res.exitCode).toBe(1); - expect(clearCacheMock).not.toHaveBeenCalled(); - expect(clearStatusCacheMock).not.toHaveBeenCalled(); - expect(clearPrimedCredsMock).not.toHaveBeenCalled(); - expect(idempotencyClearForProfileMock).not.toHaveBeenCalled(); + expect((await runCli(['auth', 'login', '--no-open'])).exitCode).toBe(1); + expect(loadCache()?.devices.OLD.name).toBe('Old device'); + expect(getCachedStatus('OLD', 60_000)).toEqual({ power: 'on' }); + expect(getPrimedCredentials('default')?.token).toBe('old-token'); + expect(await idempotencyCache.run('key', async () => 'unexpected repeat', undefined, 'default')) + .toEqual({ result: 'old result', replayed: true }); + }); + + it('invalidates the modified keychain profile rather than an unrelated --config directory', async () => { + const portable = path.join(isolatedHome, 'portable', 'config.json'); + const defaultArgv = process.argv; + process.argv = [...defaultArgv, '--config', portable]; + updateCacheFromDeviceList({ + deviceList: [{ deviceId: 'PORTABLE', deviceName: 'Portable device', deviceType: 'Bot' }], infraredRemoteList: [], + }); + setCachedStatus('PORTABLE', { power: 'off' }); + await idempotencyCache.run('key', async () => 'portable result', undefined, 'default'); + process.argv = defaultArgv; + const input = path.join(isolatedHome, 'credentials.json'); + fs.writeFileSync(input, JSON.stringify({ token: 'new-token', secret: 'new-secret' })); + + expect((await runCli(['--config', portable, 'auth', 'keychain', 'set', '--stdin-file', input])).exitCode).toBe(0); + expect(loadCache()).toBeNull(); + expect(getCachedStatus('OLD', 60_000)).toBeNull(); + expect(getPrimedCredentials('default')).toBeNull(); + expect(await idempotencyCache.run('key', async () => 'new result', undefined, 'default')) + .toEqual({ result: 'new result', replayed: false }); + + process.argv = [...defaultArgv, '--config', portable]; + expect(loadCache()?.devices.PORTABLE.name).toBe('Portable device'); + expect(getCachedStatus('PORTABLE', 60_000)).toEqual({ power: 'off' }); + expect(await idempotencyCache.run('key', async () => 'unexpected repeat', undefined, 'default')) + .toEqual({ result: 'portable result', replayed: true }); }); }); diff --git a/tests/commands/config.test.ts b/tests/commands/config.test.ts index 8520ed45..922354ac 100644 --- a/tests/commands/config.test.ts +++ b/tests/commands/config.test.ts @@ -19,55 +19,26 @@ const configMock = vi.hoisted(() => ({ vi.mock('../../src/config.js', () => configMock); -// Mocks for onCredentialChange side-effects so we can assert all four -// cache-clear functions are called on credential mutations. -const clearCacheMock = vi.hoisted(() => vi.fn()); -const clearStatusCacheMock = vi.hoisted(() => vi.fn()); - -vi.mock('../../src/devices/cache.js', async () => { - const actual = await vi.importActual( - '../../src/devices/cache.js', - ); - return { - ...actual, - clearCache: (...args: unknown[]) => clearCacheMock(...args), - clearStatusCache: (...args: unknown[]) => clearStatusCacheMock(...args), - }; -}); - -const clearPrimedCredsMock = vi.hoisted(() => vi.fn()); - -vi.mock('../../src/credentials/prime.js', async () => { - const actual = await vi.importActual( - '../../src/credentials/prime.js', - ); - return { - ...actual, - clearPrimedCredentials: (...args: unknown[]) => clearPrimedCredsMock(...args), - }; -}); - -const idempotencyClearForProfileMock = vi.hoisted(() => vi.fn()); - -vi.mock('../../src/lib/idempotency.js', async () => { - const actual = await vi.importActual( - '../../src/lib/idempotency.js', - ); - return { - ...actual, - idempotencyCache: { - clearForProfile: (...args: unknown[]) => idempotencyClearForProfileMock(...args), - clear: vi.fn(), - run: vi.fn(), - size: vi.fn(() => 0), - }, - }; -}); import { registerConfigCommand } from '../../src/commands/config.js'; import { runCli } from '../helpers/cli.js'; import { expectJsonEnvelopeShape } from '../helpers/contracts.js'; +const originalArgv = process.argv; +let isolatedHome: string; +beforeEach(() => { + isolatedHome = fs.mkdtempSync(path.join(os.tmpdir(), 'switchbot-config-command-')); + vi.stubEnv('HOME', isolatedHome); + vi.stubEnv('USERPROFILE', isolatedHome); + vi.stubEnv('XDG_CONFIG_HOME', isolatedHome); + process.argv = ['node', 'switchbot']; +}); +afterEach(() => { + process.argv = originalArgv; + vi.unstubAllEnvs(); + fs.rmSync(isolatedHome, { recursive: true, force: true }); +}); + describe('config command', () => { beforeEach(() => { configMock.saveConfig.mockReset(); @@ -76,10 +47,6 @@ describe('config command', () => { configMock.getConfigSummary.mockReturnValue({ source: 'none' }); configMock.listProfiles.mockReset(); configMock.listProfiles.mockReturnValue([]); - clearCacheMock.mockReset(); - clearStatusCacheMock.mockReset(); - clearPrimedCredsMock.mockReset(); - idempotencyClearForProfileMock.mockReset(); }); describe('set-token', () => { @@ -152,22 +119,6 @@ describe('config command', () => { expect(res.exitCode).toBeNull(); }); - it('clears all four caches after saving credentials', async () => { - const res = await runCli(registerConfigCommand, ['config', 'set-token', 'T', 'S']); - expect(res.exitCode).toBeNull(); - expect(clearCacheMock).toHaveBeenCalledOnce(); - expect(clearStatusCacheMock).toHaveBeenCalledOnce(); - expect(clearPrimedCredsMock).toHaveBeenCalledOnce(); - expect(idempotencyClearForProfileMock).toHaveBeenCalledOnce(); - }); - - it('does not clear caches when set-token fails (missing token)', async () => { - await runCli(registerConfigCommand, ['config', 'set-token']); - expect(clearCacheMock).not.toHaveBeenCalled(); - expect(clearStatusCacheMock).not.toHaveBeenCalled(); - expect(clearPrimedCredsMock).not.toHaveBeenCalled(); - expect(idempotencyClearForProfileMock).not.toHaveBeenCalled(); - }); }); describe('show', () => { diff --git a/tests/commands/devices.test.ts b/tests/commands/devices.test.ts index 338ee186..344bab92 100644 --- a/tests/commands/devices.test.ts +++ b/tests/commands/devices.test.ts @@ -2449,10 +2449,10 @@ describe('devices command', () => { expectPost('turnOn', 'default'); }); - it('skips validation entirely for --type customize (arbitrary IR button names)', async () => { + it('rejects customize commands on cached physical devices', async () => { const res = await runCmd('AnyCustomName', 'extra', '--type', 'customize'); - expect(res.exitCode).toBeNull(); - expectPost('AnyCustomName', 'extra', 'customize'); + expect(res.exitCode).toBe(2); + expect(apiMock.__instance.post).not.toHaveBeenCalled(); }); it('validates against a parameterized command (Color Bulb setBrightness)', async () => { @@ -2530,7 +2530,7 @@ describe('devices command', () => { { deviceId: 'LOCK-PRO-1', deviceName: 'Side Door', deviceType: 'Lock Pro Matter Enabled' }, { deviceId: 'BULB-1', deviceName: 'Lamp', deviceType: 'Color Bulb' }, ], - infraredRemoteList: [], + infraredRemoteList: [{ deviceId: 'IR-LOCK', deviceName: 'Remote', remoteType: 'TV' }], }); }); @@ -2564,18 +2564,13 @@ describe('devices command', () => { expect(res.stderr.join("\n")).toContain(deviceType); }); - it('allows Smart Lock unlock when --yes is passed', async () => { - apiMock.__instance.post.mockResolvedValue({ - data: { statusCode: 100, body: {} }, - }); + it('blocks Smart Lock unlock with --yes under the default profile', async () => { const res = await runCli(registerDevicesCommand, [ 'devices', 'command', LOCK_ID, 'unlock', '--yes', ]); - expect(res.exitCode).toBeNull(); - expect(apiMock.__instance.post).toHaveBeenCalledWith( - `/v1.1/devices/${LOCK_ID}/commands`, - { command: 'unlock', parameter: 'default', commandType: 'command' } - ); + expect(res.exitCode).toBe(2); + expect(res.stderr.join('\n')).toMatch(/direct destructive execution disabled/i); + expect(apiMock.__instance.post).not.toHaveBeenCalled(); }); it('allows --dry-run without --yes (guard yields to dry-run preview)', async () => { @@ -2624,7 +2619,7 @@ describe('devices command', () => { // Even if the button name happens to collide with a destructive command, // customize IR buttons are opaque to the catalog and always allowed. const res = await runCli(registerDevicesCommand, [ - 'devices', 'command', LOCK_ID, 'unlock', '--type', 'customize', + 'devices', 'command', 'IR-LOCK', 'unlock', '--type', 'customize', ]); expect(res.exitCode).toBeNull(); expect(apiMock.__instance.post).toHaveBeenCalledTimes(1); diff --git a/tests/commands/mcp-camera-alignment.test.ts b/tests/commands/mcp-camera-alignment.test.ts new file mode 100644 index 00000000..ba8dcc26 --- /dev/null +++ b/tests/commands/mcp-camera-alignment.test.ts @@ -0,0 +1,124 @@ +import { describe, expect, it, vi } from 'vitest'; +import axios, { type AxiosAdapter } from 'axios'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; +import { type McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; + +const credentialsMock = vi.hoisted(() => ({ + get: vi.fn(async () => ({ token: 'camera-test-token', secret: 'camera-test-secret' })), +})); + +vi.mock('../../src/credentials/keychain.js', () => ({ + selectCredentialStore: async () => credentialsMock, +})); + +const cacheMock = vi.hoisted(() => ({ + devices: new Map(), + getCachedDevice: vi.fn((id: string) => cacheMock.devices.get(id) ?? null), +})); + +vi.mock('../../src/devices/cache.js', () => ({ + getCachedDevice: cacheMock.getCachedDevice, + updateCacheFromDeviceList: vi.fn(), + loadCache: vi.fn(() => null), + clearCache: vi.fn(), + isListCacheFresh: vi.fn(() => false), + listCacheAgeMs: vi.fn(() => null), + getCachedStatus: vi.fn(() => null), + setCachedStatus: vi.fn(), + clearStatusCache: vi.fn(), + loadStatusCache: vi.fn(() => ({ entries: {} })), + describeCache: vi.fn(() => ({ + list: { path: '', exists: false }, + status: { path: '', exists: false, entryCount: 0 }, + })), +})); + +import { __resetPrimedCredentials } from '../../src/credentials/prime.js'; +import { createSwitchBotMcpServer } from '../../src/commands/mcp.js'; + +async function pair() { + const server = createSwitchBotMcpServer(); + const client = new Client({ name: 'camera-alignment-test', version: '1' }); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]); + return { client, server }; +} + +describe('camera MCP safety alignment', () => { + it('lists send_command, previews Solar camera motion disablement as high risk, and blocks default live execution', async () => { + vi.stubEnv('SWITCHBOT_ALLOW_DIRECT_DESTRUCTIVE', ''); + const originalAdapter = axios.defaults.adapter; + const fakeHttpAdapter: AxiosAdapter = vi.fn(async (config) => ({ + status: 200, + statusText: 'OK', + headers: {}, + config, + data: { statusCode: 100, body: {} }, + })); + axios.defaults.adapter = fakeHttpAdapter; + cacheMock.devices.set('SOLAR-CAM-1', { + type: 'Solar Pan/Tilt Cam 2K', + name: 'Driveway Camera', + category: 'physical', + }); + __resetPrimedCredentials(); + + let client: Client | undefined; + let server: McpServer | undefined; + try { + ({ client, server } = await pair()); + + const tools = await client.listTools(); + expect(tools.tools.some((tool) => tool.name === 'send_command')).toBe(true); + + const preview = await client.callTool({ + name: 'send_command', + arguments: { + deviceId: 'SOLAR-CAM-1', + command: 'disableMotionDetection', + dryRun: true, + }, + }); + expect(preview.isError).toBeFalsy(); + expect(preview.structuredContent).toMatchObject({ + ok: true, + dryRun: true, + riskProfile: { + riskLevel: 'high', + requiresConfirmation: true, + }, + }); + + const live = await client.callTool({ + name: 'send_command', + arguments: { + deviceId: 'SOLAR-CAM-1', + command: 'disableMotionDetection', + confirm: true, + }, + }); + expect(live.isError).toBe(true); + expect(live.structuredContent).toMatchObject({ + error: { + kind: 'guard', + code: 3, + context: { + directExecutionAllowed: false, + requiredWorkflow: 'plan-approval', + }, + }, + }); + expect(fakeHttpAdapter).not.toHaveBeenCalled(); + } finally { + await client?.close(); + await server?.close(); + axios.defaults.adapter = originalAdapter; + cacheMock.devices.clear(); + cacheMock.getCachedDevice.mockClear(); + credentialsMock.get.mockClear(); + vi.unstubAllEnvs(); + __resetPrimedCredentials(); + } + }); +}); diff --git a/tests/commands/mcp-profile-http.test.ts b/tests/commands/mcp-profile-http.test.ts index 910b8d29..9a4cc03b 100644 --- a/tests/commands/mcp-profile-http.test.ts +++ b/tests/commands/mcp-profile-http.test.ts @@ -14,7 +14,12 @@ afterEach(() => { for (const home of homes.splice(0)) rmSync(home, { recursive: true, force: true }); }); -async function startIsolatedMcp(keychainOnly = false): Promise { +async function startIsolatedMcp( + keychainOnly = false, + rotatingProfile?: 'default' | 'work', + accessorRotation = false, + unavailableDefault = false, +): Promise { const home = mkdtempSync(join(tmpdir(), 'switchbot-http-profile-')); homes.push(home); // Run the real CLI HTTP handler. Only listen-port allocation is adapted: @@ -23,6 +28,31 @@ async function startIsolatedMcp(keychainOnly = false): Promise { const http = (await import('node:http')).default; const { syncBuiltinESMExports } = await import('node:module'); const originalCreateServer = http.createServer; + ${rotatingProfile || unavailableDefault ? ` + import { publishCredentialRevision, readCredentialScope } from './src/credentials/scope.ts'; + import { __resetPrimedCredentials } from './src/credentials/prime.ts'; + let acceptingRequests = false; + let rotated = false; + ` : ''} + ${accessorRotation ? ` + import fs from 'node:fs'; + const originalRead = fs.readFileSync.bind(fs); + let revisionReads = 0; + fs.readFileSync = (file, ...args) => { + if (acceptingRequests && !rotated && String(file).endsWith('/.credential-revision') && ++revisionReads === 3) { + rotated = true; + publishCredentialRevision(readCredentialScope('work'), true); + } + return originalRead(file, ...args); + }; + ` : ''} + ${unavailableDefault ? ` + import fs from 'node:fs'; + import path from 'node:path'; + fs.mkdirSync(path.join(process.env.HOME, '.switchbot'), { recursive: true }); + fs.writeFileSync(path.join(process.env.HOME, '.switchbot', 'config.json'), JSON.stringify({ token: 'old-token', secret: 'old-secret' })); + publishCredentialRevision(readCredentialScope('default'), true); + ` : ''} ${keychainOnly ? ` // Simulate the external credential-store boundary, never the HTTP handler. Object.defineProperty(process, 'platform', { value: 'linux' }); @@ -33,7 +63,14 @@ async function startIsolatedMcp(keychainOnly = false): Promise { if (command === 'which' && args[0] === 'secret-tool') output = 'isolated-secret-tool'; if (command === 'secret-tool') { const account = args[args.indexOf('account') + 1]; - output = account === 'work:token' ? 'work-token' : account === 'work:secret' ? 'work-secret' : ''; + ${rotatingProfile && !accessorRotation ? ` + if (acceptingRequests && !rotated && account === ${JSON.stringify(`${rotatingProfile}:token`)}) { + rotated = true; + publishCredentialRevision(readCredentialScope(${JSON.stringify(rotatingProfile)}), true); + } + ` : ''} + output = account === 'work:token' ? 'work-token' : account === 'work:secret' ? 'work-secret' + : ${unavailableDefault ? "''" : "account === 'default:token' ? 'default-token' : account === 'default:secret' ? 'default-secret' : ''"}; } if (output !== undefined) { return originalSpawn(process.execPath, ['-e', 'process.stdout.write(' + JSON.stringify(output) + ')'], options); @@ -51,6 +88,7 @@ async function startIsolatedMcp(keychainOnly = false): Promise { const server = originalCreateServer(...args); const listen = server.listen.bind(server); server.listen = (_port, _host, callback) => listen(0, '127.0.0.1', () => { + ${rotatingProfile ? 'acceptingRequests = true; __resetPrimedCredentials();' : ''} console.log('PROFILE_TEST_PORT=' + server.address().port); if (callback) callback(); }); @@ -59,6 +97,7 @@ async function startIsolatedMcp(keychainOnly = false): Promise { syncBuiltinESMExports(); process.argv = ['node', 'switchbot', ${keychainOnly ? '' : `'--config', ${JSON.stringify(join(home, 'absent.json'))},`} '--no-quota', 'mcp', 'serve', '--port', '1']; process.execArgv = []; + // Delay entrypoint loading until the harness has installed its CLI and HTTP boundaries. await import('./src/index.ts'); `; const child = spawn(process.execPath, ['--import', 'tsx', '--input-type=module', '--eval', source], { @@ -84,6 +123,72 @@ async function startIsolatedMcp(keychainOnly = false): Promise { } describe('HTTP MCP profile validation', () => { + it('survives credential replacement between named-profile priming and validation', async () => { + const port = await startIsolatedMcp(true, 'work', true); + const url = new URL(`http://127.0.0.1:${port}/mcp`); + const headers = { Authorization: 'Bearer isolated-profile-bearer', 'x-switchbot-profile': 'work' }; + const failed = await fetch(url, { + method: 'POST', + headers: { ...headers, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { + protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'accessor-rotation', version: '1' }, + } }), + }); + expect(failed.status).toBe(500); + expect(await failed.json()).toMatchObject({ error: { code: -32603 } }); + const client = new Client({ name: 'accessor-recovery', version: '1' }); + try { + await client.connect(new StreamableHTTPClientTransport(url, { requestInit: { headers } })); + const result = await client.callTool({ name: 'get_device_status', arguments: { deviceId: 'BOT1' } }); + expect(result.structuredContent).toMatchObject({ status: { deviceId: 'BOT1', power: 'ON' } }); + } finally { + await client.close(); + } + }); + + it('serves a valid named profile when the startup profile keychain is unavailable', async () => { + const port = await startIsolatedMcp(true, undefined, false, true); + const client = new Client({ name: 'named-profile-recovery', version: '1' }); + try { + await client.connect(new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${port}/mcp`), { + requestInit: { headers: { Authorization: 'Bearer isolated-profile-bearer', 'x-switchbot-profile': 'work' } }, + })); + const result = await client.callTool({ name: 'get_device_status', arguments: { deviceId: 'BOT1' } }); + expect(result.structuredContent).toMatchObject({ status: { deviceId: 'BOT1', power: 'ON' } }); + } finally { + await client.close(); + } + }); + + it.each(['default', 'work'] as const)('survives credential replacement during %s request priming', async profile => { + const port = await startIsolatedMcp(true, profile); + const url = new URL(`http://127.0.0.1:${port}/mcp`); + const headers = { + Authorization: 'Bearer isolated-profile-bearer', + ...(profile === 'work' ? { 'x-switchbot-profile': 'work' } : {}), + }; + const failed = await fetch(url, { + method: 'POST', + headers: { ...headers, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { + protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'rotation-test', version: '1' }, + } }), + }); + expect(failed.status).toBe(500); + expect(await failed.json()).toMatchObject({ jsonrpc: '2.0', error: { code: -32603 } }); + + const client = new Client({ name: 'rotation-recovery-test', version: '1' }); + try { + await client.connect(new StreamableHTTPClientTransport(url, { requestInit: { headers } })); + const result = await client.callTool({ name: 'get_device_status', arguments: { deviceId: 'BOT1' } }); + expect(result.structuredContent).toMatchObject({ + status: { deviceId: 'BOT1', power: profile === 'work' ? 'ON' : 'OFF' }, + }); + } finally { + await client.close(); + } + }); + it('accepts keychain-only profiles without authorizing unknown profiles', async () => { const port = await startIsolatedMcp(true); const client = new Client({ name: 'keychain-profile-test', version: '1' }); diff --git a/tests/commands/mcp-safety-lifecycle.test.ts b/tests/commands/mcp-safety-lifecycle.test.ts new file mode 100644 index 00000000..97c02091 --- /dev/null +++ b/tests/commands/mcp-safety-lifecycle.test.ts @@ -0,0 +1,221 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import axios from 'axios'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; +import { createSwitchBotMcpServer } from '../../src/commands/mcp.js'; +import { resetListCache, resetStatusCache } from '../../src/devices/cache.js'; +import { idempotencyCache } from '../../src/lib/idempotency.js'; + +const originalArgv = process.argv; +const originalAdapter = axios.defaults.adapter; +let tmp: string; + +beforeEach(() => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'switchbot-mcp-safety-')); + vi.spyOn(os, 'homedir').mockReturnValue(tmp); + vi.stubEnv('SWITCHBOT_TOKEN', 'test-only-token'); + vi.stubEnv('SWITCHBOT_SECRET', 'test-only-secret'); + vi.stubEnv('SWITCHBOT_ALLOW_DIRECT_DESTRUCTIVE', ''); + process.argv = ['node', 'switchbot', '--config', path.join(tmp, 'config.json'), '--no-quota', '--no-retry']; + resetListCache(); + resetStatusCache(); + idempotencyCache.clear(); +}); + +afterEach(() => { + axios.defaults.adapter = originalAdapter; + process.argv = originalArgv; + resetListCache(); + resetStatusCache(); + idempotencyCache.clear(); + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + fs.rmSync(tmp, { recursive: true, force: true }); +}); + +async function connectMcp() { + const server = createSwitchBotMcpServer({ toolProfile: 'all' }); + const client = new Client({ name: 'safety-regression', version: '1.0.0' }); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); + await client.listTools(); + return { server, client }; +} + +describe('MCP resolved device type safety', () => { + it.each([ + ['Solar Pan/Tilt Cam 2K', 'controlType', 'disableMotionDetection'], + ['Smart Lock Ultra Max', 'controlType', 'Unlock'], + ['Smart Lock Ultra Max', 'deviceType', 'UNLOCK'], + ])('blocks %s via %s before and after warming the cache', async (deviceType, typeField, command) => { + let gets = 0; + const posts: unknown[] = []; + axios.defaults.adapter = async (config) => { + if (config.method === 'post') posts.push(JSON.parse(String(config.data))); + if (config.method === 'get') gets++; + return { + status: 200, statusText: 'OK', headers: {}, config, + data: { + statusCode: 100, + body: config.method === 'get' ? { + deviceList: [{ + deviceId: 'TARGET-1', deviceName: 'Target', [typeField]: deviceType, + enableCloudService: true, hubDeviceId: '', + }], + infraredRemoteList: [], + } : {}, + }, + }; + }; + const { client, server } = await connectMcp(); + try { + for (const cacheState of ['cold', 'warm']) { + const response = await client.callTool({ + name: 'send_command', + arguments: { deviceId: 'TARGET-1', command, confirm: false }, + }); + expect(response.isError, cacheState).toBe(true); + expect(response.structuredContent).toMatchObject({ + error: { kind: 'guard', context: { directExecutionAllowed: false, deviceType } }, + }); + } + const preview = await client.callTool({ + name: 'send_command', + arguments: { deviceId: 'TARGET-1', command, dryRun: true }, + }); + expect(preview.structuredContent).toMatchObject({ + ok: true, + riskProfile: { riskLevel: 'high', requiresConfirmation: true }, + }); + expect(gets).toBe(1); + expect(posts).toEqual([]); + } finally { + await client.close(); + await server.close(); + } + }); + + it('still requires confirmation with an explicit direct-execution override', async () => { + vi.stubEnv('SWITCHBOT_ALLOW_DIRECT_DESTRUCTIVE', '1'); + const posts: unknown[] = []; + axios.defaults.adapter = async (config) => { + if (config.method === 'post') posts.push(JSON.parse(String(config.data))); + return { + status: 200, statusText: 'OK', headers: {}, config, + data: { + statusCode: 100, + body: config.method === 'get' ? { + deviceList: [{ + deviceId: 'LOCK-1', deviceName: 'Lock', controlType: 'Smart Lock Ultra Max', + enableCloudService: true, hubDeviceId: '', + }], + infraredRemoteList: [], + } : {}, + }, + }; + }; + const { client, server } = await connectMcp(); + try { + const refused = await client.callTool({ + name: 'send_command', + arguments: { deviceId: 'LOCK-1', command: 'Unlock', confirm: false }, + }); + expect(refused.isError).toBe(true); + expect(posts).toEqual([]); + const confirmed = await client.callTool({ + name: 'send_command', + arguments: { deviceId: 'LOCK-1', command: 'Unlock', confirm: true }, + }); + expect(confirmed.structuredContent).toMatchObject({ + ok: true, command: 'unlock', riskProfile: { riskLevel: 'high' }, + }); + expect(posts).toEqual([{ command: 'unlock', parameter: 'default', commandType: 'command' }]); + } finally { + await client.close(); + await server.close(); + } + }); + + it('keeps genuine IR custom buttons available after a cold lookup', async () => { + const posts: unknown[] = []; + axios.defaults.adapter = async (config) => { + if (config.method === 'post') posts.push(JSON.parse(String(config.data))); + return { + status: 200, statusText: 'OK', headers: {}, config, + data: { + statusCode: 100, + body: config.method === 'get' ? { + deviceList: [], + infraredRemoteList: [{ + deviceId: 'IR-1', deviceName: 'Remote', remoteType: 'Others', hubDeviceId: '', + }], + } : {}, + }, + }; + }; + const { client, server } = await connectMcp(); + try { + const response = await client.callTool({ + name: 'send_command', + arguments: { deviceId: 'IR-1', command: 'Movie mode', commandType: 'customize' }, + }); + expect(response.structuredContent).toMatchObject({ ok: true, verification: { verifiable: false } }); + expect(posts).toEqual([{ command: 'Movie mode', parameter: 'default', commandType: 'customize' }]); + } finally { + await client.close(); + await server.close(); + } + }); +}); + +describe('MCP exclusive output contract', () => { + it.each([ + { name: 'missing required success fields', structuredContent: {}, isError: false }, + { + name: 'mixed success and error fields', + structuredContent: { ok: true, error: { code: 2, kind: 'usage', message: 'invalid input' } }, + isError: true, + }, + { + name: 'incorrectly typed error fields', + structuredContent: { error: { code: '2', kind: 'usage', message: 'invalid input' } }, + isError: true, + }, + ])('rejects $name after SDK discovery', async ({ structuredContent, isError }) => { + const registrations = vi.spyOn(McpServer.prototype, 'registerTool'); + const { client, server } = await connectMcp(); + try { + const index = registrations.mock.calls.findIndex(([name]) => name === 'send_command'); + const registered = registrations.mock.results[index]; + if (registered?.type !== 'return') throw new Error('send_command was not registered'); + registered.value.update({ + callback: async () => ({ + content: [{ type: 'text', text: JSON.stringify(structuredContent) }], + structuredContent, + isError, + }), + }); + const response = client.callTool({ + name: 'send_command', + arguments: { deviceId: 'TARGET-1', command: 'turnOn', dryRun: true }, + }); + if (isError) { + // The SDK validates error payloads against the published JSON Schema. + await expect(response).rejects.toMatchObject({ code: -32602 }); + } else { + // The server validates success payloads before returning them. + const rejected = await response; + expect(rejected.isError).toBe(true); + expect(rejected.structuredContent).toBeUndefined(); + } + } finally { + registrations.mockRestore(); + await client.close(); + await server.close(); + } + }); +}); diff --git a/tests/commands/mcp.test.ts b/tests/commands/mcp.test.ts index 7ecf7bac..5a5e1313 100644 --- a/tests/commands/mcp.test.ts +++ b/tests/commands/mcp.test.ts @@ -168,6 +168,120 @@ describe('mcp server', () => { delete process.env.SWITCHBOT_ALLOW_DIRECT_DESTRUCTIVE; }); + it('validates structured tool errors after SDK discovery', async () => { + cacheMock.map.set('BULB1', { type: 'Color Bulb', name: 'Desk Lamp', category: 'physical' }); + const { server, client } = await pair(); + try { + const discovery = await client.listTools(); + const tool = discovery.tools.find((item) => item.name === 'send_command'); + expect(tool?.outputSchema?.type).toBe('object'); + + const res = await client.callTool({ + name: 'send_command', + arguments: { deviceId: 'BULB1', command: 'setBrightness', parameter: '999', dryRun: true }, + }); + expect(res.isError).toBe(true); + expect(res.structuredContent).toMatchObject({ error: { kind: 'usage', code: 2 } }); + expect(apiMock.__instance.post).not.toHaveBeenCalled(); + } finally { + await client.close(); + await server.close(); + } + }); + + it('previews an RGBICWW strip light effect as an object', async () => { + cacheMock.map.set('LIGHT1', { type: 'RGBICWW Strip Light', name: 'Strip', category: 'physical' }); + const { server, client } = await pair(); + try { + await client.listTools(); + const res = await client.callTool({ + name: 'send_command', + arguments: { deviceId: 'LIGHT1', command: 'setLightEffect', parameter: '{"effectId":25}', dryRun: true }, + }); + expect(res.isError).toBeFalsy(); + expect(res.structuredContent).toMatchObject({ + ok: true, wouldSend: { command: 'setLightEffect', parameter: { effectId: 25 } }, + }); + } finally { + await client.close(); + await server.close(); + } + }); + + it('offers light effects only on the documented existing models', async () => { + const supported = [ + 'Permanent Outdoor Lights', 'RGBIC Neon Rope Light', 'RGBIC Neon Wire Rope Light', + 'RGBICWW Ceiling Light', 'RGBICWW Floor Lamp', 'RGBICWW Strip Light', + ]; + const { server, client } = await pair(); + try { + await client.listTools(); + for (const type of [...supported, 'Color Bulb', 'Ceiling Light']) { + cacheMock.map.set('LIGHT1', { type, name: 'Light', category: 'physical' }); + const res = await client.callTool({ + name: 'send_command', + arguments: { deviceId: 'LIGHT1', command: 'setLightEffect', parameter: { effectId: 0 }, dryRun: true }, + }); + expect(Boolean(res.isError), type).toBe(!supported.includes(type)); + } + } finally { + await client.close(); + await server.close(); + } + }); + + it('previews Light Bars brightness at its zero boundary', async () => { + cacheMock.map.set('BARS1', { type: 'RGBICWW Light Bars', name: 'Bars', category: 'physical' }); + const { server, client } = await pair(); + try { + await client.listTools(); + const res = await client.callTool({ + name: 'send_command', + arguments: { deviceId: 'BARS1', command: 'setBrightness', parameter: '0', dryRun: true }, + }); + expect(res.isError).toBeFalsy(); + expect(res.structuredContent).toMatchObject({ + ok: true, wouldSend: { command: 'setBrightness', parameter: '0' }, + }); + } finally { + await client.close(); + await server.close(); + } + }); + + it('validates and previews Light Bars object commands', async () => { + cacheMock.map.set('BARS1', { type: 'RGBICWW Light Bars', name: 'Bars', category: 'physical' }); + const cases = [ + ['setBrightnessAndTemperature', { brightness: 0, temperature: 2700 }, { brightness: '0', temperature: 2700 }], + ['setMusicColorMode', { colorList: [] }, { colorList: ['256:0:0'] }], + ['setMusicParamMode', { musicMode: 0, musicLevel: 1, sensitivity: 100, controllerMode: 2 }, { musicMode: 0, musicLevel: 0, sensitivity: 1, controllerMode: 0 }], + ['setEffectColorMode', { style: 999, colorList: ['0:255:0'] }, { style: '1', colorList: [] }], + ['setEffectSpeedMode', { speed: 255 }, { speed: 0 }], + ['setSegmentColorMode', { color: '0:0:255', lightIndex: 11 }, { color: '0:0:255', lightIndex: 12 }], + ['setLightEffect', { effectId: 25 }, { effectId: 26 }], + ] as const; + const { server, client } = await pair(); + try { + await client.listTools(); + for (const [command, valid, invalid] of cases) { + const ok = await client.callTool({ + name: 'send_command', + arguments: { deviceId: 'BARS1', command, parameter: JSON.stringify(valid), dryRun: true }, + }); + expect(ok.isError, command).toBeFalsy(); + expect(ok.structuredContent, command).toMatchObject({ wouldSend: { command, parameter: valid } }); + const rejected = await client.callTool({ + name: 'send_command', + arguments: { deviceId: 'BARS1', command, parameter: invalid, dryRun: true }, + }); + expect(rejected.isError, command).toBe(true); + } + } finally { + await client.close(); + await server.close(); + } + }); + it('send_command rejects destructive commands without confirm:true', async () => { cacheMock.map.set('LOCK1', { type: 'Smart Lock', name: 'Front Door', category: 'physical' }); @@ -192,6 +306,20 @@ describe('mcp server', () => { expect(apiMock.__instance.post).not.toHaveBeenCalled(); }); + it('blocks mixed-case destructive commands before sending', async () => { + cacheMock.map.set('LOCK1', { type: 'Smart Lock', name: 'Front Door', category: 'physical' }); + apiMock.__instance.post.mockResolvedValue({ data: { statusCode: 100, body: {} } }); + const { client } = await pair(); + + const res = await client.callTool({ + name: 'send_command', + arguments: { deviceId: 'LOCK1', command: 'Unlock', confirm: false }, + }); + + expect(res.isError).toBe(true); + expect(apiMock.__instance.post).not.toHaveBeenCalled(); + }); + it('send_command rejects direct destructive commands in the default profile even with confirm:true', async () => { cacheMock.map.set('LOCK1', { type: 'Smart Lock', name: 'Front Door', category: 'physical' }); const { client } = await pair(); diff --git a/tests/commands/schema.test.ts b/tests/commands/schema.test.ts index 259e18f7..04eb9d03 100644 --- a/tests/commands/schema.test.ts +++ b/tests/commands/schema.test.ts @@ -100,7 +100,7 @@ describe('schema export', () => { expect(fieldType('WoMeterPlus', 'scale')).toBe('string'); expect(fieldType('MeterPro(CO2)', 'CO2')).toBe('number'); - expect(fieldType('WoPlugEU', 'switchStatus')).toBe('number'); + expect(fieldType('Plug Mini (EU)', 'switchStatus')).toBe('number'); expect(fieldType('WoKeypad', 'eventName')).toBe('string'); expect(fieldType('Video Doorbell', 'press')).toBe('boolean'); }); diff --git a/tests/config.test.ts b/tests/config.test.ts index f98d48b5..44543fd3 100644 --- a/tests/config.test.ts +++ b/tests/config.test.ts @@ -17,7 +17,19 @@ const osMock = vi.hoisted(() => ({ homedir: vi.fn(() => '/fake/home'), })); -vi.mock('node:fs', () => ({ default: fsMock, ...fsMock })); +vi.mock('node:fs', () => ({ + ...fsMock, + default: { + ...fsMock, + readFileSync: (file: string, ...args: unknown[]) => { + // Revision sidecars are absent in this mocked filesystem. + if (String(file).endsWith('/.credential-revision')) { + throw Object.assign(new Error('not found'), { code: 'ENOENT' }); + } + return fsMock.readFileSync(file, ...args); + }, + }, +})); vi.mock('node:os', () => ({ default: osMock, ...osMock })); import { configFilePath, loadConfig, saveConfig, showConfig, listProfiles, tryLoadConfig } from '../src/config.js'; diff --git a/tests/credentials/prime.test.ts b/tests/credentials/prime.test.ts index 392aaf45..1f1e70f8 100644 --- a/tests/credentials/prime.test.ts +++ b/tests/credentials/prime.test.ts @@ -1,4 +1,14 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { EventEmitter, once } from 'node:events'; +import axios from 'axios'; +import { apiCircuitBreaker, createClient } from '../../src/api/client.js'; +import { publishCredentialRevision, readCredentialScope } from '../../src/credentials/scope.js'; +import { createFileBackend } from '../../src/credentials/backends/file.js'; +import { loadConfig, saveConfig, tryLoadConfig } from '../../src/config.js'; import { primeCredentials, getPrimedCredentials, @@ -7,6 +17,9 @@ import { } from '../../src/credentials/prime.js'; const selectMock = vi.fn(); +const originalArgv = process.argv; +const originalAdapter = axios.defaults.adapter; +let home: string; vi.mock('../../src/credentials/keychain.js', async () => { const actual = await vi.importActual( @@ -19,19 +32,123 @@ vi.mock('../../src/credentials/keychain.js', async () => { }); beforeEach(() => { + home = fs.mkdtempSync(path.join(os.tmpdir(), 'switchbot-credential-prime-')); + vi.spyOn(os, 'homedir').mockReturnValue(home); + process.argv = ['node', 'switchbot']; selectMock.mockReset(); vi.stubEnv('SWITCHBOT_TOKEN', undefined); vi.stubEnv('SWITCHBOT_SECRET', undefined); __resetPrimedCredentials(); + apiCircuitBreaker.reset(); }); afterEach(() => { + process.argv = originalArgv; + axios.defaults.adapter = originalAdapter; + apiCircuitBreaker.reset(); __resetPrimedCredentials(); vi.unstubAllEnvs(); vi.useRealTimers(); + vi.restoreAllMocks(); + fs.rmSync(home, { recursive: true, force: true }); }); +function changeAccount(): void { + const envFile = path.join(home, 'account-b.env'); + fs.writeFileSync(envFile, 'SWITCHBOT_TOKEN=account-B\nSWITCHBOT_SECRET=secret-B\n'); + const changed = spawnSync(process.execPath, [ + '--import', 'tsx', 'src/index.ts', '--json', 'config', 'set-token', '--from-env-file', envFile, + ], { + cwd: process.cwd(), + env: { ...process.env, HOME: home, USERPROFILE: home, XDG_CONFIG_HOME: home, PATH: '', SWITCHBOT_TOKEN: '', SWITCHBOT_SECRET: '' }, + encoding: 'utf8', timeout: 20_000, + }); + if (changed.status !== 0) throw new Error(changed.stderr || changed.stdout); +} + describe('primeCredentials', () => { + it('refreshes within the TTL after another process replaces credentials', async () => { + saveConfig('account-A', 'secret-A'); + selectMock.mockResolvedValue(createFileBackend()); + await primeCredentials('default'); + expect(loadConfig().token).toBe('account-A'); + + changeAccount(); + + await primeCredentials('default'); + expect(loadConfig().token).toBe('account-B'); + }); + + it('rejects an obsolete keychain lookup without poisoning the replacement account', async () => { + saveConfig('account-A', 'secret-A'); + const gate = new EventEmitter(); + const entered = once(gate, 'started'); + selectMock.mockResolvedValueOnce({ + ...createFileBackend(), + get: async () => { + const waiting = once(gate, 'release'); + gate.emit('started'); + await waiting; + return { token: 'account-A', secret: 'secret-A' }; + }, + }); + const obsolete = primeCredentials('default').then(() => null, error => error); + await entered; + changeAccount(); + selectMock.mockResolvedValue(createFileBackend()); + const replacement = primeCredentials('default'); + gate.emit('release'); + + expect(await obsolete).toMatchObject({ name: 'CredentialScopeChangedError' }); + await replacement; + expect(loadConfig().token).toBe('account-B'); + }); + + it.each(['throws', 'missing', 'file fallback'])('does not dispatch old file credentials when a replacement keychain %s', async failure => { + saveConfig('account-A', 'secret-A'); + publishCredentialRevision(readCredentialScope(), true); + if (failure === 'throws') selectMock.mockRejectedValue(new Error('keychain locked')); + else if (failure === 'missing') selectMock.mockResolvedValue({ ...createFileBackend(), name: 'keychain', get: async () => null }); + else selectMock.mockResolvedValue(createFileBackend()); + const dispatched: string[] = []; + axios.defaults.adapter = async config => { + const account = String(config.headers.Authorization); + dispatched.push(account); + return { status: 200, statusText: 'OK', headers: {}, config, data: { statusCode: 100, body: { account } } }; + }; + + await expect(createClient().get('/v1.1/devices')).rejects.toThrow(/credential/i); + expect(dispatched).toEqual([]); + selectMock.mockResolvedValue({ + ...createFileBackend(), name: 'keychain', + get: async () => ({ token: 'account-B', secret: 'secret-B' }), + }); + expect((await createClient().get('/v1.1/devices')).data.body).toEqual({ account: 'account-B' }); + expect(dispatched).toEqual(['account-B']); + }); + + it('does not let synchronous credential consumers fall back to an obsolete file after keychain replacement', () => { + saveConfig('account-A', 'secret-A'); + publishCredentialRevision(readCredentialScope(), true); + expect(() => loadConfig()).toThrow(/credential/i); + expect(tryLoadConfig()).toBeNull(); + }); + + it('keeps offline commands and credential repair available when the replacement keychain is unavailable', () => { + saveConfig('account-A', 'secret-A'); + publishCredentialRevision(readCredentialScope(), true); + const offline = spawnSync(process.execPath, ['--import', 'tsx', 'src/index.ts', '--json', 'catalog', 'show', 'Bot'], { + cwd: process.cwd(), + env: { ...process.env, HOME: home, USERPROFILE: home, XDG_CONFIG_HOME: home, PATH: '', SWITCHBOT_TOKEN: '', SWITCHBOT_SECRET: '' }, + encoding: 'utf8', timeout: 20_000, + }); + expect(offline.status, offline.stderr).toBe(0); + expect(JSON.parse(offline.stdout)).toMatchObject({ schemaVersion: expect.any(String), data: expect.anything() }); + + changeAccount(); + expect(loadConfig().token).toBe('account-B'); + }); + it('does not wait for a stalled keychain when complete env credentials are present', async () => { vi.useFakeTimers(); vi.stubEnv('SWITCHBOT_TOKEN', 'env-token'); diff --git a/tests/devices/account-cache-lifecycle.test.ts b/tests/devices/account-cache-lifecycle.test.ts new file mode 100644 index 00000000..29376493 --- /dev/null +++ b/tests/devices/account-cache-lifecycle.test.ts @@ -0,0 +1,267 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { EventEmitter, once } from 'node:events'; +import axios from 'axios'; +import { saveConfig } from '../../src/config.js'; +import { executeCommand, fetchDeviceList, fetchDeviceStatus } from '../../src/lib/devices.js'; +import { loadCache, loadStatusCache, resetListCache, resetStatusCache, setCachedStatus, updateCacheFromDeviceList } from '../../src/devices/cache.js'; +import { __resetPrimedCredentials } from '../../src/credentials/prime.js'; +import { apiCircuitBreaker, createClient } from '../../src/api/client.js'; +import { idempotencyCache } from '../../src/lib/idempotency.js'; + +const originalArgv = process.argv; +const originalAdapter = axios.defaults.adapter; +let home: string; +let configPath: string; + +beforeEach(() => { + home = fs.mkdtempSync(path.join(os.tmpdir(), 'switchbot-account-cache-')); + configPath = path.join(home, 'config.json'); + vi.spyOn(os, 'homedir').mockReturnValue(home); + vi.stubEnv('SWITCHBOT_TOKEN', ''); + vi.stubEnv('SWITCHBOT_SECRET', ''); + vi.stubEnv('PATH', ''); + process.argv = ['node', 'switchbot', '--config', configPath, '--cache', '1h', '--no-quota', '--no-retry']; + resetListCache(); + resetStatusCache(); + __resetPrimedCredentials(); + idempotencyCache.clear(); + apiCircuitBreaker.reset(); +}); + +afterEach(() => { + axios.defaults.adapter = originalAdapter; + process.argv = originalArgv; + resetListCache(); + resetStatusCache(); + __resetPrimedCredentials(); + idempotencyCache.clear(); + apiCircuitBreaker.reset(); + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + fs.rmSync(home, { recursive: true, force: true }); +}); + +function changeAccount(): void { + const envFile = path.join(home, 'account-b.env'); + fs.writeFileSync(envFile, 'SWITCHBOT_TOKEN=account-B\nSWITCHBOT_SECRET=secret-B\n'); + const result = spawnSync(process.execPath, [ + '--import', 'tsx', 'src/index.ts', '--config', configPath, '--json', + 'config', 'set-token', '--from-env-file', envFile, + ], { + cwd: process.cwd(), + env: { ...process.env, HOME: home, USERPROFILE: home, XDG_CONFIG_HOME: home, PATH: '' }, + encoding: 'utf8', timeout: 20_000, + }); + if (result.status !== 0) throw new Error(result.stderr || result.stdout || String(result.error)); +} + +describe('account changes across processes', () => { + it('stops serving the old account inventory and status after an external credential command', async () => { + saveConfig('account-A', 'secret-A'); + const requests: Array<{ url: string | undefined; token: string }> = []; + axios.defaults.adapter = async (config) => { + const token = String(config.headers.Authorization); + requests.push({ url: config.url, token }); + const oldAccount = token === 'account-A'; + const body = config.url === '/v1.1/devices' ? { + deviceList: [{ + deviceId: oldAccount ? 'A-DEVICE' : 'B-DEVICE', deviceName: 'Lamp', deviceType: 'Color Bulb', + hubDeviceId: '', enableCloudService: true, + }], + infraredRemoteList: [], + } : { power: oldAccount ? 'on' : 'off' }; + return { status: 200, statusText: 'OK', headers: {}, config, data: { statusCode: 100, body } }; + }; + expect((await fetchDeviceList()).deviceList.map(device => device.deviceId)).toEqual(['A-DEVICE']); + expect(await fetchDeviceStatus('SHARED-DEVICE')).toEqual({ power: 'on' }); + + changeAccount(); + + expect((await fetchDeviceList()).deviceList.map(device => device.deviceId)).toEqual(['B-DEVICE']); + expect(await fetchDeviceStatus('SHARED-DEVICE')).toEqual({ power: 'off' }); + expect(requests.slice(2)).toEqual([ + { url: '/v1.1/devices', token: 'account-B' }, + { url: '/v1.1/devices/SHARED-DEVICE/status', token: 'account-B' }, + ]); + }); + + it.each(['inventory', 'status', 'uncached status'])('rejects an old-account %s response after credential replacement', async kind => { + saveConfig('account-A', 'secret-A'); + if (kind === 'uncached status') process.argv.push('--no-cache'); + const client = axios.create({ + adapter: async config => { + changeAccount(); + const body = kind === 'inventory' + ? { deviceList: [{ deviceId: 'OLD', deviceName: 'Old account', deviceType: 'Bot' }], infraredRemoteList: [] } + : { power: 'on' }; + return { status: 200, statusText: 'OK', headers: {}, config, data: { body } }; + }, + }); + + const pending = kind === 'inventory' ? fetchDeviceList(client) : fetchDeviceStatus('SHARED', client); + await expect(pending).rejects.toMatchObject({ name: 'CredentialScopeChangedError' }); + resetListCache(); + resetStatusCache(); + expect(loadCache()).toBeNull(); + expect(loadStatusCache()).toEqual({ entries: {} }); + }); + + it('does not replay the previous account command result for the same idempotency key', async () => { + saveConfig('account-A', 'secret-A'); + const dispatched: string[] = []; + axios.defaults.adapter = async config => { + const account = String(config.headers.Authorization); + dispatched.push(account); + return { status: 200, statusText: 'OK', headers: {}, config, data: { statusCode: 100, body: { account } } }; + }; + const command = () => executeCommand('SHARED', 'turnOn', 'default', 'command', undefined, { idempotencyKey: 'same-key' }); + expect(await command()).toEqual({ account: 'account-A' }); + changeAccount(); + expect(await command()).toEqual({ account: 'account-B' }); + expect(await command()).toEqual({ account: 'account-B', replayed: true }); + expect(dispatched).toEqual(['account-A', 'account-B']); + }); + + it('refuses a retained client instead of silently sending its operation to either account', async () => { + saveConfig('account-A', 'secret-A'); + const dispatched: string[] = []; + axios.defaults.adapter = async config => { + dispatched.push(String(config.headers.Authorization)); + return { status: 200, statusText: 'OK', headers: {}, config, data: { statusCode: 100, body: {} } }; + }; + const client = createClient(); + changeAccount(); + await expect(client.post('/v1.1/devices/SHARED/commands', { command: 'turnOn' })) + .rejects.toMatchObject({ name: 'CredentialScopeChangedError' }); + expect(dispatched).toEqual([]); + await createClient().post('/v1.1/devices/SHARED/commands', { command: 'turnOn' }); + expect(dispatched).toEqual(['account-B']); + }); + + it('does not retry a rate-limited POST after the account changes', async () => { + saveConfig('account-A', 'secret-A'); + process.argv = process.argv.filter(arg => arg !== '--no-retry'); + process.argv.push('--retry-on-429', '1'); + const dispatched: string[] = []; + axios.defaults.adapter = async config => { + dispatched.push(String(config.headers.Authorization)); + if (dispatched.length === 1) { + changeAccount(); + throw new axios.AxiosError('Rate limited', 'ERR_BAD_REQUEST', config, undefined, { + status: 429, statusText: 'Too Many Requests', headers: { 'retry-after': '0' }, config, data: {}, + }); + } + return { status: 200, statusText: 'OK', headers: {}, config, data: { statusCode: 100, body: {} } }; + }; + await expect(createClient().post('/v1.1/devices/SHARED/commands', { command: 'turnOn' })) + .rejects.toMatchObject({ name: 'CredentialScopeChangedError' }); + expect(dispatched).toEqual(['account-A']); + }); + + it('does not let an old command completion overwrite the new account replay result', async () => { + saveConfig('account-A', 'secret-A'); + const gate = new EventEmitter(); + const entered = once(gate, 'started'); + const dispatched: string[] = []; + axios.defaults.adapter = async config => { + const account = String(config.headers.Authorization); + dispatched.push(account); + if (account === 'account-A') { + const waiting = once(gate, 'release'); + gate.emit('started'); + await waiting; + } + return { status: 200, statusText: 'OK', headers: {}, config, data: { statusCode: 100, body: { account } } }; + }; + const command = () => executeCommand('SHARED', 'turnOn', 'default', 'command', undefined, { idempotencyKey: 'same-key' }); + const old = command(); + await entered; + changeAccount(); + expect(await command()).toEqual({ account: 'account-B' }); + gate.emit('release'); + expect(await old).toEqual({ account: 'account-A' }); + expect(await command()).toEqual({ account: 'account-B', replayed: true }); + expect(dispatched).toEqual(['account-A', 'account-B']); + }); + + it.each(['inventory', 'status'])('keeps a complete %s snapshot readable during replacement', kind => { + const writeVersion = (version: string) => { + if (kind === 'inventory') updateCacheFromDeviceList({ + deviceList: [{ deviceId: version, deviceName: version, deviceType: 'Bot' }], infraredRemoteList: [], + }); + else setCachedStatus('SHARED', { power: version }); + }; + const readVersion = () => { + resetListCache(); + resetStatusCache(); + return kind === 'inventory' ? loadCache() : loadStatusCache(); + }; + writeVersion('old'); + const previous = structuredClone(readVersion()); + const originalWrite = fs.writeFileSync; + let duringWrite: unknown; + vi.spyOn(fs, 'writeFileSync').mockImplementation((file, data, options) => { + // Hold the writer at a partial document while a cold reader opens the cache. + originalWrite(file, String(data).slice(0, 12), options); + duringWrite = structuredClone(readVersion()); + originalWrite(file, data, typeof options === 'object' ? { ...options, flag: 'w' } : { flag: 'w' }); + }); + writeVersion('new'); + + expect(duringWrite).toEqual(previous); + const committed = readVersion(); + if (kind === 'inventory') expect(committed).toMatchObject({ devices: { new: { name: 'new' } } }); + else expect(committed).toMatchObject({ entries: { SHARED: { body: { power: 'new' } } } }); + }); + + it('ignores old disk snapshots even if a stale writer restores them after rotation', () => { + saveConfig('account-A', 'secret-A'); + updateCacheFromDeviceList({ + deviceList: [{ deviceId: 'OLD', deviceName: 'Old device', deviceType: 'Bot' }], infraredRemoteList: [], + }); + setCachedStatus('OLD', { power: 'on' }); + const files = ['devices.json', 'status.json'].map(name => path.join(home, name)); + const obsolete = files.map(file => fs.readFileSync(file, 'utf8')); + changeAccount(); + files.forEach((file, index) => fs.writeFileSync(file, obsolete[index])); + resetListCache(); + resetStatusCache(); + expect(loadCache()).toBeNull(); + expect(loadStatusCache()).toEqual({ entries: {} }); + }); + + it.each(['initial', 'retry'])('rejects an account replacement during %s request credential resolution', async phase => { + saveConfig('account-A', 'secret-A'); + process.argv = process.argv.filter(arg => arg !== '--no-retry'); + process.argv.push('--retry-on-429', '1'); + let rotateOnRead = phase === 'initial'; + const dispatched: string[] = []; + axios.defaults.adapter = async config => { + dispatched.push(String(config.headers.Authorization)); + if (phase === 'retry' && dispatched.length === 1) { + rotateOnRead = true; + throw new axios.AxiosError('Rate limited', 'ERR_BAD_REQUEST', config, undefined, { + status: 429, statusText: 'Too Many Requests', headers: { 'retry-after': '0' }, config, data: {}, + }); + } + return { status: 200, statusText: 'OK', headers: {}, config, data: { statusCode: 100, body: {} } }; + }; + const client = createClient(); + const originalRead = fs.readFileSync; + vi.spyOn(fs, 'readFileSync').mockImplementation((file, options) => { + if (String(file) === configPath && rotateOnRead) { + rotateOnRead = false; + changeAccount(); + } + return originalRead(file, options); + }); + + await expect(client.post('/v1.1/devices/SHARED/commands', { command: 'turnOn' })) + .rejects.toMatchObject({ name: 'CredentialScopeChangedError' }); + expect(dispatched).toEqual(phase === 'initial' ? [] : ['account-A']); + }); +}); diff --git a/tests/devices/art-frame-object-alignment.test.ts b/tests/devices/art-frame-object-alignment.test.ts new file mode 100644 index 00000000..b84e20de --- /dev/null +++ b/tests/devices/art-frame-object-alignment.test.ts @@ -0,0 +1,139 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import { resetListCache, updateCacheFromDeviceList } from '../../src/devices/cache.js'; +import { findCatalogEntry } from '../../src/devices/catalog.js'; +import { preparePlanTargets } from '../../src/lib/plan-preflight.js'; + +let tmpDir: string; +let originalArgv: string[]; + +beforeEach(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sbcli-art-frame-object-')); + originalArgv = process.argv; + process.argv = ['node', 'switchbot']; + vi.spyOn(os, 'homedir').mockReturnValue(tmpDir); + resetListCache(); +}); + +afterEach(() => { + process.argv = originalArgv; + resetListCache(); + vi.restoreAllMocks(); + fs.rmSync(tmpDir, { recursive: true, force: true }); +}); + +describe('AI Art Frame upload plan preflight', () => { + it('converts JSON-string uploads to wire objects and rejects a null second image source before dispatch', async () => { + updateCacheFromDeviceList({ + deviceList: [ + { + deviceId: 'ART-FRAME', + deviceName: 'Gallery', + deviceType: 'AI Art Frame', + }, + ], + infraredRemoteList: [], + }); + + await expect(preparePlanTargets([ + { + type: 'command', + deviceId: 'ART-FRAME', + command: 'uploadImage', + parameter: '{"imageUrl":"https://example.test/a.jpg"}', + }, + ])).resolves.toEqual({ + ok: true, + commands: [ + { + stepIndex: 0, + deviceId: 'ART-FRAME', + deviceType: 'AI Art Frame', + command: 'uploadImage', + parameter: { imageUrl: 'https://example.test/a.jpg' }, + commandType: 'command', + destructive: false, + }, + ], + }); + + await expect(preparePlanTargets([ + { + type: 'command', + deviceId: 'ART-FRAME', + command: 'uploadImage', + parameter: { imageUrl: 'https://example.test/a.jpg', imageBase64: null }, + }, + ])).resolves.toMatchObject({ + ok: false, + stepIndex: 0, + deviceId: 'ART-FRAME', + kind: 'parameter-validation', + }); + }); + + it('discovers Luma-only online status and prepares bare and JPEG data-URI base64 upload objects', async () => { + updateCacheFromDeviceList({ + deviceList: [ + { + deviceId: 'ART-FRAME-LUMA', + deviceName: 'Luma Gallery', + deviceType: 'AI Art Frame Luma', + }, + ], + infraredRemoteList: [], + }); + + const luma = findCatalogEntry('AI Art Frame Luma'); + const original = findCatalogEntry('AI Art Frame'); + expect(luma).toBeTruthy(); + expect(Array.isArray(luma)).toBe(false); + expect(original).toBeTruthy(); + expect(Array.isArray(original)).toBe(false); + if (!luma || Array.isArray(luma) || !original || Array.isArray(original)) { + throw new Error('AI Art Frame catalog entries are unavailable'); + } + expect(luma.statusFields).toContain('onlineStatus'); + expect(original.statusFields).not.toContain('onlineStatus'); + + await expect(preparePlanTargets([ + { + type: 'command', + deviceId: 'ART-FRAME-LUMA', + command: 'uploadImage', + parameter: { imageBase64: 'QUJDRA==' }, + }, + { + type: 'command', + deviceId: 'ART-FRAME-LUMA', + command: 'uploadImage', + parameter: '{"imageBase64":"data:image/jpeg;base64,/9j/4AAQ"}', + }, + ])).resolves.toEqual({ + ok: true, + commands: [ + { + stepIndex: 0, + deviceId: 'ART-FRAME-LUMA', + deviceType: 'AI Art Frame Luma', + command: 'uploadImage', + parameter: { imageBase64: 'QUJDRA==' }, + commandType: 'command', + destructive: false, + }, + { + stepIndex: 1, + deviceId: 'ART-FRAME-LUMA', + deviceType: 'AI Art Frame Luma', + command: 'uploadImage', + parameter: { imageBase64: 'data:image/jpeg;base64,/9j/4AAQ' }, + commandType: 'command', + destructive: false, + }, + ], + }); + }); +}); diff --git a/tests/devices/cache-scoping.test.ts b/tests/devices/cache-scoping.test.ts index 190e8202..bb7ad754 100644 --- a/tests/devices/cache-scoping.test.ts +++ b/tests/devices/cache-scoping.test.ts @@ -18,6 +18,9 @@ import { updateCacheFromDeviceList, setCachedStatus, resetListCache, + getCachedStatus, + clearCache, + clearStatusCache, resetStatusCache, } from '../../src/devices/cache.js'; import { withRequestContext } from '../../src/lib/request-context.js'; @@ -63,6 +66,21 @@ describe('cache scoping — no profile (legacy path)', () => { const scopedDir = path.join(tmpDir, '.switchbot', 'cache'); expect(fs.existsSync(scopedDir)).toBe(false); }); + + it('shares inventory, status and clearing with explicit default', () => { + updateCacheFromDeviceList(sampleBody); + setCachedStatus('DEV-1', { power: 'on' }); + + withRequestContext({ profile: 'default' }, () => { + expect(loadCache()?.devices['DEV-1']?.name).toBe('Bot'); + expect(getCachedStatus('DEV-1', 60_000)).toEqual({ power: 'on' }); + clearCache(); + clearStatusCache(); + }); + + expect(loadCache()).toBeNull(); + expect(getCachedStatus('DEV-1', 60_000)).toBeNull(); + }); }); // ── b. Named profile → scoped path ────────────────────────────────────────── diff --git a/tests/devices/camera-alignment.test.ts b/tests/devices/camera-alignment.test.ts new file mode 100644 index 00000000..e9a6448d --- /dev/null +++ b/tests/devices/camera-alignment.test.ts @@ -0,0 +1,72 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import { resetListCache, updateCacheFromDeviceList } from '../../src/devices/cache.js'; +import { deriveSafetyTier, findCatalogEntry } from '../../src/devices/catalog.js'; +import { preflightCommandTargets } from '../../src/lib/command-preflight.js'; + +let tmpDir: string; +let originalArgv: string[]; + +beforeEach(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sbcli-camera-alignment-')); + originalArgv = process.argv; + process.argv = ['node', 'switchbot']; + vi.spyOn(os, 'homedir').mockReturnValue(tmpDir); + resetListCache(); +}); + +afterEach(() => { + process.argv = originalArgv; + resetListCache(); + vi.restoreAllMocks(); + fs.rmSync(tmpDir, { recursive: true, force: true }); +}); + +describe('camera capability alignment', () => { + it('supports Solar motion detection controls safely while keeping Outdoor Pan/Tilt Cam 3K read-only', () => { + updateCacheFromDeviceList({ + deviceList: [ + { + deviceId: 'SOLAR-CAMERA', + deviceName: 'Solar camera', + deviceType: 'Solar Pan/Tilt Cam 2K', + }, + { + deviceId: 'OUTDOOR-CAMERA', + deviceName: 'Outdoor camera', + deviceType: 'Outdoor Pan/Tilt Cam 3K', + }, + ], + infraredRemoteList: [], + }); + + const solar = findCatalogEntry('Solar Pan/Tilt Cam 2K'); + expect(solar).toBeTruthy(); + expect(Array.isArray(solar)).toBe(false); + if (!solar || Array.isArray(solar)) throw new Error('Solar camera catalog entry is unavailable'); + + expect(preflightCommandTargets(['SOLAR-CAMERA'], 'enableMotionDetection', undefined, 'command')).toEqual({ + ok: true, + command: 'enableMotionDetection', + targets: [{ deviceId: 'SOLAR-CAMERA', command: 'enableMotionDetection', parameter: undefined }], + }); + const disableMotionDetection = solar.commands.find((command) => command.command === 'disableMotionDetection'); + expect(disableMotionDetection).toBeDefined(); + expect(deriveSafetyTier(disableMotionDetection!, solar)).toBe('destructive'); + + const outdoor = findCatalogEntry('Outdoor Pan/Tilt Cam 3K'); + expect(outdoor).toBeTruthy(); + expect(Array.isArray(outdoor)).toBe(false); + if (!outdoor || Array.isArray(outdoor)) throw new Error('Outdoor camera catalog entry is unavailable'); + expect(outdoor.readOnly).toBe(true); + expect(outdoor.commands).toEqual([]); + expect(preflightCommandTargets(['OUTDOOR-CAMERA'], 'turnOn', undefined, 'command')).toMatchObject({ + ok: false, + deviceId: 'OUTDOOR-CAMERA', + kind: 'read-only-device', + }); + }); +}); diff --git a/tests/devices/curtain-lock-alignment.test.ts b/tests/devices/curtain-lock-alignment.test.ts new file mode 100644 index 00000000..475d3f50 --- /dev/null +++ b/tests/devices/curtain-lock-alignment.test.ts @@ -0,0 +1,80 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import { resetListCache, updateCacheFromDeviceList } from '../../src/devices/cache.js'; +import { deriveSafetyTier, findCatalogEntry } from '../../src/devices/catalog.js'; +import { preflightCommandTargets } from '../../src/lib/command-preflight.js'; + +let tmpDir: string; +let originalArgv: string[]; + +beforeEach(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sbcli-curtain-lock-alignment-')); + originalArgv = process.argv; + process.argv = ['node', 'switchbot']; + vi.spyOn(os, 'homedir').mockReturnValue(tmpDir); + resetListCache(); +}); + +afterEach(() => { + process.argv = originalArgv; + resetListCache(); + vi.restoreAllMocks(); + fs.rmSync(tmpDir, { recursive: true, force: true }); +}); + +describe('Curtain 4 and Lock Ultra Max command preflight', () => { + it('preflights Curtain4 position boundaries and preserves destructive Lock Ultra Max safety after command normalization', () => { + updateCacheFromDeviceList({ + deviceList: [ + { + deviceId: 'CURTAIN-4', + deviceName: 'Curtain 4', + deviceType: 'Curtain4', + }, + { + deviceId: 'LOCK-ULTRA-MAX', + deviceName: 'Front Door', + deviceType: 'Smart Lock Ultra Max', + }, + ], + infraredRemoteList: [], + }); + + for (const parameter of ['0,ff,0', '0,1,50', '0,0,100']) { + expect(preflightCommandTargets(['CURTAIN-4'], 'setPosition', parameter, 'command')).toEqual({ + ok: true, + command: 'setPosition', + targets: [{ deviceId: 'CURTAIN-4', command: 'setPosition', parameter }], + }); + } + + for (const parameter of ['0,1,101', '0,2,50', '0,1']) { + expect(preflightCommandTargets(['CURTAIN-4'], 'setPosition', parameter, 'command')).toMatchObject({ + ok: false, + deviceId: 'CURTAIN-4', + kind: 'param-out-of-range', + }); + } + + expect(preflightCommandTargets(['LOCK-ULTRA-MAX'], 'Unlock', undefined, 'command')).toEqual({ + ok: true, + command: 'unlock', + targets: [{ deviceId: 'LOCK-ULTRA-MAX', command: 'unlock', parameter: undefined }], + }); + + const lock = findCatalogEntry('Smart Lock Ultra Max'); + expect(lock).toBeTruthy(); + expect(Array.isArray(lock)).toBe(false); + if (!lock || Array.isArray(lock)) throw new Error('Lock Ultra Max catalog entry is unavailable'); + + const unlock = lock.commands.find((command) => command.command === 'unlock'); + const deadbolt = lock.commands.find((command) => command.command === 'deadbolt'); + expect(unlock).toBeDefined(); + expect(deadbolt).toBeDefined(); + expect(deriveSafetyTier(unlock!, lock)).toBe('destructive'); + expect(deriveSafetyTier(deadbolt!, lock)).toBe('destructive'); + }); +}); diff --git a/tests/devices/k11-pro-alignment.test.ts b/tests/devices/k11-pro-alignment.test.ts new file mode 100644 index 00000000..d0352740 --- /dev/null +++ b/tests/devices/k11-pro-alignment.test.ts @@ -0,0 +1,126 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import { updateCacheFromDeviceList, resetListCache } from '../../src/devices/cache.js'; +import { preflightCommandTargets } from '../../src/lib/command-preflight.js'; + +let tmpDir: string; +let originalArgv: string[]; + +beforeEach(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sbcli-k11-pro-')); + originalArgv = process.argv; + process.argv = ['node', 'switchbot']; + vi.spyOn(os, 'homedir').mockReturnValue(tmpDir); + resetListCache(); + updateCacheFromDeviceList({ + deviceList: [ + { + deviceId: 'K11-PRO', + deviceName: 'K11+ Pro', + deviceType: 'Robot Vacuum Cleaner K11 Plus Pro', + }, + { + deviceId: 'K11-LEGACY', + deviceName: 'K11+', + deviceType: 'Robot Vacuum Cleaner K11+', + }, + ], + infraredRemoteList: [], + }); +}); + +afterEach(() => { + process.argv = originalArgv; + resetListCache(); + vi.restoreAllMocks(); + fs.rmSync(tmpDir, { recursive: true, force: true }); +}); + +describe('K11+ Pro command preflight', () => { + it('requires a documented changeParam field for K11+ Pro without changing legacy K11 empty-object behavior', () => { + expect(preflightCommandTargets(['K11-PRO'], 'changeParam', '{}', 'command')).toMatchObject({ + ok: false, + deviceId: 'K11-PRO', + kind: 'param-out-of-range', + }); + + expect(preflightCommandTargets(['K11-PRO'], 'changeParam', '{}', 'command')).toMatchObject({ + ok: false, + deviceId: 'K11-PRO', + kind: 'param-out-of-range', + }); + + expect(preflightCommandTargets(['K11-PRO'], 'changeParam', '{"waterLevel":1}', 'command')).toEqual({ + ok: true, + command: 'changeParam', + targets: [{ deviceId: 'K11-PRO', command: 'changeParam', parameter: '{"waterLevel":1}' }], + }); + + expect(preflightCommandTargets(['K11-LEGACY'], 'changeParam', '{}', 'command')).toEqual({ + ok: true, + command: 'changeParam', + targets: [{ deviceId: 'K11-LEGACY', command: 'changeParam', parameter: '{}' }], + }); + }); + + it('accepts only documented changeParam waterLevel boundaries for K11+ Pro', () => { + for (const waterLevel of [1, 2]) { + expect(preflightCommandTargets(['K11-PRO'], 'changeParam', `{"waterLevel":${waterLevel}}`, 'command')).toMatchObject({ + ok: true, + targets: [{ deviceId: 'K11-PRO', command: 'changeParam', parameter: `{"waterLevel":${waterLevel}}` }], + }); + } + + for (const parameter of ['{"waterLevel":0}', '{"waterLevel":3}', '{"unsupported":1}']) { + expect(preflightCommandTargets(['K11-PRO'], 'changeParam', parameter, 'command')).toMatchObject({ + ok: false, + deviceId: 'K11-PRO', + kind: 'param-out-of-range', + }); + } + }); + + it('enforces K11+ Pro setVolume boundaries through command preflight', () => { + for (const volume of [0, 100]) { + expect(preflightCommandTargets(['K11-PRO'], 'setVolume', String(volume), 'command')).toMatchObject({ + ok: true, + targets: [{ deviceId: 'K11-PRO', command: 'setVolume', parameter: String(volume) }], + }); + } + + for (const volume of [-1, 101]) { + expect(preflightCommandTargets(['K11-PRO'], 'setVolume', String(volume), 'command')).toMatchObject({ + ok: false, + deviceId: 'K11-PRO', + kind: 'param-out-of-range', + }); + } + }); + + it('allows K11+ Pro sweep and mop startClean commands but rejects invalid parameters', () => { + for (const parameter of [ + '{"action":"sweep","param":{"fanLevel":1,"times":1}}', + '{"action":"mop","param":{"fanLevel":4,"times":2639999}}', + ]) { + expect(preflightCommandTargets(['K11-PRO'], 'startClean', parameter, 'command')).toMatchObject({ + ok: true, + targets: [{ deviceId: 'K11-PRO', command: 'startClean', parameter }], + }); + } + + for (const parameter of [ + '{"action":"sweep","param":{"fanLevel":0}}', + '{"action":"sweep","param":{"times":0}}', + '{"action":"sweep","param":{"waterLevel":1}}', + ]) { + expect(preflightCommandTargets(['K11-PRO'], 'startClean', parameter, 'command')).toMatchObject({ + ok: false, + deviceId: 'K11-PRO', + kind: 'param-out-of-range', + }); + } + }); +}); diff --git a/tests/devices/light-bars-boundary.test.ts b/tests/devices/light-bars-boundary.test.ts new file mode 100644 index 00000000..4d1f553f --- /dev/null +++ b/tests/devices/light-bars-boundary.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from 'vitest'; + +import { + parseParameterForWire, + validateParameter, +} from '../../src/devices/param-validator.js'; + +function expectValidLightEffect(effectId: number): void { + const result = validateParameter( + 'RGBICWW Light Bars', + 'setLightEffect', + JSON.stringify({ effectId }), + ); + + expect(result.ok).toBe(true); + if (!result.ok) throw new Error(result.error); + expect(parseParameterForWire(result.normalized)).toEqual({ effectId }); +} + +describe('RGBICWW Light Bars parameter boundaries', () => { + it('accepts setLightEffect integer boundaries and preserves their JSON wire values', () => { + expectValidLightEffect(0); + expectValidLightEffect(25); + }); + + it('rejects setLightEffect values outside its JSON integer contract', () => { + for (const parameter of [ + '{"effectId":-1}', + '{"effectId":26}', + '{"effectId":1.5}', + '{"effectId":"1"}', + '{}', + undefined, + '[]', + '{"effectId":', + ]) { + expect(validateParameter('RGBICWW Light Bars', 'setLightEffect', parameter).ok).toBe(false); + } + }); + + it('requires numeric Light Bars object fields while allowing zero brightness', () => { + const valid = validateParameter( + 'RGBICWW Light Bars', + 'setBrightnessAndTemperature', + '{"brightness":0,"temperature":2700}', + ); + expect(valid.ok).toBe(true); + if (!valid.ok) throw new Error(valid.error); + expect(parseParameterForWire(valid.normalized)).toEqual({ brightness: 0, temperature: 2700 }); + + for (const parameter of [ + { brightness: null, temperature: 2700 }, + { brightness: false, temperature: 2700 }, + { brightness: '0', temperature: 2700 }, + { brightness: 0, temperature: null }, + { brightness: 0, temperature: false }, + { brightness: 0, temperature: '2700' }, + ]) { + expect(validateParameter( + 'RGBICWW Light Bars', + 'setBrightnessAndTemperature', + JSON.stringify(parameter), + ).ok).toBe(false); + } + }); +}); diff --git a/tests/devices/webhook-alignment.test.ts b/tests/devices/webhook-alignment.test.ts new file mode 100644 index 00000000..b1aaf7df --- /dev/null +++ b/tests/devices/webhook-alignment.test.ts @@ -0,0 +1,104 @@ +import { describe, expect, it } from 'vitest'; +import { registerSchemaCommand } from '../../src/commands/schema.js'; +import { runCli } from '../helpers/cli.js'; + +describe('webhook resource discovery alignment', () => { + it('discovers the EU Plug webhook context as Plug Mini (EU) with documented event fields', async () => { + const result = await runCli(registerSchemaCommand, ['schema', 'export']); + const data = JSON.parse(result.stdout.join('')) as { + data: { + resources: { + webhooks: { + events: Array<{ + eventType: string; + eventVersion: string; + context: { + deviceType: string; + fields: Array<{ name: string; type: string }>; + }; + }>; + }; + }; + }; + }; + + const event = data.data.resources.webhooks.events.find( + ({ context }) => context.deviceType === 'Plug Mini (EU)', + ); + + expect(event).toMatchObject({ eventType: 'changeReport', eventVersion: '1' }); + expect(event?.context.fields).toEqual(expect.arrayContaining([ + expect.objectContaining({ name: 'deviceMac', type: 'string' }), + expect.objectContaining({ name: 'online', type: 'boolean' }), + expect.objectContaining({ name: 'switchStatus', type: 'number' }), + ])); + }); + it('discovers all five confirmed webhook identities with their documented context fields', async () => { + const result = await runCli(registerSchemaCommand, ['schema', 'export']); + // This test exercises the typed schema command directly through its public CLI output. + const schemaExport = JSON.parse(result.stdout.join('')) as { + data: { + resources: { + webhooks: { + events: Array<{ + eventType: string; + eventVersion: string; + context: { + deviceType: string; + fields: Array<{ name: string; type: string }>; + }; + }>; + }; + }; + }; + }; + const events = schemaExport.data.resources.webhooks.events; + + const expectedFields: Record> = { + WoCurtain4: [ + ['deviceMac', 'string'], + ['calibrate', 'boolean'], + ['group', 'boolean'], + ['slidePosition', 'number'], + ['battery', 'number'], + ['timeOfSample', 'timestamp'], + ], + 'Smart Lock Ultra Max': [ + ['deviceMac', 'string'], + ['lockState', 'string'], + ['battery', 'number'], + ['timeOfSample', 'timestamp'], + ], + 'Robot Vacuum Cleaner K11 Plus Pro': [ + ['deviceMac', 'string'], + ['workingStatus', 'string'], + ['onlineStatus', 'string'], + ['battery', 'number'], + ['waterBaseBattery', 'number'], + ['taskType', 'string'], + ['timeOfSample', 'timestamp'], + ], + 'AI Art Frame Luma': [ + ['deviceMac', 'string'], + ['displayMode', 'number'], + ['battery', 'number'], + ['timeOfSample', 'timestamp'], + ], + 'Solar Pan/Tilt Cam 2K': [ + ['deviceMac', 'string'], + ['battery', 'number'], + ['detectionState', 'string'], + ['timeOfSample', 'timestamp'], + ], + }; + + for (const [deviceType, fields] of Object.entries(expectedFields)) { + const event = events.find(({ context }) => context.deviceType === deviceType); + + expect(event).toMatchObject({ eventType: 'changeReport', eventVersion: '1' }); + expect(event?.context.fields).toEqual(expect.arrayContaining( + fields.map(([name, type]) => expect.objectContaining({ name, type })), + )); + } + }); +}); diff --git a/tests/lib/devices.test.ts b/tests/lib/devices.test.ts index 6adcef4f..b112dc04 100644 --- a/tests/lib/devices.test.ts +++ b/tests/lib/devices.test.ts @@ -37,6 +37,7 @@ vi.mock('../../src/utils/flags.js', () => ({ getCacheMode: flagsMock.getCacheMode, isDryRun: flagsMock.isDryRun, getAuditLog: flagsMock.getAuditLog, + getConfigPath: vi.fn(() => undefined), })); vi.mock('../../src/devices/cache.js', () => ({ @@ -66,6 +67,7 @@ describe('executeCommand audit semantics', () => { beforeEach(() => { tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'sb-devlib-')); + vi.spyOn(os, 'homedir').mockReturnValue(tmp); auditFile = path.join(tmp, 'audit.log'); flagsMock.dryRun = false; flagsMock.auditPath = auditFile; @@ -76,6 +78,7 @@ describe('executeCommand audit semantics', () => { afterEach(() => { flagsMock.auditPath = null; idempotencyCache.clear(); + vi.restoreAllMocks(); fs.rmSync(tmp, { recursive: true, force: true }); }); diff --git a/tests/lib/idempotency.test.ts b/tests/lib/idempotency.test.ts index 1172dcc1..0b454eb8 100644 --- a/tests/lib/idempotency.test.ts +++ b/tests/lib/idempotency.test.ts @@ -1,4 +1,5 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { EventEmitter, once } from 'node:events'; import { IdempotencyCache, IdempotencyConflictError } from '../../src/lib/idempotency.js'; describe('IdempotencyCache', () => { @@ -105,6 +106,23 @@ describe('IdempotencyCache', () => { expect(fn).toHaveBeenCalledTimes(2); }); + it.each(['all', 'profile'])('does not repopulate a cleared %s cache from an in-flight command', async target => { + const cache = new IdempotencyCache(); + const gate = new EventEmitter(); + const waiting = once(gate, 'release'); + const pending = cache.run('key', async () => { + await waiting; + return 'old result'; + }, undefined, 'work'); + if (target === 'all') cache.clear(); + else cache.clearForProfile('work'); + await cache.run('key', async () => 'new result', undefined, 'work'); + gate.emit('release'); + expect(await pending).toEqual({ result: 'old result', replayed: false }); + expect(await cache.run('key', async () => 'unexpected repeat', undefined, 'work')) + .toEqual({ result: 'new result', replayed: true }); + }); + it('clearForProfile() removes only entries tagged with the given profile', async () => { const cache = new IdempotencyCache(60000); const fn = vi.fn().mockResolvedValue('v'); diff --git a/tests/policy/camera-safety-alignment.test.ts b/tests/policy/camera-safety-alignment.test.ts new file mode 100644 index 00000000..ee45f595 --- /dev/null +++ b/tests/policy/camera-safety-alignment.test.ts @@ -0,0 +1,32 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import { loadPolicyFile } from '../../src/policy/load.js'; +import { validateLoadedPolicy } from '../../src/policy/validate.js'; + +describe('Solar Pan/Tilt Cam safety policy', () => { + let tmpDir: string | undefined; + + afterEach(() => { + if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true }); + }); + + it('rejects disableMotionDetection in confirmations.never_confirm', () => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'switchbot-camera-policy-')); + const policyPath = path.join(tmpDir, 'policy.yaml'); + fs.writeFileSync( + policyPath, + ['version: "0.2"', 'confirmations:', ' never_confirm:', ' - disableMotionDetection', ''].join('\n'), + 'utf-8', + ); + + const result = validateLoadedPolicy(loadPolicyFile(policyPath)); + + expect(result.valid).toBe(false); + expect(result.errors).toContainEqual( + expect.objectContaining({ keyword: 'not', path: '/confirmations/never_confirm/0' }), + ); + }); +}); diff --git a/tests/policy/validate.test.ts b/tests/policy/validate.test.ts index 2783d5de..21d06034 100644 --- a/tests/policy/validate.test.ts +++ b/tests/policy/validate.test.ts @@ -670,6 +670,168 @@ describe('policy validator (v0.2)', () => { expect(err!.path).toBe('/automation/rules/0/then/0/command'); }); + it('validates rule parameters against the supplied inventory type', () => { + const loaded = writeAndLoad(tmpDir, [ + 'version: "0.2"', + 'aliases:', + ' vacuum: 01-202407090924-26354212', + 'automation:', + ' rules:', + ' - name: vacuum action', + ' when: { source: mqtt, event: x.y }', + ' then:', + ` - command: 'devices command startClean {"action":"sweep","param":{"fanLevel":999}}'`, + ' device: vacuum', + ].join('\n')); + const result = validateLoadedPolicyAgainstInventory(loaded, { + deviceList: [{ + deviceId: '01-202407090924-26354212', deviceName: 'Vacuum', + deviceType: 'Robot Vacuum Cleaner K11+', enableCloudService: true, hubDeviceId: '', + }], + infraredRemoteList: [], + }); + + expect(result.valid).toBe(false); + expect(result.errors).toContainEqual(expect.objectContaining({ + keyword: 'rule-live-invalid-parameter', path: '/automation/rules/0/then/0/command', + })); + }); + + it('validates both RGB rule formats against live inventory and rejects invalid colors', () => { + const inventory = { + deviceList: [{ + deviceId: '01-202407090924-26354212', deviceName: 'Lamp', + deviceType: 'Color Bulb', enableCloudService: true, hubDeviceId: '', + }], + infraredRemoteList: [], + }; + for (const [color, valid] of [['255 0 0', true], ['255:0:0', true], ['256 0 0', false]] as const) { + const loaded = writeAndLoad(tmpDir, [ + 'version: "0.2"', + 'aliases:', + ' lamp: 01-202407090924-26354212', + 'automation:', + ' rules:', + ' - name: lamp color', + ' when: { source: mqtt, event: x.y }', + ' then:', + ` - command: "devices command setColor ${color}"`, + ' device: lamp', + ].join('\n')); + const result = validateLoadedPolicyAgainstInventory(loaded, inventory); + expect(result.valid, color).toBe(valid); + if (!valid) expect(result.errors).toContainEqual(expect.objectContaining({ keyword: 'rule-live-invalid-parameter' })); + } + }); + + it('rejects parameters for no-argument actions against live inventory', () => { + const loaded = writeAndLoad(tmpDir, [ + 'version: "0.2"', + 'aliases:', + ' lamp: 01-202407090924-26354212', + 'automation:', + ' rules:', + ' - name: lamp action', + ' when: { source: mqtt, event: x.y }', + ' then:', + ' - command: "devices command turnOn unwanted"', + ' device: lamp', + ].join('\n')); + const result = validateLoadedPolicyAgainstInventory(loaded, { + deviceList: [{ + deviceId: '01-202407090924-26354212', deviceName: 'Lamp', + deviceType: 'Color Bulb', enableCloudService: true, hubDeviceId: '', + }], + infraredRemoteList: [], + }); + + expect(result.valid).toBe(false); + expect(result.errors).toContainEqual(expect.objectContaining({ + keyword: 'rule-live-invalid-parameter', path: '/automation/rules/0/then/0/command', + })); + }); + + it('accepts turnOn via controlType when deviceType is missing or empty', () => { + for (const deviceType of [undefined, '']) { + const loaded = writeAndLoad(tmpDir, [ + 'version: "0.2"', + 'aliases:', + ' lamp: 01-202407090924-26354212', + 'automation:', + ' rules:', + ' - name: lamp action', + ' when: { source: mqtt, event: x.y }', + ' then:', + ' - command: "devices command turnOn"', + ' device: lamp', + ].join('\n')); + const result = validateLoadedPolicyAgainstInventory(loaded, { + deviceList: [{ + deviceId: '01-202407090924-26354212', + deviceName: 'Lamp', + ...(deviceType === undefined ? {} : { deviceType }), + controlType: 'Color Bulb', + enableCloudService: true, + hubDeviceId: '', + }], + infraredRemoteList: [], + }); + + expect(result.valid, JSON.stringify(result.errors)).toBe(true); + } + }); + + it('rejects inventory targets whose device type cannot be validated', () => { + const loaded = writeAndLoad(tmpDir, [ + 'version: "0.2"', + 'aliases:', + ' target: 01-202407090924-26354212', + 'automation:', + ' rules:', + ' - name: unknown model', + ' when: { source: mqtt, event: x.y }', + ' then:', + ' - command: "devices command turnOn"', + ' device: target', + ].join('\n')); + const result = validateLoadedPolicyAgainstInventory(loaded, { + deviceList: [{ + deviceId: '01-202407090924-26354212', deviceName: 'Unknown', + deviceType: 'Uncatalogued Model 123', enableCloudService: true, hubDeviceId: '', + }], + infraredRemoteList: [], + }); + + expect(result.valid).toBe(false); + expect(result.errors).toContainEqual(expect.objectContaining({ + keyword: 'rule-live-unknown-device-type', path: '/automation/rules/0/then/0/command', + })); + }); + + it('accepts case-normalized commands for the supplied inventory', () => { + const loaded = writeAndLoad(tmpDir, [ + 'version: "0.2"', + 'aliases:', + ' lamp: 01-202407090924-26354212', + 'automation:', + ' rules:', + ' - name: lamp action', + ' when: { source: mqtt, event: x.y }', + ' then:', + ' - command: "devices command TurnOn"', + ' device: lamp', + ].join('\n')); + const result = validateLoadedPolicyAgainstInventory(loaded, { + deviceList: [{ + deviceId: '01-202407090924-26354212', deviceName: 'Lamp', + deviceType: 'Color Bulb', enableCloudService: true, hubDeviceId: '', + }], + infraredRemoteList: [], + }); + + expect(result.valid).toBe(true); + }); + it.each(['turnOn', 'turnOff'])('rejects garage %s automation after inventory resolves its safety tier', (command) => { const loaded = writeAndLoad(tmpDir, [ 'version: "0.2"', diff --git a/tests/rules/action.test.ts b/tests/rules/action.test.ts index 05a373f4..cb5b31fb 100644 --- a/tests/rules/action.test.ts +++ b/tests/rules/action.test.ts @@ -1,12 +1,11 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import axios from 'axios'; -import { resetListCache } from '../../src/devices/cache.js'; +import { resetListCache, updateCacheFromDeviceList } from '../../src/devices/cache.js'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { executeRuleAction, - parseRuleCommand, resolveActionDevice, extractDeviceIdFromAction, } from '../../src/rules/action.js'; @@ -19,26 +18,6 @@ const baseRule: Rule = { then: [{ command: 'devices command turnOn' }], }; -describe('parseRuleCommand', () => { - it('parses the canonical shape', () => { - expect(parseRuleCommand('devices command FAKE-ID turnOn')).toEqual({ - deviceIdSlot: 'FAKE-ID', - verb: 'turnOn', - parameterTokens: [], - }); - }); - it('captures multi-token parameters', () => { - expect(parseRuleCommand('devices command setMode cool 72')).toEqual({ - deviceIdSlot: '', - verb: 'setMode', - parameterTokens: ['cool', '72'], - }); - }); - it('returns null for shapes we do not understand', () => { - expect(parseRuleCommand('scenes run abc')).toBeNull(); - expect(parseRuleCommand('')).toBeNull(); - }); -}); describe('resolveActionDevice', () => { it('prefers explicit device field over command slot', () => { @@ -93,6 +72,46 @@ describe('executeRuleAction', () => { expect(entries[0].rule?.name).toBe('test rule'); }); + it('rejects a case-normalized lock rule before the device request', async () => { + updateCacheFromDeviceList({ + deviceList: [{ deviceId: 'LOCK-1', deviceName: 'Door', deviceType: 'Smart Lock' }], + infraredRemoteList: [], + }); + const adapter = vi.fn(async (config) => ({ + data: { body: {} }, status: 200, statusText: 'OK', headers: {}, config, + })); + const action = { command: 'devices command LOCK-1 Lock' }; + const result = await executeRuleAction(action, { + rule: { ...baseRule, then: [action] }, fireId: 'lock-case', aliases: {}, + httpClient: axios.create({ adapter }), + }); + + expect(result.blocked).toBe(true); + expect(adapter).not.toHaveBeenCalled(); + expect(readAudit(auditFile).at(-1)?.result).toBe('error'); + }); + + it('blocks Solar camera motion disabling without changing Video Doorbell rules', async () => { + updateCacheFromDeviceList({ + deviceList: [ + { deviceId: 'SOLAR', deviceName: 'Solar camera', deviceType: 'Solar Pan/Tilt Cam 2K' }, + { deviceId: 'DOORBELL', deviceName: 'Doorbell', deviceType: 'Video Doorbell' }, + ], + infraredRemoteList: [], + }); + const solarAction = { command: 'devices command SOLAR disableMotionDetection' }; + const doorbellAction = { command: 'devices command DOORBELL disableMotionDetection' }; + const solar = await executeRuleAction(solarAction, { + rule: { ...baseRule, then: [solarAction], dry_run: true }, fireId: 'solar', aliases: {}, + }); + const doorbell = await executeRuleAction(doorbellAction, { + rule: { ...baseRule, then: [doorbellAction], dry_run: true }, fireId: 'doorbell', aliases: {}, + }); + + expect(solar.blocked).toBe(true); + expect(doorbell).toMatchObject({ ok: true, dryRun: true }); + }); + it.each([ ['Garage Door Opener', 'turnOn', false], ['Garage Door Opener', 'turnOff', false], @@ -121,7 +140,198 @@ describe('executeRuleAction', () => { if (!allowed) expect(readAudit(auditFile).at(-1)?.result).toBe('error'); }); + it('sends spaced JSON rule parameters as an object', async () => { + let posted: Record | undefined; + const client = axios.create({ + adapter: async (config) => { + if (config.method === 'post') posted = JSON.parse(config.data as string); + return { + data: { body: config.method === 'get' ? { + deviceList: [{ deviceId: 'VAC-1', deviceName: 'Vacuum', deviceType: 'Robot Vacuum Cleaner K11+' }], + infraredRemoteList: [], + } : {} }, + status: 200, statusText: 'OK', headers: {}, config, + }; + }, + }); + const action = { + command: 'devices command VAC-1 startClean {"action": "sweep", "param": {"fanLevel": 2, "times": 1}}', + }; + const result = await executeRuleAction(action, { + rule: { ...baseRule, then: [action] }, fireId: 'json-param', aliases: {}, httpClient: client, + }); + + expect(result.ok).toBe(true); + expect(posted?.parameter).toEqual({ action: 'sweep', param: { fanLevel: 2, times: 1 } }); + }); + + it('preserves spaces in JSON strings and unrelated text parameters', async () => { + updateCacheFromDeviceList({ + deviceList: [ + { deviceId: 'FRAME-1', deviceName: 'Frame', deviceType: 'AI Art Frame' }, + { deviceId: 'WEATHER-1', deviceName: 'Weather', deviceType: 'WeatherStation' }, + ], + infraredRemoteList: [], + }); + const parameters: unknown[] = []; + const client = axios.create({ + adapter: async (config) => { + parameters.push(JSON.parse(config.data as string).parameter); + return { data: { body: {} }, status: 200, statusText: 'OK', headers: {}, config }; + }, + }); + const commands = [ + 'devices command FRAME-1 uploadImage {\n "imageUrl": "https://example.test/my art.jpg"\n}', + 'devices command WEATHER-1 customQuote hello home', + ]; + for (const command of commands) { + const action = { command }; + const result = await executeRuleAction(action, { + rule: { ...baseRule, then: [action] }, fireId: command, aliases: {}, httpClient: client, + }); + expect(result.ok, command).toBe(true); + } + expect(parameters).toEqual([{ imageUrl: 'https://example.test/my art.jpg' }, 'hello home']); + }); + + it('sends legacy space-separated and colon-separated RGB rules identically', async () => { + updateCacheFromDeviceList({ + deviceList: [{ deviceId: 'LAMP-1', deviceName: 'Lamp', deviceType: 'Color Bulb' }], + infraredRemoteList: [], + }); + const parameters: unknown[] = []; + const client = axios.create({ + adapter: async (config) => { + parameters.push(JSON.parse(config.data as string).parameter); + return { data: { body: {} }, status: 200, statusText: 'OK', headers: {}, config }; + }, + }); + + for (const color of ['255 0 0', '255:0:0', '255 0\t0']) { + const action = { command: `devices command LAMP-1 setColor ${color}` }; + const result = await executeRuleAction(action, { + rule: { ...baseRule, then: [action] }, fireId: color, aliases: {}, httpClient: client, + }); + expect(result.ok, color).toBe(true); + } + expect(parameters).toEqual(['255:0:0', '255:0:0', '255:0:0']); + }); + + it('preserves space-separated RGB rules for the ceiling color light', async () => { + updateCacheFromDeviceList({ + deviceList: [{ deviceId: 'CEILING-1', deviceName: 'Ceiling', deviceType: 'RGBICWW Ceiling Light' }], + infraredRemoteList: [], + }); + let parameter: unknown; + const client = axios.create({ + adapter: async (config) => { + parameter = JSON.parse(config.data as string).parameter; + return { data: { body: {} }, status: 200, statusText: 'OK', headers: {}, config }; + }, + }); + const action = { command: 'devices command CEILING-1 setColorLightRGB 255 0 0' }; + const result = await executeRuleAction(action, { + rule: { ...baseRule, then: [action] }, fireId: 'ceiling-rgb', aliases: {}, httpClient: client, + }); + + expect(result.ok).toBe(true); + expect(parameter).toBe('255:0:0'); + }); + + it('rejects invalid space-separated RGB rules before sending', async () => { + updateCacheFromDeviceList({ + deviceList: [{ deviceId: 'LAMP-1', deviceName: 'Lamp', deviceType: 'Color Bulb' }], + infraredRemoteList: [], + }); + const adapter = vi.fn(async (config) => ({ + data: { body: {} }, status: 200, statusText: 'OK', headers: {}, config, + })); + const client = axios.create({ adapter }); + for (const color of ['256 0 0', '-1 0 0', '255 0', '255 0 0 0']) { + const action = { command: `devices command LAMP-1 setColor ${color}` }; + const result = await executeRuleAction(action, { + rule: { ...baseRule, then: [action] }, fireId: color, aliases: {}, httpClient: client, + }); + expect(result.ok, color).toBe(false); + } + expect(adapter).not.toHaveBeenCalled(); + }); + + it('rejects out-of-range rule parameters before the device request', async () => { + updateCacheFromDeviceList({ + deviceList: [{ deviceId: 'VAC-1', deviceName: 'Vacuum', deviceType: 'Robot Vacuum Cleaner K11+' }], + infraredRemoteList: [], + }); + const requests: string[] = []; + const client = axios.create({ + adapter: async (config) => { + requests.push(`${config.method} ${config.url}`); + return { data: { body: {} }, status: 200, statusText: 'OK', headers: {}, config }; + }, + }); + const action = { command: 'devices command VAC-1 startClean {"action":"sweep","param":{"fanLevel":999}}' }; + const result = await executeRuleAction(action, { + rule: { ...baseRule, then: [action] }, fireId: 'invalid-param', aliases: {}, httpClient: client, + }); + + expect(result.ok).toBe(false); + expect(requests).toEqual([]); + expect(readAudit(auditFile).at(-1)?.result).toBe('error'); + }); + + it.each([ + { raw: '{"action": "sweep", "param": {"fanLevel": 999}}', expected: { action: 'sweep', param: { fanLevel: 999 } } }, + { raw: '{"action":', expected: '{"action":' }, + ])('preserves the original rule parameter in rejected-action audit records', async ({ raw, expected }) => { + updateCacheFromDeviceList({ + deviceList: [{ deviceId: 'VAC-1', deviceName: 'Vacuum', deviceType: 'Robot Vacuum Cleaner K11+' }], + infraredRemoteList: [], + }); + const action = { command: `devices command VAC-1 startClean ${raw}` }; + const result = await executeRuleAction(action, { + rule: { ...baseRule, then: [action] }, fireId: 'invalid-audit', aliases: {}, skipApiCall: true, + }); + expect(result.ok).toBe(false); + expect(readAudit(auditFile).at(-1)).toMatchObject({ result: 'error', parameter: expected }); + }); + + it('preserves validated JSON in the rule audit when the device request fails', async () => { + updateCacheFromDeviceList({ + deviceList: [{ deviceId: 'VAC-1', deviceName: 'Vacuum', deviceType: 'Robot Vacuum Cleaner K11+' }], + infraredRemoteList: [], + }); + const client = axios.create({ adapter: async () => { throw new Error('device unavailable'); } }); + const action = { command: 'devices command VAC-1 startClean {"action": "sweep", "param": {"fanLevel": 2}}' }; + const result = await executeRuleAction(action, { + rule: { ...baseRule, then: [action] }, fireId: 'failed-audit', aliases: {}, httpClient: client, + }); + expect(result.ok).toBe(false); + expect(readAudit(auditFile).at(-1)).toMatchObject({ + kind: 'rule-fire', result: 'error', parameter: { action: 'sweep', param: { fanLevel: 2 } }, + }); + }); + + it('rejects cold-cache dry-run without any network request', async () => { + const adapter = vi.fn(async (config) => ({ + data: { body: {} }, status: 200, statusText: 'OK', headers: {}, config, + })); + const action = { command: 'devices command MISSING turnOn' }; + const result = await executeRuleAction(action, { + rule: { ...baseRule, then: [action], dry_run: true }, + fireId: 'cold-cache', aliases: {}, httpClient: axios.create({ adapter }), + }); + + expect(result.ok).toBe(false); + expect(result.error).toMatch(/cache|inventory/i); + expect(adapter).not.toHaveBeenCalled(); + expect(readAudit(auditFile).at(-1)?.result).toBe('error'); + }); + it('dry-run records rule-fire-dry and skips the API', async () => { + updateCacheFromDeviceList({ + deviceList: [{ deviceId: 'AA-BB', deviceName: 'Lamp', deviceType: 'Color Bulb' }], + infraredRemoteList: [], + }); const action = { command: 'devices command AA-BB turnOn' }; const result = await executeRuleAction(action, { rule: { ...baseRule, then: [action], dry_run: true }, @@ -138,6 +348,10 @@ describe('executeRuleAction', () => { }); it('resolves aliases before calling executeCommand', async () => { + updateCacheFromDeviceList({ + deviceList: [{ deviceId: 'AA-BB-CC', deviceName: 'Lamp', deviceType: 'Color Bulb' }], + infraredRemoteList: [], + }); const action = { command: 'devices command turnOn', device: 'bedroom light' }; const result = await executeRuleAction(action, { rule: { ...baseRule, then: [action] }, @@ -176,6 +390,10 @@ describe('executeRuleAction', () => { }); it('globalDryRun forces dry-run even when rule.dry_run is false', async () => { + updateCacheFromDeviceList({ + deviceList: [{ deviceId: 'AA-BB', deviceName: 'Lamp', deviceType: 'Color Bulb' }], + infraredRemoteList: [], + }); const action = { command: 'devices command AA-BB turnOff' }; const result = await executeRuleAction(action, { rule: { ...baseRule, then: [action], dry_run: false }, diff --git a/tests/rules/engine.test.ts b/tests/rules/engine.test.ts index 9fff4bfc..665a9c29 100644 --- a/tests/rules/engine.test.ts +++ b/tests/rules/engine.test.ts @@ -9,6 +9,7 @@ import type { AutomationBlock, Rule } from '../../src/rules/types.js'; import { readAudit } from '../../src/utils/audit.js'; import type { SwitchBotMqttClient } from '../../src/mqtt/client.js'; import type { MqttCredential } from '../../src/mqtt/credential.js'; +import { resetListCache, updateCacheFromDeviceList } from '../../src/devices/cache.js'; const fakeCredential: MqttCredential = { brokerUrl: 'ssl://broker.example.com:8883', @@ -19,6 +20,25 @@ const fakeCredential: MqttCredential = { tls: { enabled: true, caBase64: '', certBase64: '', keyBase64: '' }, }; +let cacheHome: string; +beforeEach(() => { + cacheHome = fs.mkdtempSync(path.join(os.tmpdir(), 'sbengine-cache-')); + vi.spyOn(os, 'homedir').mockReturnValue(cacheHome); + resetListCache(); + updateCacheFromDeviceList({ + deviceList: [ + { deviceId: 'AA-BB-CC', deviceName: 'Hallway lamp', deviceType: 'Color Bulb' }, + { deviceId: 'LAMP-ID', deviceName: 'Lamp', deviceType: 'Color Bulb' }, + ], + infraredRemoteList: [], + }); +}); +afterEach(() => { + resetListCache(); + vi.restoreAllMocks(); + fs.rmSync(cacheHome, { recursive: true, force: true }); +}); + class FakeMqttClient extends EventEmitter { private messageHandlers = new Set<(t: string, p: Buffer) => void>(); private stateHandlers = new Set<(s: string) => void>(); @@ -917,6 +937,39 @@ describe('RulesEngine.reload', () => { await engine.stop(); }); + it('suppresses mixed-case TurnOn when cached target status is already on', async () => { + const fires: EngineFireEntry[] = []; + const fetchStatus = vi.fn(async () => ({ power: 'on' })); + const rule: Rule = { + name: 'auto-on', + when: { source: 'mqtt', event: 'motion.detected' }, + conditions: [{ device: 'hallway lamp', field: 'power', op: '==', value: 'on' }], + then: [{ command: 'devices command TurnOn', device: 'hallway lamp' }], + dry_run: true, + suppressIfAlreadyDesired: true, + }; + const engine = new RulesEngine({ + automation: automation([rule]), + aliases: { 'hallway lamp': 'LAMP-ID' }, + mqttClient: mqtt as unknown as SwitchBotMqttClient, + mqttCredential: fakeCredential, + skipApiCall: true, + statusFetcher: fetchStatus, + onFire: (e) => fires.push(e), + }); + await engine.start(); + + await engine.ingestEventForTest({ source: 'mqtt', event: 'motion.detected', t: new Date(), deviceId: 'S1' }); + await engine.drainForTest(); + + expect(fetchStatus).toHaveBeenCalledTimes(1); + expect(fetchStatus).toHaveBeenCalledWith('LAMP-ID'); + expect(fires.at(-1)?.status).toBe('throttled'); + expect(fires.at(-1)?.reason).toBe('already-desired'); + + await engine.stop(); + }); + it('allows turnOn when device is currently off', async () => { const fires: EngineFireEntry[] = []; const rule: Rule = { From cfc82a4310c0f5ebbc41a78f7fec716a12ec74da Mon Sep 17 00:00:00 2001 From: chenliuyun Date: Thu, 5 Nov 2026 21:05:18 +0800 Subject: [PATCH 2/3] fix: cover MCP credential regressions --- CHANGELOG.md | 2 + README.md | 5 +- docs/account-switch-safety-mvp.md | 17 +++- docs/agent-guide.md | 13 ++- src/commands/mcp.ts | 14 ++- tests/commands/auth.test.ts | 23 ++++- tests/commands/mcp-profile-http.test.ts | 73 +++++++------- tests/commands/mcp-safety-lifecycle.test.ts | 97 +++++++++++++++++++ tests/credentials/prime.test.ts | 19 ++++ tests/devices/account-cache-lifecycle.test.ts | 75 +++++++++++++- tests/devices/cache-scoping.test.ts | 36 +++++++ tests/policy/camera-safety-alignment.test.ts | 33 ++++++- tests/rules/action.test.ts | 55 +++++------ 13 files changed, 377 insertions(+), 85 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 405a0b1d..d1b3514a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,8 @@ This project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - MCP now applies destructive-command safety to cold-cache devices identified only by `controlType`. - HTTP MCP returns a protocol error instead of terminating if credentials change during request priming; unavailable replacement keychains cannot fall back to older file credentials. +- HTTP MCP honors explicit `--config` credentials for named-profile requests without relaxing profile-name or bearer-token checks. +- MCP tool credential-refresh failures retain structured runtime errors and allow recovery after credential repair. - Rule JSON parameters avoid a redundant parse while preserving request and audit formats. ### Compatibility diff --git a/README.md b/README.md index 7570c75f..269d885d 100644 --- a/README.md +++ b/README.md @@ -272,6 +272,9 @@ rebound automatically. Audit, policy, and event-history files are not cleared. If a newly selected native keychain is locked or unavailable, requests fail closed rather than using older file credentials. Offline commands and credential-repair commands remain available. +HTTP MCP also honors `--config` when a request selects a named profile; the +override selects the account, while profile-name and bearer-token checks +remain enforced. For HTTP `401`, check the active token/secret, signature and system clock; use `auth login` or replace the credential source locally, never paste secrets @@ -490,7 +493,7 @@ Policy commands retain their documented specialized exit codes (including YAML p ## Development -Verified CLI regression suite: 3163 tests. Plugin workspace checks are separate. +Verified CLI regression suite: 3191 tests. Plugin workspace checks are separate. ```bash npm install && npm run build diff --git a/docs/account-switch-safety-mvp.md b/docs/account-switch-safety-mvp.md index 61e73cac..0d346519 100644 --- a/docs/account-switch-safety-mvp.md +++ b/docs/account-switch-safety-mvp.md @@ -87,7 +87,7 @@ parameter shapes must remain unchanged. ## Delivery evidence -- Full CLI suite: **180 files, 3163 tests passed**; its setup ran the release +- Full CLI suite: **180 files, 3191 tests passed**; its setup ran the release build and TypeScript typecheck. Plugin workspace tests were not rerun. - `npm run lint:md` passed. - Isolated real CLI + MCP SDK smoke: a separate `config set-token` process @@ -101,5 +101,20 @@ parameter shapes must remain unchanged. failure and repair, retained-client/429 races, HTTP MCP recovery including an unavailable startup profile, profile scoping, and invalid SDK output. All network boundaries were local adapters. +- Follow-up coverage protects failed credential mutations, named-profile and + config-directory isolation, explicit credential overrides, obsolete default + caches, dispatched HMAC signatures, and dry-run read/mutation separation. + Live MCP cases exercise nine Light Bars numeric fields at both endpoints + and reject out-of-range, fractional, string, null, and missing values. + Policy and cold-cache rule cases preserve the Solar/Video Doorbell exception; + RGB and multiline JSON cases assert both wire and audit data, including dry-runs. +- Two new regressions failed before the minimal MCP fixes: named-profile HTTP + requests ignored `--config`, and tool credential-refresh failures omitted + structured errors. Both now pass. The ordinal filesystem-read race probe was + removed; retained HTTP recovery cases verify distinct replacement accounts. +- Built CLI HTTP/stdio smoke verified config-override dispatch, structured + credential failure with zero API requests, and same-process recovery after + an external `config set-token` repair. A local HTTP boundary replaced the + cloud; no real credential store was accessed. - No real OAuth, cloud API, MQTT broker, camera/image URL, or physical device was exercised. diff --git a/docs/agent-guide.md b/docs/agent-guide.md index 287a7140..ff5816fb 100644 --- a/docs/agent-guide.md +++ b/docs/agent-guide.md @@ -178,7 +178,12 @@ MQTT credentials are auto-provisioned from the startup profile's SwitchBot token HTTP profile selection uses `x-switchbot-profile` before `?profile=...`; names must start with a letter/digit and contain only letters, digits, `_` and `-`. Traversal and explicit empty names are rejected before filesystem access. Named history queries, aggregates, simulations and resets cannot read or remove another profile's history. -Named HTTP profiles may store credentials only in the OS keychain; a profile JSON file is not required. Profile lookup happens after bearer authentication, and names without credentials or a configuration file are rejected. +Named HTTP profiles may store credentials only in the OS keychain; a profile +JSON file is not required. Profile lookup happens after bearer authentication. +Without complete environment credentials or a `--config` override, names +without credentials or a configuration file are rejected. An explicit override +selects the account even when the request names another valid profile; profile +syntax and bearer-token checks still apply. MQTT subscriptions belong to the startup profile. A request for a different profile cannot read that subscription's `switchbot://events` ring or receive its MQTT account-overview fields. Restart the subscription/server after switching its account; existing streams and event history are not rebound or cleared. @@ -203,6 +208,12 @@ initialization is disabled instead of using an older file credential. HTTP MCP can still serve other valid named profiles. Restore the keychain and restart the server to establish the startup subscription. +Credential-refresh failures inside MCP tool callbacks retain +`isError: true` and `structuredContent.error` with kind `runtime`; the callback +does not dispatch an API request. After unlocking the replacement keychain or +repairing credentials, retry explicitly. HTTP request preflight failures remain +JSON-RPC protocol errors rather than tool results. + Implicit and explicit `default` use the same legacy cache paths. Named profiles are isolated; `--config` places caches in the config file's directory, so separate config files in one directory share a cache scope. diff --git a/src/commands/mcp.ts b/src/commands/mcp.ts index b70e33f8..2002b493 100644 --- a/src/commands/mcp.ts +++ b/src/commands/mcp.ts @@ -87,7 +87,7 @@ import { simulateRule } from '../rules/simulate.js'; import { allowsDirectDestructiveExecution, destructiveExecutionHint } from '../lib/destructive-mode.js'; import { writeFileSync } from 'node:fs'; import { readAudit, type AuditEntry } from '../utils/audit.js'; -import { isDryRun, parseDurationToMs } from '../utils/flags.js'; +import { getConfigPath, isDryRun, parseDurationToMs } from '../utils/flags.js'; import { resolveDeviceId } from '../utils/name-resolver.js'; import { preparePlanTargets, type PlanPreflightResult } from '../lib/plan-preflight.js'; import { parse as yamlParse } from 'yaml'; @@ -450,7 +450,11 @@ Tool profile: ${profileName} (${allowedTools.size} tools loaded).${profileName ! callback: (args: SchemaOutput, extra: RequestHandlerExtra) => CallToolResult | Promise, ) => { const primedCallback = async (args: SchemaOutput, extra: RequestHandlerExtra) => { - await primeCredentials(getActiveProfile() ?? 'default'); + try { + await primeCredentials(getActiveProfile() ?? 'default'); + } catch (error) { + return apiErrorToMcpError(error); + } return callback(args, extra); }; // Every local tool has an input schema; the SDK also supports a separate no-input callback form. @@ -2908,13 +2912,13 @@ process_uptime_seconds ${Math.floor(process.uptime())} } } - // Resolve keychain-only profiles after authentication, before rejecting - // names that have neither credentials nor a profile configuration. + // Explicit environment/config credentials override profile selection. + // Otherwise resolve keychain-only profiles before rejecting unknown names. if (profile) { try { await primeCredentials(profile); const envCredsPresent = !!(process.env.SWITCHBOT_TOKEN && process.env.SWITCHBOT_SECRET); - if (!envCredsPresent && !getPrimedCredentials(profile) && !fs.existsSync(profileFilePath(profile))) { + if (!envCredsPresent && !getConfigPath() && !getPrimedCredentials(profile) && !fs.existsSync(profileFilePath(profile))) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ jsonrpc: '2.0', diff --git a/tests/commands/auth.test.ts b/tests/commands/auth.test.ts index 12feedc8..709dfd4c 100644 --- a/tests/commands/auth.test.ts +++ b/tests/commands/auth.test.ts @@ -550,9 +550,26 @@ describe('authentication cache lifecycle', () => { .toEqual({ result: 'new result', replayed: false }); }); - it('preserves the current account caches when login fails', async () => { - browserLoginMock.mockRejectedValue(new Error('user cancelled')); - expect((await runCli(['auth', 'login', '--no-open'])).exitCode).toBe(1); + it.each([ + ['login', 'cancelled'], ['login', 'verification'], ['login', 'persistence'], + ['set', 'persistence'], ['delete', 'persistence'], ['migrate', 'persistence'], + ])('preserves the current account caches after %s %s failure', async (command, failure) => { + browserLoginMock.mockResolvedValue({ token: 'new-token', secret: 'new-secret' }); + verifyCredsMock.mockResolvedValue({ ok: true }); + if (failure === 'cancelled') browserLoginMock.mockRejectedValue(new Error('user cancelled')); + else if (failure === 'verification') verifyCredsMock.mockResolvedValue({ ok: false, reason: 'invalid credentials' }); + else selectMock.mockResolvedValue(makeStore({ + writable: true, + getResult: { token: 'old-token', secret: 'old-secret' }, + setImpl: async () => { throw new Error('credential store is read-only'); }, + deleteImpl: async () => { throw new Error('credential store is read-only'); }, + })); + const input = path.join(isolatedHome, 'credentials.json'); + fs.writeFileSync(input, JSON.stringify({ token: 'new-token', secret: 'new-secret' })); + const args = command === 'login' ? ['auth', 'login', '--no-open'] + : command === 'set' ? ['auth', 'keychain', 'set', '--stdin-file', input] + : ['auth', 'keychain', command, ...(command === 'delete' ? ['--yes'] : [])]; + expect((await runCli(args)).exitCode).toBe(1); expect(loadCache()?.devices.OLD.name).toBe('Old device'); expect(getCachedStatus('OLD', 60_000)).toEqual({ power: 'on' }); expect(getPrimedCredentials('default')?.token).toBe('old-token'); diff --git a/tests/commands/mcp-profile-http.test.ts b/tests/commands/mcp-profile-http.test.ts index 9a4cc03b..a28f29dc 100644 --- a/tests/commands/mcp-profile-http.test.ts +++ b/tests/commands/mcp-profile-http.test.ts @@ -14,17 +14,23 @@ afterEach(() => { for (const home of homes.splice(0)) rmSync(home, { recursive: true, force: true }); }); -async function startIsolatedMcp( +async function startIsolatedMcp({ keychainOnly = false, - rotatingProfile?: 'default' | 'work', - accessorRotation = false, + rotatingProfile, unavailableDefault = false, -): Promise { + configOverride = false, +}: { + keychainOnly?: boolean; + rotatingProfile?: 'default' | 'work'; + unavailableDefault?: boolean; + configOverride?: boolean; +} = {}): Promise { const home = mkdtempSync(join(tmpdir(), 'switchbot-http-profile-')); homes.push(home); // Run the real CLI HTTP handler. Only listen-port allocation is adapted: // Commander rejects port 0, so the harness delegates listen to a free port. const source = ` + import fs from 'node:fs'; const http = (await import('node:http')).default; const { syncBuiltinESMExports } = await import('node:module'); const originalCreateServer = http.createServer; @@ -34,25 +40,15 @@ async function startIsolatedMcp( let acceptingRequests = false; let rotated = false; ` : ''} - ${accessorRotation ? ` - import fs from 'node:fs'; - const originalRead = fs.readFileSync.bind(fs); - let revisionReads = 0; - fs.readFileSync = (file, ...args) => { - if (acceptingRequests && !rotated && String(file).endsWith('/.credential-revision') && ++revisionReads === 3) { - rotated = true; - publishCredentialRevision(readCredentialScope('work'), true); - } - return originalRead(file, ...args); - }; - ` : ''} ${unavailableDefault ? ` - import fs from 'node:fs'; import path from 'node:path'; fs.mkdirSync(path.join(process.env.HOME, '.switchbot'), { recursive: true }); fs.writeFileSync(path.join(process.env.HOME, '.switchbot', 'config.json'), JSON.stringify({ token: 'old-token', secret: 'old-secret' })); publishCredentialRevision(readCredentialScope('default'), true); ` : ''} + ${configOverride ? ` + fs.writeFileSync(${JSON.stringify(join(home, 'override.json'))}, JSON.stringify({ token: 'override-token', secret: 'override-secret' })); + ` : ''} ${keychainOnly ? ` // Simulate the external credential-store boundary, never the HTTP handler. Object.defineProperty(process, 'platform', { value: 'linux' }); @@ -63,7 +59,7 @@ async function startIsolatedMcp( if (command === 'which' && args[0] === 'secret-tool') output = 'isolated-secret-tool'; if (command === 'secret-tool') { const account = args[args.indexOf('account') + 1]; - ${rotatingProfile && !accessorRotation ? ` + ${rotatingProfile ? ` if (acceptingRequests && !rotated && account === ${JSON.stringify(`${rotatingProfile}:token`)}) { rotated = true; publishCredentialRevision(readCredentialScope(${JSON.stringify(rotatingProfile)}), true); @@ -71,6 +67,11 @@ async function startIsolatedMcp( ` : ''} output = account === 'work:token' ? 'work-token' : account === 'work:secret' ? 'work-secret' : ${unavailableDefault ? "''" : "account === 'default:token' ? 'default-token' : account === 'default:secret' ? 'default-secret' : ''"}; + ${rotatingProfile ? ` + if (rotated && account.startsWith(${JSON.stringify(`${rotatingProfile}:`)})) { + output = account.endsWith(':token') ? ${JSON.stringify(`${rotatingProfile}-replacement-token`)} : 'replacement-secret'; + } + ` : ''} } if (output !== undefined) { return originalSpawn(process.execPath, ['-e', 'process.stdout.write(' + JSON.stringify(output) + ')'], options); @@ -81,7 +82,8 @@ async function startIsolatedMcp( axios.defaults.adapter = async (config) => ({ status: 200, statusText: 'OK', headers: {}, config, data: { statusCode: 100, body: { deviceId: 'BOT1', deviceType: 'Bot', - power: config.headers.Authorization === 'work-token' ? 'ON' : 'OFF' } }, + power: String(config.headers.Authorization).startsWith('work-') ? 'ON' : 'OFF', + account: String(config.headers.Authorization) } }, }); ` : ''} http.createServer = (...args) => { @@ -95,7 +97,7 @@ async function startIsolatedMcp( return server; }; syncBuiltinESMExports(); - process.argv = ['node', 'switchbot', ${keychainOnly ? '' : `'--config', ${JSON.stringify(join(home, 'absent.json'))},`} '--no-quota', 'mcp', 'serve', '--port', '1']; + process.argv = ['node', 'switchbot', ${configOverride ? `'--config', ${JSON.stringify(join(home, 'override.json'))},` : keychainOnly ? '' : `'--config', ${JSON.stringify(join(home, 'absent.json'))},`} '--no-quota', 'mcp', 'serve', '--port', '1']; process.execArgv = []; // Delay entrypoint loading until the harness has installed its CLI and HTTP boundaries. await import('./src/index.ts'); @@ -123,31 +125,22 @@ async function startIsolatedMcp( } describe('HTTP MCP profile validation', () => { - it('survives credential replacement between named-profile priming and validation', async () => { - const port = await startIsolatedMcp(true, 'work', true); - const url = new URL(`http://127.0.0.1:${port}/mcp`); - const headers = { Authorization: 'Bearer isolated-profile-bearer', 'x-switchbot-profile': 'work' }; - const failed = await fetch(url, { - method: 'POST', - headers: { ...headers, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' }, - body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { - protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'accessor-rotation', version: '1' }, - } }), - }); - expect(failed.status).toBe(500); - expect(await failed.json()).toMatchObject({ error: { code: -32603 } }); - const client = new Client({ name: 'accessor-recovery', version: '1' }); + it('uses explicit config credentials for a keychain-only named profile', async () => { + const port = await startIsolatedMcp({ keychainOnly: true, configOverride: true }); + const client = new Client({ name: 'config-override-profile', version: '1' }); try { - await client.connect(new StreamableHTTPClientTransport(url, { requestInit: { headers } })); + await client.connect(new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${port}/mcp`), { + requestInit: { headers: { Authorization: 'Bearer isolated-profile-bearer', 'x-switchbot-profile': 'work' } }, + })); const result = await client.callTool({ name: 'get_device_status', arguments: { deviceId: 'BOT1' } }); - expect(result.structuredContent).toMatchObject({ status: { deviceId: 'BOT1', power: 'ON' } }); + expect(result.structuredContent).toMatchObject({ status: { deviceId: 'BOT1', account: 'override-token' } }); } finally { await client.close(); } }); it('serves a valid named profile when the startup profile keychain is unavailable', async () => { - const port = await startIsolatedMcp(true, undefined, false, true); + const port = await startIsolatedMcp({ keychainOnly: true, unavailableDefault: true }); const client = new Client({ name: 'named-profile-recovery', version: '1' }); try { await client.connect(new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${port}/mcp`), { @@ -161,7 +154,7 @@ describe('HTTP MCP profile validation', () => { }); it.each(['default', 'work'] as const)('survives credential replacement during %s request priming', async profile => { - const port = await startIsolatedMcp(true, profile); + const port = await startIsolatedMcp({ keychainOnly: true, rotatingProfile: profile }); const url = new URL(`http://127.0.0.1:${port}/mcp`); const headers = { Authorization: 'Bearer isolated-profile-bearer', @@ -182,7 +175,7 @@ describe('HTTP MCP profile validation', () => { await client.connect(new StreamableHTTPClientTransport(url, { requestInit: { headers } })); const result = await client.callTool({ name: 'get_device_status', arguments: { deviceId: 'BOT1' } }); expect(result.structuredContent).toMatchObject({ - status: { deviceId: 'BOT1', power: profile === 'work' ? 'ON' : 'OFF' }, + status: { deviceId: 'BOT1', power: profile === 'work' ? 'ON' : 'OFF', account: `${profile}-replacement-token` }, }); } finally { await client.close(); @@ -190,7 +183,7 @@ describe('HTTP MCP profile validation', () => { }); it('accepts keychain-only profiles without authorizing unknown profiles', async () => { - const port = await startIsolatedMcp(true); + const port = await startIsolatedMcp({ keychainOnly: true }); const client = new Client({ name: 'keychain-profile-test', version: '1' }); const transport = new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${port}/mcp`), { requestInit: { headers: { Authorization: 'Bearer isolated-profile-bearer', 'x-switchbot-profile': 'work' } }, diff --git a/tests/commands/mcp-safety-lifecycle.test.ts b/tests/commands/mcp-safety-lifecycle.test.ts index 97c02091..19276cfd 100644 --- a/tests/commands/mcp-safety-lifecycle.test.ts +++ b/tests/commands/mcp-safety-lifecycle.test.ts @@ -9,6 +9,19 @@ import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; import { createSwitchBotMcpServer } from '../../src/commands/mcp.js'; import { resetListCache, resetStatusCache } from '../../src/devices/cache.js'; import { idempotencyCache } from '../../src/lib/idempotency.js'; +import { publishCredentialRevision, readCredentialScope } from '../../src/credentials/scope.js'; +import { __resetPrimedCredentials } from '../../src/credentials/prime.js'; +import { createFileBackend } from '../../src/credentials/backends/file.js'; +import { saveConfig } from '../../src/config.js'; +import type * as CredentialStoreModule from '../../src/credentials/keychain.js'; + +const credentialStoreMock = vi.fn(); +vi.mock('../../src/credentials/keychain.js', async () => { + const actual = await vi.importActual( + '../../src/credentials/keychain.js', + ); + return { ...actual, selectCredentialStore: (...args: unknown[]) => credentialStoreMock(...args) }; +}); const originalArgv = process.argv; const originalAdapter = axios.defaults.adapter; @@ -24,6 +37,8 @@ beforeEach(() => { resetListCache(); resetStatusCache(); idempotencyCache.clear(); + __resetPrimedCredentials(); + credentialStoreMock.mockReset(); }); afterEach(() => { @@ -32,6 +47,7 @@ afterEach(() => { resetListCache(); resetStatusCache(); idempotencyCache.clear(); + __resetPrimedCredentials(); vi.unstubAllEnvs(); vi.restoreAllMocks(); fs.rmSync(tmp, { recursive: true, force: true }); @@ -46,7 +62,88 @@ async function connectMcp() { return { server, client }; } +describe('MCP Light Bars live parameter validation', () => { + it.each([ + { command: 'setBrightnessAndTemperature', field: 'brightness', min: 0, max: 100, base: { brightness: 50, temperature: 2700 } }, + { command: 'setBrightnessAndTemperature', field: 'temperature', min: 2700, max: 6500, base: { brightness: 0, temperature: 2700 } }, + { command: 'setMusicParamMode', field: 'musicMode', min: 0, max: 5, base: { musicMode: 0, musicLevel: 1, sensitivity: 100, controllerMode: 2 } }, + { command: 'setMusicParamMode', field: 'musicLevel', min: 1, max: 100, base: { musicMode: 0, musicLevel: 1, sensitivity: 100, controllerMode: 2 } }, + { command: 'setMusicParamMode', field: 'sensitivity', min: 1, max: 100, base: { musicMode: 0, musicLevel: 1, sensitivity: 100, controllerMode: 2 } }, + { command: 'setMusicParamMode', field: 'controllerMode', min: 0, max: 2, base: { musicMode: 0, musicLevel: 1, sensitivity: 100, controllerMode: 2 } }, + { command: 'setEffectSpeedMode', field: 'speed', min: 1, max: 255, base: { speed: 1 } }, + { command: 'setSegmentColorMode', field: 'lightIndex', min: 0, max: 11, base: { color: '0:0:255', lightIndex: 0 } }, + { command: 'setLightEffect', field: 'effectId', min: 0, max: 25, base: { effectId: 0 } }, + ])('enforces $command.$field boundaries before dispatch', async ({ command, field, min, max, base }) => { + const posts: unknown[] = []; + axios.defaults.adapter = async config => { + if (config.method === 'post') posts.push(JSON.parse(String(config.data))); + return { status: 200, statusText: 'OK', headers: {}, config, data: { statusCode: 100, + body: config.method === 'get' ? { + deviceList: [{ deviceId: 'BARS1', deviceName: 'Bars', deviceType: 'RGBICWW Light Bars', enableCloudService: true }], + infraredRemoteList: [], + } : {}, + } }; + }; + const { client, server } = await connectMcp(); + try { + for (const value of [min - 1, max + 1, min + 0.5, String(min), null, undefined]) { + const rejected = await client.callTool({ + name: 'send_command', arguments: { deviceId: 'BARS1', command, parameter: { ...base, [field]: value } }, + }); + expect(rejected.isError, `${field}=${value}`).toBe(true); + expect(posts).toEqual([]); + } + for (const value of [min, max]) { + const accepted = await client.callTool({ + name: 'send_command', arguments: { deviceId: 'BARS1', command, parameter: { ...base, [field]: value } }, + }); + expect(accepted.structuredContent).toMatchObject({ ok: true }); + } + expect(posts).toEqual([min, max].map(value => ({ + command, parameter: { ...base, [field]: value }, commandType: 'command', + }))); + } finally { + await client.close(); + await server.close(); + } + }); +}); + describe('MCP resolved device type safety', () => { + it('returns a structured error for unavailable replacement credentials and recovers after unlocking', async () => { + vi.stubEnv('SWITCHBOT_TOKEN', ''); + vi.stubEnv('SWITCHBOT_SECRET', ''); + process.argv = ['node', 'switchbot', '--no-quota', '--no-retry']; + saveConfig('obsolete-file-token', 'obsolete-file-secret'); + publishCredentialRevision(readCredentialScope(), true); + credentialStoreMock.mockRejectedValue(new Error('keychain locked')); + const dispatched: string[] = []; + axios.defaults.adapter = async config => { + const account = String(config.headers.Authorization); + dispatched.push(account); + return { status: 200, statusText: 'OK', headers: {}, config, + data: { statusCode: 100, body: { deviceId: 'BOT1', deviceType: 'Bot', power: 'ON', account } } }; + }; + const { client, server } = await connectMcp(); + try { + const failed = await client.callTool({ name: 'get_device_status', arguments: { deviceId: 'BOT1' } }); + expect(failed.isError).toBe(true); + expect(failed.structuredContent).toMatchObject({ error: { kind: 'runtime', code: 1 } }); + expect(dispatched).toEqual([]); + + credentialStoreMock.mockResolvedValue({ + ...createFileBackend(), name: 'keychain', + get: async () => ({ token: 'replacement-token', secret: 'replacement-secret' }), + }); + const recovered = await client.callTool({ name: 'get_device_status', arguments: { deviceId: 'BOT1' } }); + expect(recovered.structuredContent).toMatchObject({ status: { deviceId: 'BOT1', account: 'replacement-token' } }); + expect(dispatched).toEqual(['replacement-token']); + } finally { + await client.close(); + await server.close(); + } + }); + it.each([ ['Solar Pan/Tilt Cam 2K', 'controlType', 'disableMotionDetection'], ['Smart Lock Ultra Max', 'controlType', 'Unlock'], diff --git a/tests/credentials/prime.test.ts b/tests/credentials/prime.test.ts index 1f1e70f8..872632cb 100644 --- a/tests/credentials/prime.test.ts +++ b/tests/credentials/prime.test.ts @@ -127,6 +127,25 @@ describe('primeCredentials', () => { expect(dispatched).toEqual(['account-B']); }); + it.each(['environment', 'explicit config'])('honors the %s override while a replacement keychain is unavailable', async source => { + saveConfig('file-account', 'file-secret'); + publishCredentialRevision(readCredentialScope(), true); + selectMock.mockRejectedValue(new Error('keychain locked')); + if (source === 'environment') { + vi.stubEnv('SWITCHBOT_TOKEN', 'env-account'); + vi.stubEnv('SWITCHBOT_SECRET', 'env-secret'); + } else { + process.argv.push('--config', path.join(home, '.switchbot', 'config.json')); + } + axios.defaults.adapter = async config => ({ + status: 200, statusText: 'OK', headers: {}, config, + data: { statusCode: 100, body: { account: String(config.headers.Authorization) } }, + }); + + const response = await createClient().get('/v1.1/devices'); + expect(response.data.body).toEqual({ account: source === 'environment' ? 'env-account' : 'file-account' }); + }); + it('does not let synchronous credential consumers fall back to an obsolete file after keychain replacement', () => { saveConfig('account-A', 'secret-A'); publishCredentialRevision(readCredentialScope(), true); diff --git a/tests/devices/account-cache-lifecycle.test.ts b/tests/devices/account-cache-lifecycle.test.ts index 29376493..bbf966cb 100644 --- a/tests/devices/account-cache-lifecycle.test.ts +++ b/tests/devices/account-cache-lifecycle.test.ts @@ -4,6 +4,7 @@ import os from 'node:os'; import path from 'node:path'; import { spawnSync } from 'node:child_process'; import { EventEmitter, once } from 'node:events'; +import { createHmac } from 'node:crypto'; import axios from 'axios'; import { saveConfig } from '../../src/config.js'; import { executeCommand, fetchDeviceList, fetchDeviceStatus } from '../../src/lib/devices.js'; @@ -11,6 +12,7 @@ import { loadCache, loadStatusCache, resetListCache, resetStatusCache, setCached import { __resetPrimedCredentials } from '../../src/credentials/prime.js'; import { apiCircuitBreaker, createClient } from '../../src/api/client.js'; import { idempotencyCache } from '../../src/lib/idempotency.js'; +import { withRequestContext } from '../../src/lib/request-context.js'; const originalArgv = process.argv; const originalAdapter = axios.defaults.adapter; @@ -45,11 +47,11 @@ afterEach(() => { fs.rmSync(home, { recursive: true, force: true }); }); -function changeAccount(): void { +function changeAccount(scopeArgs = ['--config', configPath]): void { const envFile = path.join(home, 'account-b.env'); fs.writeFileSync(envFile, 'SWITCHBOT_TOKEN=account-B\nSWITCHBOT_SECRET=secret-B\n'); const result = spawnSync(process.execPath, [ - '--import', 'tsx', 'src/index.ts', '--config', configPath, '--json', + '--import', 'tsx', 'src/index.ts', ...scopeArgs, '--json', 'config', 'set-token', '--from-env-file', envFile, ], { cwd: process.cwd(), @@ -59,6 +61,26 @@ function changeAccount(): void { if (result.status !== 0) throw new Error(result.stderr || result.stdout || String(result.error)); } +describe('authenticated dry-run requests', () => { + it('allows inventory reads while refusing command dispatch', async () => { + saveConfig('account-A', 'secret-A'); + process.argv.push('--dry-run'); + vi.spyOn(console, 'log').mockImplementation(() => {}); + const requests: string[] = []; + axios.defaults.adapter = async config => { + requests.push(`${config.method} ${config.url}`); + return { status: 200, statusText: 'OK', headers: {}, config, data: { + statusCode: 100, body: { deviceList: [{ deviceId: 'A-DEVICE' }], infraredRemoteList: [] }, + } }; + }; + const client = createClient(); + expect((await client.get('/v1.1/devices')).data.body.deviceList).toEqual([{ deviceId: 'A-DEVICE' }]); + await expect(client.post('/v1.1/devices/A-DEVICE/commands', { command: 'turnOn' })) + .rejects.toMatchObject({ name: 'DryRunSignal' }); + expect(requests).toEqual(['get /v1.1/devices']); + }); +}); + describe('account changes across processes', () => { it('stops serving the old account inventory and status after an external credential command', async () => { saveConfig('account-A', 'secret-A'); @@ -67,6 +89,9 @@ describe('account changes across processes', () => { const token = String(config.headers.Authorization); requests.push({ url: config.url, token }); const oldAccount = token === 'account-A'; + const expectedSignature = createHmac('sha256', oldAccount ? 'secret-A' : 'secret-B') + .update(`${token}${config.headers.t}${config.headers.nonce}`).digest('base64').toUpperCase(); + expect(config.headers.sign).toBe(expectedSignature); const body = config.url === '/v1.1/devices' ? { deviceList: [{ deviceId: oldAccount ? 'A-DEVICE' : 'B-DEVICE', deviceName: 'Lamp', deviceType: 'Color Bulb', @@ -89,6 +114,52 @@ describe('account changes across processes', () => { ]); }); + it.each(['named profiles', 'config directories'])('rotates only the selected account across %s', async mode => { + const scopeArgs = (name: string) => mode === 'named profiles' + ? ['--profile', name] + : ['--config', path.join(home, name, 'config.json')]; + const inScope = (name: string, run: () => T): T => { + process.argv = ['node', 'switchbot', ...scopeArgs(name), '--cache', '1h', '--no-quota', '--no-retry']; + return withRequestContext({ profile: mode === 'named profiles' ? name : 'default' }, run); + }; + inScope('alpha', () => saveConfig('alpha-token', 'alpha-secret')); + inScope('beta', () => saveConfig('beta-token', 'beta-secret')); + const dispatched: Array<{ account: string; method: string | undefined }> = []; + axios.defaults.adapter = async config => { + const account = String(config.headers.Authorization); + dispatched.push({ account, method: config.method }); + const body = config.url === '/v1.1/devices' + ? { deviceList: [{ deviceId: 'SHARED', deviceName: account, deviceType: 'Bot' }], infraredRemoteList: [] } + : { account }; + return { status: 200, statusText: 'OK', headers: {}, config, data: { statusCode: 100, body } }; + }; + const readAccount = (name: string) => inScope(name, async () => ({ + deviceName: (await fetchDeviceList()).deviceList[0].deviceName, + status: await fetchDeviceStatus('SHARED'), + command: await executeCommand('SHARED', 'turnOn', 'default', 'command', undefined, { idempotencyKey: 'shared-key' }), + })); + + expect(await readAccount('alpha')).toEqual({ + deviceName: 'alpha-token', status: { account: 'alpha-token' }, command: { account: 'alpha-token' }, + }); + expect(await readAccount('beta')).toEqual({ + deviceName: 'beta-token', status: { account: 'beta-token' }, command: { account: 'beta-token' }, + }); + changeAccount(scopeArgs('alpha')); + dispatched.length = 0; + + expect(await readAccount('beta')).toEqual({ + deviceName: 'beta-token', status: { account: 'beta-token' }, command: { account: 'beta-token', replayed: true }, + }); + expect(dispatched).toEqual([]); + expect(await readAccount('alpha')).toEqual({ + deviceName: 'account-B', status: { account: 'account-B' }, command: { account: 'account-B' }, + }); + expect(dispatched).toEqual([ + { account: 'account-B', method: 'get' }, { account: 'account-B', method: 'get' }, { account: 'account-B', method: 'post' }, + ]); + }); + it.each(['inventory', 'status', 'uncached status'])('rejects an old-account %s response after credential replacement', async kind => { saveConfig('account-A', 'secret-A'); if (kind === 'uncached status') process.argv.push('--no-cache'); diff --git a/tests/devices/cache-scoping.test.ts b/tests/devices/cache-scoping.test.ts index bb7ad754..5879104b 100644 --- a/tests/devices/cache-scoping.test.ts +++ b/tests/devices/cache-scoping.test.ts @@ -25,6 +25,7 @@ import { } from '../../src/devices/cache.js'; import { withRequestContext } from '../../src/lib/request-context.js'; +const originalArgv = process.argv; let tmpDir: string; const sampleBody = { @@ -46,6 +47,7 @@ beforeEach(() => { }); afterEach(() => { + process.argv = originalArgv; vi.restoreAllMocks(); resetListCache(); resetStatusCache(); @@ -81,6 +83,40 @@ describe('cache scoping — no profile (legacy path)', () => { expect(loadCache()).toBeNull(); expect(getCachedStatus('DEV-1', 60_000)).toBeNull(); }); + + it('does not restore obsolete hashed-default inventory or status after clearing the active cache', () => { + const obsolete = path.join(tmpDir, '.switchbot', 'cache', sha8('default')); + const now = new Date().toISOString(); + fs.mkdirSync(obsolete, { recursive: true }); + fs.writeFileSync(path.join(obsolete, 'devices.json'), JSON.stringify({ + lastUpdated: now, devices: { OLD: { type: 'Bot', name: 'Old account', category: 'physical' } }, + })); + fs.writeFileSync(path.join(obsolete, 'status.json'), JSON.stringify({ + entries: { OLD: { fetchedAt: now, body: { power: 'on' } } }, + })); + updateCacheFromDeviceList(sampleBody); + setCachedStatus('DEV-1', { power: 'off' }); + + withRequestContext({ profile: 'default' }, () => { + expect(loadCache()?.devices).toEqual({ + 'DEV-1': { type: 'Bot', typeSource: 'deviceType', name: 'Bot', category: 'physical' }, + }); + expect(getCachedStatus('OLD', 60_000)).toBeNull(); + expect(getCachedStatus('DEV-1', 60_000)).toEqual({ power: 'off' }); + clearCache(); + clearStatusCache(); + }); + resetListCache(); + resetStatusCache(); + + for (const profile of [undefined, 'default']) { + withRequestContext({ profile }, () => { + expect(loadCache()).toBeNull(); + expect(getCachedStatus('OLD', 60_000)).toBeNull(); + expect(getCachedStatus('DEV-1', 60_000)).toBeNull(); + }); + } + }); }); // ── b. Named profile → scoped path ────────────────────────────────────────── diff --git a/tests/policy/camera-safety-alignment.test.ts b/tests/policy/camera-safety-alignment.test.ts index ee45f595..a32bb1db 100644 --- a/tests/policy/camera-safety-alignment.test.ts +++ b/tests/policy/camera-safety-alignment.test.ts @@ -4,7 +4,7 @@ import os from 'node:os'; import path from 'node:path'; import { loadPolicyFile } from '../../src/policy/load.js'; -import { validateLoadedPolicy } from '../../src/policy/validate.js'; +import { validateLoadedPolicy, validateLoadedPolicyAgainstInventory } from '../../src/policy/validate.js'; describe('Solar Pan/Tilt Cam safety policy', () => { let tmpDir: string | undefined; @@ -29,4 +29,35 @@ describe('Solar Pan/Tilt Cam safety policy', () => { expect.objectContaining({ keyword: 'not', path: '/confirmations/never_confirm/0' }), ); }); + + it.each([ + ['Solar Pan/Tilt Cam 2K', false], + ['Video Doorbell', true], + ] as const)('validates disableMotionDetection against %s rather than globally banning the verb', (deviceType, allowed) => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'switchbot-camera-policy-')); + const policyPath = path.join(tmpDir, 'policy.yaml'); + fs.writeFileSync(policyPath, [ + 'version: "0.2"', + 'aliases:', + ' camera: 01-202407090924-26354212', + 'automation:', + ' rules:', + ' - name: camera motion', + ' when: { source: mqtt, event: x.y }', + ' then:', + ' - command: devices command disableMotionDetection', + ' device: camera', + ].join('\n')); + const result = validateLoadedPolicyAgainstInventory(loadPolicyFile(policyPath), { + deviceList: [{ + deviceId: '01-202407090924-26354212', deviceName: 'Camera', deviceType, + enableCloudService: true, hubDeviceId: '', + }], + infraredRemoteList: [], + }); + expect(result.valid).toBe(allowed); + if (!allowed) expect(result.errors).toContainEqual(expect.objectContaining({ + keyword: 'rule-destructive-action', path: '/automation/rules/0/then/0/command', + })); + }); }); diff --git a/tests/rules/action.test.ts b/tests/rules/action.test.ts index cb5b31fb..133bc5b7 100644 --- a/tests/rules/action.test.ts +++ b/tests/rules/action.test.ts @@ -117,6 +117,8 @@ describe('executeRuleAction', () => { ['Garage Door Opener', 'turnOff', false], ['Color Bulb', 'turnOn', true], [null, 'turnOn', false], + ['Solar Pan/Tilt Cam 2K', 'disableMotionDetection', false], + ['Video Doorbell', 'disableMotionDetection', true], ])('checks live inventory before automating %s %s', async (deviceType, command, allowed) => { const requests: string[] = []; const client = axios.create({ @@ -163,9 +165,12 @@ describe('executeRuleAction', () => { expect(result.ok).toBe(true); expect(posted?.parameter).toEqual({ action: 'sweep', param: { fanLevel: 2, times: 1 } }); + expect(readAudit(auditFile).at(-1)).toMatchObject({ + kind: 'rule-fire', result: 'ok', parameter: { action: 'sweep', param: { fanLevel: 2, times: 1 } }, + }); }); - it('preserves spaces in JSON strings and unrelated text parameters', async () => { + it.each([false, true])('preserves JSON and text whitespace in wire and audit data with dryRun=%s', async dryRun => { updateCacheFromDeviceList({ deviceList: [ { deviceId: 'FRAME-1', deviceName: 'Frame', deviceType: 'AI Art Frame' }, @@ -187,55 +192,43 @@ describe('executeRuleAction', () => { for (const command of commands) { const action = { command }; const result = await executeRuleAction(action, { - rule: { ...baseRule, then: [action] }, fireId: command, aliases: {}, httpClient: client, + rule: { ...baseRule, then: [action], dry_run: dryRun }, fireId: command, aliases: {}, httpClient: client, }); expect(result.ok, command).toBe(true); } - expect(parameters).toEqual([{ imageUrl: 'https://example.test/my art.jpg' }, 'hello home']); + const expected = [{ imageUrl: 'https://example.test/my art.jpg' }, 'hello home']; + expect(parameters).toEqual(dryRun ? [] : expected); + const kinds = dryRun ? ['rule-fire-dry'] : ['command', 'rule-fire']; + expect(readAudit(auditFile).map(({ kind, result, parameter }) => ({ kind, result, parameter }))) + .toEqual(expected.flatMap(parameter => kinds.map(kind => ({ kind, result: 'ok', parameter })))); }); - it('sends legacy space-separated and colon-separated RGB rules identically', async () => { + it.each([ + ['Color Bulb', 'setColor', false], ['Color Bulb', 'setColor', true], + ['RGBICWW Ceiling Light', 'setColorLightRGB', false], ['RGBICWW Ceiling Light', 'setColorLightRGB', true], + ] as const)('preserves both RGB formats for %s %s with dryRun=%s', async (deviceType, verb, dryRun) => { updateCacheFromDeviceList({ - deviceList: [{ deviceId: 'LAMP-1', deviceName: 'Lamp', deviceType: 'Color Bulb' }], + deviceList: [{ deviceId: 'LAMP-1', deviceName: 'Lamp', deviceType }], infraredRemoteList: [], }); const parameters: unknown[] = []; const client = axios.create({ - adapter: async (config) => { + adapter: async config => { parameters.push(JSON.parse(config.data as string).parameter); return { data: { body: {} }, status: 200, statusText: 'OK', headers: {}, config }; }, }); - for (const color of ['255 0 0', '255:0:0', '255 0\t0']) { - const action = { command: `devices command LAMP-1 setColor ${color}` }; + const action = { command: `devices command LAMP-1 ${verb} ${color}` }; const result = await executeRuleAction(action, { - rule: { ...baseRule, then: [action] }, fireId: color, aliases: {}, httpClient: client, + rule: { ...baseRule, then: [action], dry_run: dryRun }, fireId: color, aliases: {}, httpClient: client, }); expect(result.ok, color).toBe(true); + expect(readAudit(auditFile).at(-1)).toMatchObject({ + kind: dryRun ? 'rule-fire-dry' : 'rule-fire', result: 'ok', command: verb, parameter: '255:0:0', + }); } - expect(parameters).toEqual(['255:0:0', '255:0:0', '255:0:0']); - }); - - it('preserves space-separated RGB rules for the ceiling color light', async () => { - updateCacheFromDeviceList({ - deviceList: [{ deviceId: 'CEILING-1', deviceName: 'Ceiling', deviceType: 'RGBICWW Ceiling Light' }], - infraredRemoteList: [], - }); - let parameter: unknown; - const client = axios.create({ - adapter: async (config) => { - parameter = JSON.parse(config.data as string).parameter; - return { data: { body: {} }, status: 200, statusText: 'OK', headers: {}, config }; - }, - }); - const action = { command: 'devices command CEILING-1 setColorLightRGB 255 0 0' }; - const result = await executeRuleAction(action, { - rule: { ...baseRule, then: [action] }, fireId: 'ceiling-rgb', aliases: {}, httpClient: client, - }); - - expect(result.ok).toBe(true); - expect(parameter).toBe('255:0:0'); + expect(parameters).toEqual(dryRun ? [] : ['255:0:0', '255:0:0', '255:0:0']); }); it('rejects invalid space-separated RGB rules before sending', async () => { From f1101dc3a131fa351e84e2c88994a984877c1fe6 Mon Sep 17 00:00:00 2001 From: chenliuyun Date: Fri, 6 Nov 2026 09:44:58 +0800 Subject: [PATCH 3/3] ci: harden release gates and native credential checks --- .github/workflows/ci.yml | 42 +++++- .github/workflows/keychain-matrix.yml | 61 +++++--- .github/workflows/npm-published-smoke.yml | 8 +- .github/workflows/publish.yml | 8 + .github/workflows/smoke.yml | 18 ++- CHANGELOG.md | 4 + README.md | 9 +- docs/account-switch-safety-mvp.md | 7 +- docs/release-pipeline.md | 109 ++++++++++---- package-lock.json | 1 + package.json | 3 + scripts/release-candidate.mjs | 21 ++- scripts/smoke-keychain.mjs | 26 ++++ tests/build/keychain-smoke.test.ts | 66 ++++++++ .../build/release-candidate-promotion.test.ts | 142 +++++++++++++++--- 15 files changed, 442 insertions(+), 83 deletions(-) create mode 100755 scripts/smoke-keychain.mjs create mode 100644 tests/build/keychain-smoke.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index afebde46..53b51e82 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,9 +6,28 @@ on: pull_request: branches: [main] +permissions: + contents: read + +concurrency: + group: ci-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + jobs: + workflow-lint: + name: GitHub Actions schema lint + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.13' + - run: python -m pip install --disable-pip-version-check check-jsonschema==0.39.0 + - run: check-jsonschema --builtin-schema vendor.github-workflows .github/workflows/*.yml + docs-lint: - name: Markdown lint (changelog) + name: Markdown lint runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -17,14 +36,15 @@ jobs: node-version: 20.x cache: npm - run: npm ci - - run: npm run lint:md:changelog + - run: npm run lint:md test: runs-on: ubuntu-latest - needs: docs-lint + needs: [docs-lint, workflow-lint] strategy: + fail-fast: false matrix: - node-version: [18.x, 20.x, 22.x] + node-version: [18.x, 20.x, 22.x, 24.x] steps: - uses: actions/checkout@v4 - name: Use Node.js ${{ matrix.node-version }} @@ -43,12 +63,22 @@ jobs: exit 1 fi - run: npm test + if: matrix.node-version != '24.x' + - run: npm run test:coverage + if: matrix.node-version == '24.x' + - name: Upload coverage report + if: always() && matrix.node-version == '24.x' + uses: actions/upload-artifact@v4 + with: + name: cli-coverage + path: coverage/ + if-no-files-found: error - run: npm run test:workspaces openclaw-bootstrap: name: OpenClaw native bootstrap (${{ matrix.os }}) runs-on: ${{ matrix.os }} - needs: docs-lint + needs: [docs-lint, workflow-lint] strategy: fail-fast: false matrix: @@ -78,7 +108,7 @@ jobs: strategy: fail-fast: false matrix: - node-version: [18.x, 20.x, 22.x] + node-version: [18.x, 20.x, 22.x, 24.x] steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 diff --git a/.github/workflows/keychain-matrix.yml b/.github/workflows/keychain-matrix.yml index 20bc01fa..c9da22f9 100644 --- a/.github/workflows/keychain-matrix.yml +++ b/.github/workflows/keychain-matrix.yml @@ -4,23 +4,33 @@ on: push: branches: [main] paths: - - 'src/credentials/**' - - 'src/install/**' - - 'tests/credentials/**' - - 'tests/install/**' + - 'src/**' + - 'tests/**' + - 'scripts/smoke-keychain.mjs' + - 'package*.json' + - 'tsconfig*.json' + - '.github/workflows/keychain-matrix.yml' pull_request: branches: [main] paths: - - 'src/credentials/**' - - 'src/install/**' - - 'tests/credentials/**' - - 'tests/install/**' + - 'src/**' + - 'tests/**' + - 'scripts/smoke-keychain.mjs' + - 'package*.json' + - 'tsconfig*.json' + - '.github/workflows/keychain-matrix.yml' workflow_dispatch: -# Each job installs Node, builds, and runs the credential + install-step -# test suites against the real OS keychain backend. The unit tests (which -# mock spawn) pass on ubuntu-latest in the main CI; here we verify -# that the live system commands are available and callable. +permissions: + contents: read + +concurrency: + group: keychain-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +# Shared cache/credential/MCP regressions run on every supported OS. +# The separate native smoke rejects file fallback and exercises actual +# keychain create/read/replace/delete with disposable dummy credentials. jobs: keychain-macos: @@ -38,19 +48,28 @@ jobs: # Create and unlock a temporary keychain so the macOS backend can # write entries without prompting the System Keychain. - name: Set up temporary keychain + shell: bash run: | + original=$(security default-keychain -d user | xargs) + echo "SWITCHBOT_CI_ORIGINAL_KEYCHAIN=$original" >> "$GITHUB_ENV" security create-keychain -p "" switchbot-ci.keychain security set-keychain-settings -lut 3600 switchbot-ci.keychain security unlock-keychain -p "" switchbot-ci.keychain security list-keychains -d user -s switchbot-ci.keychain $(security list-keychains -d user | sed s/\"//g) - echo "SWITCHBOT_CI_KEYCHAIN=switchbot-ci.keychain" >> "$GITHUB_ENV" + security default-keychain -d user -s switchbot-ci.keychain - - name: Run credential + install-step tests - run: npm test -- tests/credentials tests/install + - name: Run account lifecycle regressions + run: npm run test:account-lifecycle + - name: Exercise native keychain lifecycle + run: npm run smoke:keychain - name: Delete temporary keychain if: always() + shell: bash run: | + if [ -n "${SWITCHBOT_CI_ORIGINAL_KEYCHAIN:-}" ]; then + security default-keychain -d user -s "$SWITCHBOT_CI_ORIGINAL_KEYCHAIN" + fi security delete-keychain switchbot-ci.keychain || true keychain-linux: @@ -76,12 +95,14 @@ jobs: # Start a D-Bus session and unlock gnome-keyring so secret-tool can # store entries. The keyring is unlocked with an empty password. - - name: Run credential + install-step tests inside D-Bus session + - name: Run lifecycle regressions and native smoke inside D-Bus session + shell: bash run: | eval "$(dbus-launch --sh-syntax)" echo "" | gnome-keyring-daemon --daemonize --unlock --components=secrets export DBUS_SESSION_BUS_ADDRESS - npm test -- tests/credentials tests/install + npm run test:account-lifecycle + npm run smoke:keychain keychain-windows: name: Keychain — Windows (Credential Manager) @@ -97,5 +118,7 @@ jobs: # Windows Credential Manager is available to any logged-in user on # GitHub-hosted Windows runners; no extra setup required. - - name: Run credential + install-step tests - run: npm test -- tests/credentials tests/install + - name: Run account lifecycle regressions + run: npm run test:account-lifecycle + - name: Exercise native Credential Manager lifecycle + run: npm run smoke:keychain diff --git a/.github/workflows/npm-published-smoke.yml b/.github/workflows/npm-published-smoke.yml index d6c771c1..f42163df 100644 --- a/.github/workflows/npm-published-smoke.yml +++ b/.github/workflows/npm-published-smoke.yml @@ -237,17 +237,23 @@ jobs: (github.event.workflow_run.event == 'release' || github.event.workflow_run.event == 'workflow_dispatch') needs: [source, smoke, required-hosts] runs-on: ubuntu-latest + concurrency: + group: npm-latest-promotion + cancel-in-progress: false + queue: max permissions: actions: read contents: read steps: + # Apply current promotion policy even when recovering an older candidate. - uses: actions/checkout@v4 with: - ref: ${{ needs.source.outputs.revision }} + ref: ${{ github.workflow_sha }} - uses: actions/setup-node@v4 with: node-version: 20.x registry-url: https://registry.npmjs.org + - run: npm ci --ignore-scripts - name: Download authoritative candidate outcomes uses: actions/download-artifact@v4 with: diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index fb399a26..4e2d88f7 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -13,6 +13,12 @@ on: description: 'Dry run — record candidate outcomes without publishing' type: boolean default: false + +concurrency: + group: npm-candidate-publication + cancel-in-progress: false + queue: max + jobs: publish: runs-on: ubuntu-latest @@ -30,6 +36,8 @@ jobs: cache: npm - run: npm ci - run: npm run verify:release-gate + - name: Full CLI regression gate for the exact release source + run: npm test - run: npm run verify:release - name: Verify tag matches root CLI package.json version diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 9db27274..87744942 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -8,12 +8,19 @@ on: workflow_dispatch: inputs: physical_device_id: - description: "Physical device ID (idempotency + history). Will send turnOn, turnOn (replay), turnOff (conflict). Omit to skip." + description: "Physical device ID (idempotency flag + history). Sends ONE turnOn. Omit to skip." required: false ir_device_id: description: "IR device ID (verification flag). Will send ONE turnOn IR transmission. Omit to skip." required: false +permissions: + contents: read + +defaults: + run: + shell: bash + jobs: smoke: runs-on: ubuntu-latest @@ -44,15 +51,16 @@ jobs: run: | node dist/index.js devices list --json > /tmp/list.json echo "device count=$(jq '.data | length' /tmp/list.json)" - node dist/index.js doctor --json | jq '.data.summary' + node dist/index.js doctor --json | jq -e '.data.summary | objects' - name: IR verification flag (destructive — real IR transmission) if: ${{ inputs.ir_device_id != '' }} env: SWITCHBOT_TOKEN: ${{ secrets.SWITCHBOT_TOKEN }} SWITCHBOT_SECRET: ${{ secrets.SWITCHBOT_SECRET }} + DEV: ${{ inputs.ir_device_id }} run: | - node dist/index.js devices command "${{ inputs.ir_device_id }}" turnOn --json > /tmp/ir.json + node dist/index.js devices command "$DEV" turnOn --json > /tmp/ir.json cat /tmp/ir.json jq -e '.data.verification.verifiable == false' /tmp/ir.json echo "PASS: data.verification.verifiable == false" @@ -92,6 +100,6 @@ jobs: kill $TAIL_PID 2>/dev/null || true wait $TAIL_PID 2>/dev/null || true - node dist/index.js history stats "$DEV" --json | tee /tmp/stats.json | jq '.data' - node dist/index.js history range "$DEV" --since 5m --json | jq '.data | length' + node dist/index.js history stats "$DEV" --json | tee /tmp/stats.json | jq -e '.data | objects' + node dist/index.js history range "$DEV" --since 5m --json | jq -e '.data.records | arrays | length' echo "PASS: history commands returned valid JSON" diff --git a/CHANGELOG.md b/CHANGELOG.md index d1b3514a..b58cb41e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ This project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - Catalog coverage for RGBICWW Light Bars, Smart Lock Ultra Max, Curtain 4, Robot Vacuum Cleaner K11 Plus Pro, AI Art Frame Luma, Outdoor Pan/Tilt Cam 3K, and Solar Pan/Tilt Cam 2K. - Light Bars object commands, including `setLightEffect` with `effectId` 0–25; six existing documented lights also expose their light effects. - Camera `latestImage` metadata with its expiry contract, Solar motion-detection controls, and Art Frame Luma upload/status support. +- CI workflow-schema validation, full Markdown lint, Node 24 regression/coverage gates, and isolated native credential create/replace/delete smoke checks on Linux, macOS, and Windows. ### Changed @@ -30,6 +31,9 @@ This project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - HTTP MCP honors explicit `--config` credentials for named-profile requests without relaxing profile-name or bearer-token checks. - MCP tool credential-refresh failures retain structured runtime errors and allow recovery after credential repair. - Rule JSON parameters avoid a redundant parse while preserving request and audit formats. +- Publication now runs the full CLI suite on the exact release source; queued publication/promotion runs preserve pending candidates, and promotion rejects SemVer downgrades before changing any `latest` tags. +- Historical candidate recovery uses the workflow revision's promotion policy instead of reviving older release tooling. +- Manual hardware smoke now fails on CLI pipeline errors and invalid JSON envelopes; empty history remains valid. ### Compatibility diff --git a/README.md b/README.md index 269d885d..4205c79d 100644 --- a/README.md +++ b/README.md @@ -493,14 +493,21 @@ Policy commands retain their documented specialized exit codes (including YAML p ## Development -Verified CLI regression suite: 3191 tests. Plugin workspace checks are separate. +Verified CLI regression suite: 3205 tests. Plugin workspace checks are separate. ```bash npm install && npm run build npm run dev -- # run from TypeScript via tsx npm test # Vitest suite +npm run test:account-lifecycle # focused account/cache/MCP regressions +npm run test:coverage # suite plus coverage thresholds ``` +CI runs CLI regressions on Node 18/20/22/24, enforces coverage on Node 24, +and checks all Markdown and workflow schemas. Native credential checks and +candidate publication/promotion gates are described in the +[release pipeline](docs/release-pipeline.md). + ## License [MIT](./LICENSE) © chenliuyun diff --git a/docs/account-switch-safety-mvp.md b/docs/account-switch-safety-mvp.md index 0d346519..e4aa6109 100644 --- a/docs/account-switch-safety-mvp.md +++ b/docs/account-switch-safety-mvp.md @@ -87,7 +87,7 @@ parameter shapes must remain unchanged. ## Delivery evidence -- Full CLI suite: **180 files, 3191 tests passed**; its setup ran the release +- Full CLI suite: **181 files, 3205 tests passed**; its setup ran the release build and TypeScript typecheck. Plugin workspace tests were not rerun. - `npm run lint:md` passed. - Isolated real CLI + MCP SDK smoke: a separate `config set-token` process @@ -116,5 +116,10 @@ parameter shapes must remain unchanged. credential failure with zero API requests, and same-process recovery after an external `config set-token` repair. A local HTTP boundary replaced the cloud; no real credential store was accessed. +- CI/CD follow-up verifies promotion with real npm and a local registry, + including stale-version rejection before any tag write. Workflow shell + fixtures reject CLI failures and invalid envelopes while accepting empty + history; macOS cleanup preserves a quoted default-keychain path with spaces. + These fixtures do not claim native macOS/Windows credential-store execution. - No real OAuth, cloud API, MQTT broker, camera/image URL, or physical device was exercised. diff --git a/docs/release-pipeline.md b/docs/release-pipeline.md index 8b3c5636..7a5977ca 100644 --- a/docs/release-pipeline.md +++ b/docs/release-pipeline.md @@ -52,32 +52,47 @@ stage 5 with a message pointing to `scripts/bundle.mjs`. ## Gates before `npm publish` -```text -git commit ──▶ pre-commit hook ─── verify:pre-commit - (npm run build + tests/version.test.ts) - -git push ──▶ pre-push hook ──── verify:pre-push - (npm run build + version test + - smoke:pack-install) - -open PR ──▶ ci.yml ──────────── docs-lint - test matrix (Node 18/20/22) - bundle-smoke (Node 18/20/22) - offline-smoke (size budgets) - pack-install-smoke (matches publish) - policy-schema-sync - -merge PR ──▶ main - -release ──▶ publish.yml ─────── 1. npm ci - 2. verify:release-gate (build, tests, pack and host-independent smokes) - 3. verify:release (built CLI/runtime documentation invariants) - 4. root tag == package.json version - 5. resolve and record five exact candidate outcomes - 6. publish only new exact versions to @next - └── prepublishOnly runs before each npm publication +```mermaid +flowchart TD + Commit["git commit"] --> Precommit["verify:pre-commit"] + Push["git push"] --> Prepush["verify:pre-push = verify:release-gate"] + PR["Pull request"] --> Lint["Markdown + workflow schema lint"] + Lint --> Tests["CLI tests: Node 18/20/22/24
Coverage thresholds: Node 24"] + Lint --> Bootstrap["Native OpenClaw bootstrap"] + PR --> Artifacts["Bundle / offline / pack-install smoke"] + PR --> Keychain["Native credential checks
Relevant source/test/config changes"] + Release["Release / tag-bound dispatch"] --> Gate["verify:release-gate"] + Gate --> Regression["Full npm test on exact release source"] + Regression --> Validate["verify:release + root version/tag"] + Validate --> Next["Record exact outcomes
Publish new versions to next"] ``` +`verify:pre-commit` builds and runs version/Codex regressions plus workspace +checks. `verify:pre-push` delegates to the release gate, including installed +package smokes. Publication additionally runs the complete root CLI suite; +passing PR checks are not a substitute for testing the exact release source. + +CI covers Node 18/20/22/24. Node 24 runs `npm run test:coverage` and uploads +the report; other matrix entries run `npm test`. Existing coverage thresholds +remain blocking. All repository Markdown is checked with `npm run lint:md`. +Workflow schemas are validated with pinned +[check-jsonschema 0.39.0](https://pypi.org/project/check-jsonschema/0.39.0/) +and its bundled `vendor.github-workflows` schema, including `concurrency.queue`. +No floating remote schema or ignored validation error is required. + +The credential matrix runs `npm run test:account-lifecycle` and then +`npm run smoke:keychain` on Linux, macOS, and Windows. The latter is restricted +to isolated GitHub Actions runners: it requires the expected native backend, +creates a unique dummy profile, verifies replacement, deletes it in `finally`, +and verifies absence. File fallback fails this gate. Linux shares the unlocked +D-Bus session; macOS temporarily changes and then restores the default keychain. +It uses no cloud credentials or device calls. The regression suite's mocked +backend tests are not evidence that native OS storage works. + +The separate, manually dispatched hardware smoke remains opt-in. Its Bash +pipelines use `pipefail`; `jq -e` requires the expected JSON result shapes. +Empty history is valid, but failed CLI commands or error envelopes fail the run. + The pre-publish artifact gate runs `scripts/smoke-pack-install.mjs`, which: @@ -122,7 +137,11 @@ The checkout and all five package versions come from that tag, not the workflow dispatcher commit. The outcome artifact records `source.tag` and `source.revision`; the downstream source job verifies the exact GitHub ref, dereferences annotated tags, and rejects missing metadata or a changed target. -Artifact, host, and promotion jobs all check out that verified revision. +Artifact and required-host jobs check out that verified candidate revision. +Promotion instead checks out `github.workflow_sha`, the commit containing its +workflow definition, so its tooling and dependencies enforce the current +promotion policy even for a historical candidate. This does not change the +candidate source or exact-version evidence binding. The npm provenance workflow reference identifies the fixed dispatcher workflow; the explicit source binding records the separately checked-out release code. @@ -198,6 +217,31 @@ outcomes and applies `npm dist-tag add latest` only to entries marked `published`. The job refuses to promote when artifact, exact-candidate, or required-host readonly evidence is absent or failed. +Publication runs share the `npm-candidate-publication` concurrency group; +promotion jobs share `npm-latest-promotion`. Both use `cancel-in-progress: false` +and [`queue: max`](https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/control-workflow-concurrency#example-queueing-multiple-pending-runs), +preserving up to 100 pending runs instead of replacing the previous pending +release. Ordinary PR CI cancels superseded runs. + +Before any tag write, promotion reads every newly published candidate's tags +with `npm view @ dist-tags --json`. Registry errors, +invalid SemVer metadata, or any candidate older than its current `latest` +block the whole promotion before writes begin. A missing `latest` or an equal +version is valid; independently `already-published` entries remain untouched. +This also prevents a slower, older candidate from undoing a newer promotion. +Npm tag writes across packages are not atomic, and these concurrency groups +do not lock external publishers; a registry write failure can still require +the recovery procedure above. + +## Repository guardrails + +Recommended repository settings: protect `main`, require pull requests, and +require the always-scheduled Markdown, workflow-schema, and Node test checks. +Do not require path-filtered credential jobs for every PR: documentation-only +changes would otherwise wait for checks that are never scheduled. +Workflow files do not enable branch protection; repository settings must be +configured separately. + ## Invariants Changes to the release pipeline must preserve these invariants: @@ -232,11 +276,11 @@ Changes to the release pipeline must preserve these invariants: 7. **`bundle-smoke` must stay blocking and matrixed.** Because the bundle is the publish source, it has to start cleanly on every Node version the - package supports (`engines.node >= 18`). The job runs `npm run build + + package currently tests (`engines.node >= 18`). The job runs `npm run build + shebang count + node --check + --version + bundle size test` on Node - 18/20/22. Adding a new supported Node version means adding it to the - matrix; making the job advisory again means end-users on some supported - Node version can install a broken CLI without CI catching it. + 18/20/22/24. Adding another supported LTS line means adding it to the + matrix; making the job advisory again can let users install a broken CLI + without CI catching it. ## Related tests @@ -246,3 +290,10 @@ Changes to the release pipeline must preserve these invariants: size budget). - `scripts/smoke-pack-install.mjs` — the end-to-end install smoke used by both the `pre-push` hook and the CI / publish workflows. +- `tests/build/release-candidate-promotion.test.ts` — real npm against a local + registry fixture: first promotion, equal/newer versions, stale multi-package + candidates, prerelease ordering, malformed metadata, and registry failures. +- `tests/build/keychain-smoke.test.ts` — isolated command fixtures verify smoke + cleanup, replacement, and rejection of fallback or corrupt reads. +- `scripts/smoke-keychain.mjs` — actual native credential lifecycle in the + three-OS CI matrix; local fixtures do not prove those OS jobs ran. diff --git a/package-lock.json b/package-lock.json index 63b9b8f2..2abd5d89 100644 --- a/package-lock.json +++ b/package-lock.json @@ -36,6 +36,7 @@ "esbuild": "^0.28.0", "js-yaml": "^4.1.1", "markdownlint-cli": "^0.48.0", + "semver": "7.7.4", "tsx": "^4.19.2", "typescript": "^5.7.3", "uuid": "^11.0.5", diff --git a/package.json b/package.json index 33c740db..efba4864 100644 --- a/package.json +++ b/package.json @@ -59,7 +59,9 @@ "smoke:gemini-extension-lint": "node scripts/smoke-gemini-extension-lint.mjs", "smoke:release-host": "node scripts/smoke-release-host.mjs", "smoke:openclaw-bootstrap": "node scripts/smoke-openclaw-bootstrap.mjs", + "smoke:keychain": "node --import tsx scripts/smoke-keychain.mjs", "test": "vitest run", + "test:account-lifecycle": "vitest run tests/credentials tests/install tests/devices/cache-scoping.test.ts tests/devices/account-cache-lifecycle.test.ts tests/lib/idempotency.test.ts tests/lib/request-context.test.ts tests/commands/auth.test.ts tests/commands/config.test.ts tests/commands/mcp-profile-http.test.ts tests/commands/mcp-safety-lifecycle.test.ts", "test:workspaces": "npm test --workspaces --if-present", "test:all": "npm test && npm run test:workspaces", "test:watch": "vitest", @@ -92,6 +94,7 @@ "esbuild": "^0.28.0", "js-yaml": "^4.1.1", "markdownlint-cli": "^0.48.0", + "semver": "7.7.4", "tsx": "^4.19.2", "typescript": "^5.7.3", "uuid": "^11.0.5", diff --git a/scripts/release-candidate.mjs b/scripts/release-candidate.mjs index c9b8ed7c..0eb80657 100644 --- a/scripts/release-candidate.mjs +++ b/scripts/release-candidate.mjs @@ -241,7 +241,7 @@ function createGates(args) { writeJson(required(args, "gates"), gates); } -function promote(args) { +async function promote(args) { if (!process.env.NODE_AUTH_TOKEN) fail('NPM authentication is required to promote a release candidate'); const outcomes = readOutcomes(required(args, 'outcomes')); const gates = readGates(required(args, 'gates')); @@ -259,6 +259,23 @@ function promote(args) { } } if (blocked.length > 0) fail(`Promotion blocked: ${blocked.join(', ')}`); + // Other outcome commands stay dependency-free; only promotion needs SemVer. + const { default: semver } = await import('semver'); + // Preflight every tag before the first write so a stale plugin cannot leave + // a partially promoted candidate. The workflow serializes this whole job. + for (const item of outcomes.packages) { + if (item.outcome !== 'published') continue; + const result = runNpm(['view', candidateKey(item.name, item.version), 'dist-tags', '--json']); + if (result.status !== 0) fail(`Could not read current dist-tags for ${item.name}`); + const tags = JSON.parse(result.stdout); + if (!tags || typeof tags !== 'object' || Array.isArray(tags) || + !semver.valid(item.version) || (tags.latest !== undefined && !semver.valid(tags.latest))) { + fail(`Invalid version metadata for ${item.name}`); + } + if (tags.latest !== undefined && semver.lt(item.version, tags.latest)) { + fail(`Refusing to move ${item.name} latest backward from ${tags.latest} to ${item.version}`); + } + } const summary = { published: [], alreadyPublished: [] }; for (const item of outcomes.packages) { const candidate = candidateKey(item.name, item.version); @@ -283,7 +300,7 @@ try { else if (command === 'candidate') candidate(args); else if (command === 'record-gate') recordGate(args); else if (command === 'create-gates') createGates(args); - else if (command === 'promote') promote(args); + else if (command === 'promote') await promote(args); else fail(`Unknown command: ${command ?? ''}`); } catch (error) { process.stderr.write(`release-candidate: ${error instanceof Error ? error.message : String(error)}\n`); diff --git a/scripts/smoke-keychain.mjs b/scripts/smoke-keychain.mjs new file mode 100755 index 00000000..db3b3d86 --- /dev/null +++ b/scripts/smoke-keychain.mjs @@ -0,0 +1,26 @@ +#!/usr/bin/env node +import assert from 'node:assert/strict'; +import { randomUUID } from 'node:crypto'; +import { selectCredentialStore } from '../src/credentials/keychain.ts'; + +if (process.env.GITHUB_ACTIONS !== 'true') { + throw new Error('Native keychain smoke requires an isolated GitHub Actions runner.'); +} +const expected = { linux: 'secret-service', darwin: 'keychain', win32: 'credman' }[process.platform]; +assert.ok(expected, `Unsupported keychain smoke platform: ${process.platform}`); +const store = await selectCredentialStore(); +assert.equal(store.name, expected, 'Native keychain is required; file fallback is not a passing smoke.'); +const profile = `ci-${randomUUID()}`; +assert.equal(await store.get(profile), null); +try { + const initial = { token: 'ci-dummy-token-A', secret: 'ci-dummy-secret-A' }; + await store.set(profile, initial); + assert.deepEqual(await store.get(profile), initial); + const replacement = { token: 'ci-dummy-token-B', secret: 'ci-dummy-secret-B' }; + await store.set(profile, replacement); + assert.deepEqual(await store.get(profile), replacement); +} finally { + await store.delete(profile); +} +assert.equal(await store.get(profile), null); +console.log(JSON.stringify({ backend: store.name, checks: ['create', 'replace', 'delete'] })); diff --git a/tests/build/keychain-smoke.test.ts b/tests/build/keychain-smoke.test.ts new file mode 100644 index 00000000..029832ce --- /dev/null +++ b/tests/build/keychain-smoke.test.ts @@ -0,0 +1,66 @@ +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { afterEach, describe, expect, it } from 'vitest'; + +const directories: string[] = []; +const untouched = { 'default:token': 'unrelated-token', 'default:secret': 'unrelated-secret' }; + +afterEach(() => { + for (const directory of directories.splice(0)) rmSync(directory, { recursive: true, force: true }); +}); + +function runSmoke(mode = 'healthy') { + const directory = mkdtempSync(path.join(os.tmpdir(), 'switchbot-keychain-smoke-')); + directories.push(directory); + const bin = path.join(directory, 'bin'); + mkdirSync(bin); + const registry = path.join(directory, 'registry.json'); + writeFileSync(registry, JSON.stringify(untouched)); + const which = path.join(bin, 'which'); + writeFileSync(which, `#!${process.execPath}\nif (process.env.KEYCHAIN_FIXTURE_MODE === 'fallback') process.exit(1);\nconsole.log(${JSON.stringify(path.join(bin, 'secret-tool'))});\n`); + chmodSync(which, 0o755); + const secretTool = path.join(bin, 'secret-tool'); + writeFileSync(secretTool, `#!${process.execPath} +const fs = require('node:fs'); +const args = process.argv.slice(2); +const file = ${JSON.stringify(registry)}; +const values = JSON.parse(fs.readFileSync(file, 'utf8')); +const account = args[args.indexOf('account') + 1]; +switch (args[0]) { + case 'search': break; + case 'lookup': + if (!(account in values)) process.exit(1); + process.stdout.write(process.env.KEYCHAIN_FIXTURE_MODE === 'corrupt-read' ? 'corrupted-value' : values[account]); + break; + case 'store': values[account] = fs.readFileSync(0, 'utf8'); fs.writeFileSync(file, JSON.stringify(values)); break; + case 'clear': delete values[account]; fs.writeFileSync(file, JSON.stringify(values)); break; + default: process.exit(90); +} +`); + chmodSync(secretTool, 0o755); + const result = spawnSync(process.execPath, ['--import', 'tsx', 'scripts/smoke-keychain.mjs'], { + cwd: process.cwd(), encoding: 'utf8', timeout: 20_000, + env: { ...process.env, HOME: directory, USERPROFILE: directory, XDG_CONFIG_HOME: directory, + GITHUB_ACTIONS: 'true', KEYCHAIN_FIXTURE_MODE: mode, PATH: bin + path.delimiter + process.env.PATH }, + }); + return { result, remaining: JSON.parse(readFileSync(registry, 'utf8')) }; +} + +// The production smoke runs native commands on all three runner OSes. This +// regression fixture implements only the external Linux secret-tool boundary. +describe.skipIf(process.platform !== 'linux')('native keychain smoke gate', () => { + it('exercises replacement and cleanup without modifying other profiles', () => { + const smoke = runSmoke(); + expect(smoke.result.status, smoke.result.stderr).toBe(0); + expect(JSON.parse(smoke.result.stdout)).toEqual({ backend: 'secret-service', checks: ['create', 'replace', 'delete'] }); + expect(smoke.remaining).toEqual(untouched); + }); + + it.each(['fallback', 'corrupt-read'])('rejects %s without leaving dummy credentials behind', mode => { + const smoke = runSmoke(mode); + expect(smoke.result.status).toBe(1); + expect(smoke.remaining).toEqual(untouched); + }); +}); diff --git a/tests/build/release-candidate-promotion.test.ts b/tests/build/release-candidate-promotion.test.ts index 144e0929..7150863e 100644 --- a/tests/build/release-candidate-promotion.test.ts +++ b/tests/build/release-candidate-promotion.test.ts @@ -1,7 +1,9 @@ import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import { spawnSync } from 'node:child_process'; +import { spawn, spawnSync } from 'node:child_process'; +import { createServer } from 'node:http'; +import { once } from 'node:events'; import { afterEach, describe, expect, it } from 'vitest'; const PACKAGE_OUTCOMES = [ @@ -18,7 +20,127 @@ afterEach(() => { for (const directory of tempDirs.splice(0)) rmSync(directory, { recursive: true, force: true }); }); +async function promoteWithRegistry( + packages: typeof PACKAGE_OUTCOMES, + registry: Record, + registryError?: 'unavailable' | 'malformed', +) { + const directory = mkdtempSync(path.join(os.tmpdir(), 'switchbot-promotion-registry-')); + tempDirs.push(directory); + const outcomes = path.join(directory, 'outcomes.json'); + const gates = path.join(directory, 'gates.json'); + const state = structuredClone(registry); + writeFileSync(outcomes, JSON.stringify({ schemaVersion: 1, packages })); + writeFileSync(gates, JSON.stringify({ candidates: Object.fromEntries(packages.map(item => [ + `${item.name}@${item.version}`, { artifact: 'passed', 'exact-candidate': 'passed', 'required-host': 'passed' }, + ])) })); + const server = createServer((request, response) => { + response.setHeader('Content-Type', 'application/json'); + const url = decodeURIComponent(request.url ?? '/'); + if (request.method === 'GET') { + if (registryError === 'unavailable') { response.writeHead(503); response.end('{}'); return; } + if (registryError === 'malformed') { response.end('invalid-json'); return; } + const name = url.startsWith('/-/package/') ? url.slice('/-/package/'.length, -'/dist-tags'.length) : url.slice(1); + const candidate = packages.find(item => item.name === name); + if (!candidate) { response.writeHead(404); response.end('{}'); return; } + const tags = { next: candidate.version, ...state[name] }; + const versions = new Set([candidate.version, ...(state[name]?.latest ? [state[name].latest] : [])]); + response.end(JSON.stringify(url.startsWith('/-/package/') ? tags : { + name, 'dist-tags': tags, versions: Object.fromEntries([...versions].map(version => [version, { name, version }])), + })); + } else if (request.method === 'PUT' && url.endsWith('/dist-tags/latest')) { + const name = url.slice('/-/package/'.length, -'/dist-tags/latest'.length); + let body = ''; + request.on('data', chunk => { body += chunk; }); + request.on('end', () => { + state[name] = { ...state[name], latest: JSON.parse(body) }; + response.end('{}'); + }); + } else { + response.writeHead(404); + response.end('{}'); + } + }); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + const address = server.address(); + if (!address || typeof address === 'string') throw new Error('Registry fixture did not bind TCP'); + try { + const child = spawn(process.execPath, [ + 'scripts/release-candidate.mjs', 'promote', '--outcomes', outcomes, '--gates', gates, + ], { cwd: process.cwd(), env: { + ...process.env, NODE_AUTH_TOKEN: 'offline-fixture', + NPM_CONFIG_REGISTRY: `http://127.0.0.1:${address.port}`, + NPM_CONFIG_USERCONFIG: path.join(directory, 'isolated.npmrc'), + NPM_CONFIG_CACHE: path.join(directory, 'npm-cache'), NPM_CONFIG_FETCH_RETRIES: '0', + } }); + let stdout = ''; + let stderr = ''; + child.stdout.on('data', chunk => { stdout += chunk; }); + child.stderr.on('data', chunk => { stderr += chunk; }); + const [status] = await once(child, 'close'); + return { result: { status, stdout, stderr }, registry: state }; + } finally { + server.closeAllConnections(); + await new Promise(resolve => server.close(() => resolve())); + } +} + describe('release candidate promotion', () => { + it('rejects a stale package before changing any candidate latest tags', async () => { + const registry = { + '@switchbot/openapi-cli': { latest: '3.8.1' }, + '@switchbot/codex-plugin': { latest: '0.3.0' }, + }; + const candidate = PACKAGE_OUTCOMES.map(item => item.name === '@switchbot/codex-plugin' + ? { ...item, outcome: 'published' } : item); + const promotion = await promoteWithRegistry(candidate, registry); + expect(promotion.result.status).toBe(1); + expect(promotion.registry).toEqual(registry); + }); + + it.each([ + [undefined, '3.9.0', true], + ['3.9.0', '3.9.0', true], + ['3.9.0', '3.10.0', true], + ['3.9.0-beta.10', '3.9.0-beta.2', false], + ['3.9.0', '3.9.0-beta.1', false], + ['invalid', '3.9.0', false], + ['3.9.0', 'invalid', false], + ] as const)('guards latest=%s against candidate=%s', async (latest, version, allowed) => { + const registry = { '@switchbot/openapi-cli': latest === undefined ? {} : { latest } }; + const packages = PACKAGE_OUTCOMES.map(item => item.name === '@switchbot/openapi-cli' ? { ...item, version } : item); + const promotion = await promoteWithRegistry(packages, registry); + expect(promotion.result.status, promotion.result.stderr).toBe(allowed ? 0 : 1); + expect(promotion.registry).toEqual(allowed ? { '@switchbot/openapi-cli': { latest: version } } : registry); + }); + + it('promotes a newer CLI while leaving already-published plugin tags unchanged', async () => { + const promotion = await promoteWithRegistry(PACKAGE_OUTCOMES, { + '@switchbot/openapi-cli': { latest: '3.8.1' }, + '@switchbot/codex-plugin': { latest: '0.3.0' }, + }); + expect(promotion.result.status, promotion.result.stderr).toBe(0); + expect(promotion.registry).toEqual({ + '@switchbot/openapi-cli': { latest: '3.9.0' }, + '@switchbot/codex-plugin': { latest: '0.3.0' }, + }); + expect(JSON.parse(promotion.result.stdout)).toEqual({ + published: ['@switchbot/openapi-cli@3.9.0'], + alreadyPublished: [ + '@switchbot/codex-plugin@0.2.0', '@switchbot/openclaw-skill@0.2.0', + '@switchbot/claude-code-plugin@0.2.0', '@switchbot/gemini-extension@0.2.0', + ], + }); + }); + + it.each(['unavailable', 'malformed'] as const)('blocks promotion when registry metadata is %s', async error => { + const registry = { '@switchbot/openapi-cli': { latest: '3.8.1' } }; + const promotion = await promoteWithRegistry(PACKAGE_OUTCOMES, registry, error); + expect(promotion.result.status).toBe(1); + expect(promotion.registry).toEqual(registry); + }); + it('rejects passed host evidence from a different candidate', () => { const directory = mkdtempSync(path.join(os.tmpdir(), 'switchbot-release-evidence-')); tempDirs.push(directory); @@ -164,23 +286,5 @@ describe('release candidate promotion', () => { const failedPlugin = runPromotion(required); expect(failedPlugin.status).toBe(1); expect(() => readFileSync(npmLog, 'utf8')).toThrow(); - writeFileSync(outcomes, JSON.stringify({ schemaVersion: 1, packages: PACKAGE_OUTCOMES })); - - const promoted = runPromotion({ - ...required, - '@switchbot/openapi-cli@3.9.0:exact-candidate': 'passed', - '@switchbot/openapi-cli@3.9.0:required-host': 'passed', - }); - expect(promoted.status).toBe(0); - expect(JSON.parse(promoted.stdout)).toMatchObject({ - published: ['@switchbot/openapi-cli@3.9.0'], - alreadyPublished: [ - '@switchbot/codex-plugin@0.2.0', - '@switchbot/openclaw-skill@0.2.0', - '@switchbot/claude-code-plugin@0.2.0', - '@switchbot/gemini-extension@0.2.0', - ], - }); - expect(readFileSync(npmLog, 'utf8')).toBe('dist-tag add @switchbot/openapi-cli@3.9.0 latest\n'); }); });